Compare commits

..
30 Commits
Author SHA1 Message Date
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
Denozordec 63c0fc6506 fix(ix): ограничивать размер сегмента TCP для туннелей VPS
Docker images / prepare-release (push) Successful in 10s
Docker images / backend-test (push) Successful in 10m38s
Docker images / frontend-image (push) Successful in 2m14s
Docker images / updater-image (push) Successful in 40s
Docker images / netflow-agent-image (push) Successful in 35s
Docker images / backend-image (push) Successful in 2m2s
Docker images / publish-release (push) Successful in 12s
Docker images / notify-webhook (push) Successful in 2s
2026-11-25 19:29:56 +07:00
Denozordec 682d6c8d55 fix(mcp): разрешить настройку размера сегмента TCP
Docker images / prepare-release (push) Successful in 9s
Docker images / backend-test (push) Successful in 10m27s
Docker images / backend-image (push) Successful in 2m19s
Docker images / frontend-image (push) Successful in 2m16s
Docker images / updater-image (push) Successful in 38s
Docker images / netflow-agent-image (push) Successful in 45s
Docker images / notify-webhook (push) Successful in 2s
Docker images / publish-release (push) Successful in 10s
2026-11-25 13:35:20 +07:00
Denozordec a41c70b104 feat(ix): добавить одноразовые ссылки импорта конфигураций
Docker images / prepare-release (push) Successful in 9s
Docker images / updater-image (push) Successful in 42s
Docker images / netflow-agent-image (push) Successful in 36s
Docker images / backend-test (push) Successful in 9m43s
Docker images / backend-image (push) Successful in 1m59s
Docker images / frontend-image (push) Successful in 15m47s
Docker images / notify-webhook (push) Successful in 0s
Docker images / publish-release (push) Successful in 10s
2026-11-25 11:46:51 +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
Denozordec 01779d7ee6 fix(scheduler): дождаться освобождения блокировки перед сбором метрик
Docker images / prepare-release (push) Successful in 9s
Docker images / updater-image (push) Successful in 3m22s
Docker images / frontend-image (push) Successful in 3m26s
Docker images / netflow-agent-image (push) Successful in 3m21s
Docker images / backend-test (push) Successful in 25m38s
Docker images / backend-image (push) Successful in 20m27s
Docker images / notify-webhook (push) Successful in 1s
Docker images / publish-release (push) Successful in 9s
2026-11-24 22:01:12 +07:00
Denozordec 1b927dcf68 fix(traffic): показывать показатели интерфейсов при неполных замерах
Docker images / prepare-release (push) Successful in 9s
Docker images / backend-test (push) Successful in 2s
Docker images / backend-image (push) Successful in 15s
Docker images / updater-image (push) Successful in 39s
Docker images / netflow-agent-image (push) Successful in 1m18s
Docker images / notify-webhook (push) Successful in 2s
Docker images / publish-release (push) Successful in 29s
Docker images / frontend-image (push) Successful in 6m50s
2026-11-24 16:37:50 +07:00
Denozordec af82497f20 fix(netflow): исправить учёт трафика по выходным узлам на карте сети
Docker images / prepare-release (push) Successful in 12s
Docker images / backend-test (push) Successful in 10m33s
Docker images / updater-image (push) Successful in 39s
Docker images / netflow-agent-image (push) Successful in 32s
Docker images / backend-image (push) Successful in 2m0s
Docker images / frontend-image (push) Successful in 7m41s
Docker images / publish-release (push) Successful in 33s
Docker images / notify-webhook (push) Successful in 1m55s
2026-11-24 15:41:44 +07:00
Denozordec ca65969728 fix(netflow): исправить подсчёт трафика туннелей на карте сети
Docker images / prepare-release (push) Successful in 11s
Docker images / backend-test (push) Successful in 10m26s
Docker images / frontend-image (push) Successful in 2m15s
Docker images / updater-image (push) Successful in 39s
Docker images / netflow-agent-image (push) Successful in 35s
Docker images / backend-image (push) Successful in 2m7s
Docker images / publish-release (push) Successful in 12s
Docker images / notify-webhook (push) Successful in 2s
2026-11-24 13:59:48 +07:00
Denozordec ee6fd675ac fix(routing): устранить конфликты чтения фильтров и маршрутов
Docker images / prepare-release (push) Successful in 10s
Docker images / backend-test (push) Successful in 10m25s
Docker images / frontend-image (push) Successful in 3m18s
Docker images / updater-image (push) Successful in 41s
Docker images / netflow-agent-image (push) Successful in 32s
Docker images / backend-image (push) Successful in 2m48s
Docker images / publish-release (push) Successful in 10s
Docker images / notify-webhook (push) Successful in 1s
2026-11-24 12:46:31 +07:00
Denozordec 5a46594ec9 fix(ix): объединить туннели по клиентам и показать счётчики трафика
Docker images / prepare-release (push) Successful in 11s
Docker images / backend-test (push) Successful in 10m24s
Docker images / backend-image (push) Successful in 2m0s
Docker images / frontend-image (push) Successful in 2m15s
Docker images / updater-image (push) Successful in 39s
Docker images / netflow-agent-image (push) Successful in 32s
Docker images / notify-webhook (push) Successful in 2s
Docker images / publish-release (push) Successful in 10s
2026-11-24 10:48:21 +07:00
Denozordec 31f75a8eed feat(ix): включать действующие интерфейсы в группы резервирования
Docker images / prepare-release (push) Successful in 12s
Docker images / backend-test (push) Successful in 11m40s
Docker images / frontend-image (push) Successful in 3m56s
Docker images / updater-image (push) Successful in 2m38s
Docker images / netflow-agent-image (push) Successful in 33s
Docker images / backend-image (push) Successful in 5m2s
Docker images / publish-release (push) Successful in 11s
Docker images / notify-webhook (push) Successful in 2s
2026-11-24 00:56:00 +07:00
Denozordec 2a759ae5e5 fix(ci): зарегистрировать операции оператора и запускать тесты резервирования
Docker images / prepare-release (push) Successful in 11s
Docker images / backend-test (push) Canceled after 3m3s
Docker images / backend-image (push) Canceled after 0s
Docker images / frontend-image (push) Canceled after 0s
Docker images / updater-image (push) Canceled after 0s
Docker images / netflow-agent-image (push) Canceled after 0s
Docker images / publish-release (push) Canceled after 0s
Docker images / notify-webhook (push) Canceled after 0s
2026-11-24 00:48:04 +07:00
Denozordec fad89c7059 fix(ci): учесть маршруты групп туннелей в реестре покрытия
Docker images / prepare-release (push) Successful in 10s
Docker images / backend-test (push) Failing after 4m9s
Docker images / backend-image (push) Skipped
Docker images / frontend-image (push) Successful in 4m7s
Docker images / updater-image (push) Successful in 2m15s
Docker images / netflow-agent-image (push) Successful in 35s
Docker images / publish-release (push) Skipped
Docker images / notify-webhook (push) Skipped
2026-11-24 00:38:57 +07:00
Denozordec 350ae34862 feat(ix): добавить управление группами туннелей для резервирования и балансировки
Docker images / prepare-release (push) Successful in 11s
Docker images / backend-test (push) Failing after 4m0s
Docker images / backend-image (push) Skipped
Docker images / frontend-image (push) Successful in 3m55s
Docker images / updater-image (push) Successful in 2m11s
Docker images / netflow-agent-image (push) Successful in 37s
Docker images / publish-release (push) Skipped
Docker images / notify-webhook (push) Skipped
2026-11-24 00:29:50 +07:00
Denozordec 676be13251 fix(ix): открыть добавление протокола из формы клиента
Docker images / prepare-release (push) Successful in 12s
Docker images / backend-test (push) Successful in 10m31s
Docker images / frontend-image (push) Successful in 3m20s
Docker images / updater-image (push) Successful in 1m56s
Docker images / netflow-agent-image (push) Successful in 34s
Docker images / backend-image (push) Successful in 3m4s
Docker images / publish-release (push) Successful in 13s
Docker images / notify-webhook (push) Successful in 2s
2026-11-23 21:48:52 +07:00
Denozordec ca1bc1ab38 feat(ix): добавить два протокола для одного клиента
Docker images / prepare-release (push) Successful in 11s
Docker images / backend-test (push) Successful in 10m29s
Docker images / frontend-image (push) Successful in 2m14s
Docker images / updater-image (push) Successful in 39s
Docker images / netflow-agent-image (push) Successful in 32s
Docker images / backend-image (push) Successful in 1m58s
Docker images / publish-release (push) Successful in 12s
Docker images / notify-webhook (push) Successful in 2s
Выдавать профиль и скрипт настройки туннеля с прямым доступом по внешнему адресу. Учитывать собственные маршруты возврата при применении черновика.
2026-11-23 18:48:10 +07:00
Denozordec d9f623ccda 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 2m9s
Docker images / updater-image (push) Successful in 40s
Docker images / netflow-agent-image (push) Successful in 31s
Docker images / backend-image (push) Successful in 1m58s
Docker images / publish-release (push) Successful in 12s
Docker images / notify-webhook (push) Successful in 2s
2026-11-23 14:39:40 +07:00
Denozordec 9951035448 feat(ix): упростить настройку и добавить выдачу конфигов 2026-11-23 14:39:40 +07:00
147 changed files with 7962 additions and 4016 deletions

No files matched your search

+394 -306
View File
@@ -1,349 +1,437 @@
"use client" "use client"
import { useState } from "react" import { useEffect, useMemo, useState } from "react"
import { Button } from "@/components/ui/button"
import Link from "next/link" import Link from "next/link"
import { import {
ActivityIcon,
BellIcon,
CableIcon, CableIcon,
FilterIcon, ChartColumnIcon,
GitMergeIcon, CircleAlertIcon,
HardDriveIcon,
HeartPulseIcon, HeartPulseIcon,
MapIcon, LayoutDashboardIcon,
ServerIcon, ServerIcon,
ShieldIcon, SlidersHorizontalIcon,
TableIcon,
} from "lucide-react" } 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 { PageHeader } from "@/components/page-header"
import { OpsPanel } from "@/components/ops-panel" import { PageTitle } from "@/components/page-title"
import { KpiStatGrid } from "@/components/reui-kit/kpi-stat-grid" import { DataFreshness } from "@/components/data-freshness"
import { QuickActionGrid } from "@/components/reui-kit/quick-action-grid" import { EmptyState } from "@/components/empty-state"
import { AttentionQueue } from "@/components/reui-kit/attention-queue" 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 { TrafficRxTxChart } from "@/components/reui-kit/traffic-rx-tx-chart"
import { LatencyChart } from "@/components/dashboard/latency-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 { 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 { 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 { 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" 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 { function fmtIntRu(n: number): string {
return n.toLocaleString("ru-RU") return n.toLocaleString("ru-RU")
} }
function AttentionRows({ rows }: { rows: AttentionRow[] }) { function averageSeries(series: Record<string, (number | null)[]>): number[] {
const [expanded,setExpanded]=useState(false) const rows = Object.values(series)
const [visible,setVisible]=useState(55) const length = Math.max(0, ...rows.map((values) => values.length))
function renderRow(row: AttentionRow) { const out: number[] = []
return ( for (let i = 0; i < length; i++) {
<Link const values = rows.map((row) => row[i]).filter((v): v is number => typeof v === "number" && Number.isFinite(v))
key={row.id} if (values.length) out.push(values.reduce((sum, v) => sum + v, 0) / values.length)
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>
)
} }
return out
}
return ( function toGridRows(rows: AttentionRow[], kind: AttentionGridRow["kind"]): AttentionGridRow[] {
<div className="flex flex-col gap-0.5"> return rows.map((row) => ({
{rows.slice(0, 5).map(renderRow)} id: row.id,
{rows.length > 5 && ( title: row.title,
<details onToggle={event=>{setExpanded(event.currentTarget.open);if(!event.currentTarget.open)setVisible(55)}}> kind,
<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> hint: row.hint,
{expanded && rows.slice(5,visible).map(renderRow)} href: row.href,
{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>} tone: row.tone === "destructive" ? "er" : "wn",
</details> confirmed: row.hint !== "Статус неизвестен",
)} }))
</div>
)
} }
export default function DashboardPage() { export default function DashboardPage() {
const dash = useDashboardLive() 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 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 ( return (
<div className="flex h-full flex-col"> <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-1 overflow-y-auto">
<div className="flex flex-col gap-4 px-4 py-4 md:gap-6 md:px-6 md:py-5"> <div className="flex flex-col gap-6 px-4 pt-5 pb-10 md:px-7 md:pt-6">
{dash.isLive && <DashboardDataStatus sources={dash.sources} refreshing={dash.refreshing} onRefresh={dash.retry} />} <PageTitle
icon={<LayoutDashboardIcon />}
<KpiStatGrid title="Дашборд"
aria-label="Сводка дашборда" description="Здоровье сети: индекс, события за период, Internet path, пробы и источники"
isLoading={dash.loading} actions={
items={[ <>
{ <DropdownMenu>
id: "fleet", <DropdownMenuTrigger render={<Button type="button" variant="outline"><SlidersHorizontalIcon data-icon="inline-start" />Настроить виджеты</Button>} />
label: "Серверы онлайн", <DropdownMenuContent align="end" className="w-60">
value: dash.availability.servers ? `${dash.onlineCount} / ${dash.totalServers}` : "—", <DropdownMenuGroup>
hint: !dash.availability.servers ? "нет данных" : !dash.isLive <DropdownMenuLabel>Виджеты дашборда</DropdownMenuLabel>
? "демо" {(Object.keys(WIDGETS) as Widget[]).map((key) => (
: offline > 0 || dash.unknownServerCount > 0 || dash.degradedServerCount > 0 <DropdownMenuCheckboxItem key={key} checked={show(key)} onCheckedChange={(value) => toggle(key, !!value)}>
? [offline > 0 ? `${offline} не в сети` : null,dash.unknownServerCount > 0 ? `Статус неизвестен: ${dash.unknownServerCount}` : null,dash.degradedServerCount > 0 ? `Ухудшение: ${dash.degradedServerCount}` : null].filter(Boolean).join(" · ") {WIDGETS[key]}
: dash.totalServers > 0 </DropdownMenuCheckboxItem>
? "все в сети" ))}
: "нет серверов", </DropdownMenuGroup>
href: "/servers", </DropdownMenuContent>
icon: <ServerIcon />, </DropdownMenu>
iconClassName: "text-muted-foreground", <Button type="button" onClick={dash.retry} disabled={dash.refreshing}>Обновить данные</Button>
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",
},
]}
/> />
<section aria-labelledby="dashboard-attention-title" className="flex min-w-0 flex-col gap-2"> <div className="flex flex-col gap-5">
<h2 id="dashboard-attention-title" className="text-sm font-semibold">Требует внимания</h2> {failedSources.length > 0 ? (
<AttentionQueue <Alert variant="warning">
className="lg:grid-cols-3" <CircleAlertIcon />
columns={[ <AlertTitle>Не все источники доступны.</AlertTitle>
{ <AlertDescription>
id: "nodes", Последний успешный снимок; не все источники обновлены. Не обновлены: {failedSources.map((row) => row.name).join(", ")}. Проверьте состояние источников ниже.
title: "Серверы", </AlertDescription>
icon: ServerIcon, <AlertAction>
count: dash.attentionServers.length, <Button type="button" size="sm" variant="outline" onClick={() => setTab("src")}>Объяснить</Button>
countVariant: "warning-light", </AlertAction>
emptyTitle: dash.reliable.servers ? (dash.totalServers > 0 ? "Серверы без проблем" : "Нет серверов") : "Состояние не подтверждено", </Alert>
emptyDescription: dash.reliable.servers ? "Нет включённых серверов с ошибками доступности." : "Проверьте состояние источников выше.", ) : null}
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="grid grid-cols-1 gap-4 lg:grid-cols-[2fr_1fr]"> {show("cap") ? (
<OpsPanel <CapacityGrid
title="Задержка до серверов" label="Ёмкость сети"
description={ items={[
dash.latency.kind === "mock" || dash.latency.kind === "live" {
? dash.latency.subtitle id: "fleet",
: dash.latency.kind === "loading" title: "Серверы онлайн",
? "Загрузка…" caption: serverCaption,
: "Нет серии RTT" value: dash.availability.servers ? dash.onlineCount : null,
} total: dash.availability.servers ? dash.totalServers : null,
contentClassName="px-3 pb-3" tone: serverTrouble ? "wn" : "ok",
> icon: <ServerIcon />,
{dash.latency.kind === "loading" && ( href: "/servers",
<div className="bg-muted/50 h-[220px] w-full animate-pulse rounded-md" /> },
)} {
{dash.latency.kind === "empty" && ( id: "overlay",
<p className="text-muted-foreground px-4 py-10 text-center text-sm">{dash.latency.message}</p> title: "Туннели работают",
)} caption: !dash.availability.overlay ? "не все источники доступны" : !dash.reliable.overlay ? "Последний успешный снимок; не все источники обновлены" : dash.overlay.total > 0 ? `GRE · WireGuard · VXLAN · не работают: ${dash.overlay.down}` : "нет туннелей",
{(dash.latency.kind === "mock" || dash.latency.kind === "live") && ( value: dash.availability.overlay ? dash.overlay.up : null,
<LatencyChart series={dash.latency.series} labels={dash.latency.labels} /> total: dash.availability.overlay ? dash.overlay.total : null,
)} tone: dash.overlay.down > 0 ? "wn" : "ok",
</OpsPanel> icon: <CableIcon />,
href: "/gre",
<OpsPanel },
title="Последние события" {
description="Система и BGP" id: "health",
headerRight={ title: "Проверки с проблемами",
<Link href="/alerts" className={cn(buttonVariants({ variant: "ghost", size: "sm" }), "h-7 text-xs")}> caption: dash.availability.probes ? `${dash.probeDown} ошибок · ${dash.probeWarn} предупреждений${dash.unknownProbeCount > 0 ? ` · неизвестны: ${dash.unknownProbeCount}` : ""}` : "нет данных",
Все → value: dash.availability.probes && dash.unknownProbeCount === 0 ? problems : null,
</Link> total: dash.availability.probes && dash.unknownProbeCount === 0 ? dash.probeCount : null,
} tone: problems > 0 ? "er" : "ok",
> icon: <HeartPulseIcon />,
<DashboardEventsTimeline href: "/uptime",
events={dash.recentEvents} },
loading={dash.eventsLoading} ]}
error={dash.eventsError}
/> />
</OpsPanel> ) : null}
</div>
<div> {show("spark") ? (
<OpsPanel <SparkKpiGrid
title="Пропускная способность" label="Показатели сети"
description={dash.traffic?.demo ? "Суммарный RX / TX · демо" : "Суммарная история RX / TX · 1 ч; значения — последний измеренный снимок"} items={[
headerRight={<Link href="/traffic" className={cn(buttonVariants({ variant: "outline", size: "sm" }), "h-7 text-xs")}>Трафик →</Link>} {
contentClassName="px-3 pb-3" id: "bgp",
> title: "Префиксы BGP",
{dash.loading && !dash.traffic ? ( value: dash.bgp?.prefixSum != null ? fmtIntRu(dash.bgp.prefixSum) : "—",
<div className="bg-muted/50 h-[220px] w-full animate-pulse rounded-md" /> footnote: dash.bgp ? `Сессий установлено: ${dash.bgp.establishedCount ?? "неизвестно"}${dash.bgp.prefixSum === null ? " · префиксы неизвестны" : ""}` : "нет данных",
) : !dash.traffic ? ( href: "/bgp",
<p className="text-muted-foreground px-4 py-10 text-center text-sm"> },
Нет данных трафика за последний час.{" "} {
<Link href="/traffic" className="underline underline-offset-2"> id: "rtt",
Открыть трафик title: "Средний RTT",
</Link> value: rttNow ?? "—",
</p> unit: rttNow != null ? " мс" : undefined,
) : ( series: latencySeries,
<> delta: seriesDelta(latencySeries, "wn", "ok"),
<div className="flex flex-wrap items-center gap-3 px-2 py-3 text-xs"> footnote: "за 1 ч",
{dash.traffic.demo ? <Badge variant="outline" size="sm">демо</Badge> : !dash.traffic.observationsKnown ? <Badge variant="outline" size="sm">Измерения не подтверждены API</Badge> : null} href: "/uptime",
<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> {
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> </div>
<TrafficRxTxChart rx={dash.traffic.rx} tx={dash.traffic.tx} range="1h" embedded /> </SectionFrame>
</> </TabsContent>
)}
</OpsPanel>
<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> </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> </div>
</div> </div>
+209
View File
@@ -0,0 +1,209 @@
"use client"
import { useEffect, useState, type ReactNode } from "react"
import type { IxBondBundle, IxBondCandidate, IxBondCatalog, IxBondEdit, IxBondMode, IxSavedBond, IxSegment } from "@mmapp/contracts/internet-exchange"
import { Button } from "@/components/ui/button"
import { Checkbox } from "@/components/ui/checkbox"
import { Input } from "@/components/ui/input"
import { Textarea } from "@/components/ui/textarea"
import { Field, FieldLabel } from "@/components/ui/field"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Sheet, SheetContent, SheetDescription, SheetFooter, SheetHeader, SheetTitle } from "@/components/ui/sheet"
import { requestJson } from "@/shared/api/http-client"
import { nodeLabel, type IxNode } from "./ix-view"
import { IxExistingTransport } from "./ix-existing-transport"
import { toast } from "sonner"
import { copyIxImportLink } from "./ix-import-link"
const modes = [
{ value: "failover", label: "Основной и резервные" },
{ value: "equal", label: "Параллельно, поровну" },
{ value: "weighted", label: "Параллельно, по весам" },
] as const
type Member = IxBondEdit["members"][number]
type Ref = Pick<Member, "segmentId" | "interfaceName" | "serverId">
export type IxRowBondAction = (binding: Pick<Ref, "interfaceName" | "serverId">) => { label: string; open: () => void } | undefined
const memberKey = (m: Pick<Member, "segmentId" | "interfaceName" | "serverId">) => [m.segmentId, m.serverId, m.interfaceName].join("/")
const memberRef = ({ segmentId, serverId, appliedRevision, interfaceName }: IxBondCandidate): Member => ({ segmentId, serverId, appliedRevision, interfaceName, weight: 1 })
const modeLabel = (mode: IxBondMode) => modes.find(item => item.value === mode)?.label
export function IxClientBonds({ segmentId, segments, backendUrl, nodes, readOnly, download, live, children }: {
segmentId: string; segments: IxSegment[]; backendUrl: string; nodes: IxNode[]; readOnly: boolean; live: boolean
download: (filename: string, text: string) => void
children: (action: IxRowBondAction, catalog: IxBondCatalog, groups: (clientId: string) => ReactNode, unassigned: ReactNode) => ReactNode
}) {
const [catalog, setCatalog] = useState<IxBondCatalog>({ groups: [], candidates: [] })
const [reload, setReload] = useState(0)
const [draft, setDraft] = useState<IxBondEdit | null>(null)
const [direct, setDirect] = useState("")
const [error, setError] = useState("")
const [busy, setBusy] = useState(false)
const [remove, setRemove] = useState(false)
const [confirmedMembers, setConfirmedMembers] = useState("")
const [importing, setImporting] = useState(false)
const [initialInterface, setInitialInterface] = useState<Pick<Ref, "serverId" | "interfaceName">>()
useEffect(() => {
if (!live) return
const ctl = new AbortController()
void requestJson<IxBondCatalog>(backendUrl, "/api/ix/linux-bonds", { signal: ctl.signal })
.then(result => { if (!ctl.signal.aborted) setCatalog(result) })
.catch(e => { if (!ctl.signal.aborted) setError(e.message) })
return () => ctl.abort()
}, [backendUrl, segmentId, reload, live])
const available = new Map(catalog.candidates.map(c => [memberKey(c), c]))
for (const m of [...catalog.groups.flatMap(g => g.members), ...(draft?.members ?? [])]) {
if (!m.existing) continue
const segment = segments.find(s => s.id === m.segmentId)
available.set(memberKey(m), { ...m, ...m.existing, name: m.existing.linuxInterface, segmentName: segment?.configuration.name ?? m.segmentId,
appliedRevision: segment?.appliedRevision ?? m.appliedRevision, destinations: [...new Set(m.existing.destinations)].sort() })
}
const label = (c: IxBondCandidate) => [c.name, c.segmentName, nodeLabel(nodes, c.serverId), c.kind === "wireguard" ? "WG" : "GRE/IPsec", c.endpoint, c.interfaceName].join(" · ")
function open(group?: IxSavedBond, first?: IxBondCandidate) {
setError("")
setRemove(false)
setConfirmedMembers("")
setImporting(false)
setInitialInterface(undefined)
setDirect(group?.directCidrs.join("\n") ?? "")
setDraft(group ? {
id: group.id, revision: group.revision, name: group.name, mode: group.mode, directCidrs: group.directCidrs,
members: group.members.map(m => ({ ...m, appliedRevision: available.get(memberKey(m))?.appliedRevision ?? m.appliedRevision })),
} : { revision: 0, name: first?.name ?? "", mode: "failover", members: first ? [memberRef(first)] : [], directCidrs: [] })
}
async function perform(action: () => Promise<void>) {
if (busy || readOnly) return
setBusy(true)
setError("")
try { await action() } catch (e) { setError(e instanceof Error ? e.message : "Ошибка операции с группой") }
finally { setBusy(false) }
}
const patch = (fields: Partial<IxBondEdit>) => setDraft(old => old && { ...old, ...fields })
const ownedGroups = catalog.groups.filter(g => g.members.some(m => m.segmentId === segmentId))
const previous = catalog.groups.find(g => g.id === draft?.id)
const owner = previous?.ownerSegmentId ?? segmentId
const root = "/api/ix/segments/" + owner + "/linux-bonds"
const occupied = new Set(catalog.groups.filter(g => g.id !== draft?.id).flatMap(g => g.members.map(memberKey)))
const selected = (draft?.members ?? []).flatMap(m => available.get(memberKey(m)) ?? [])
const identity = previous?.clientId ?? selected.find(m => m.clientId)?.clientId
const first = selected[0]
const choices = catalog.candidates.filter(c => c.destinations.length && !occupied.has(memberKey(c)) && (!identity || !c.clientId || c.clientId === identity) &&
(!first || c.address.includes(":") === first.address.includes(":") && JSON.stringify(c.destinations) === JSON.stringify(first.destinations) &&
!selected.some(m => [m.address, m.probe].some(ip => ip === c.address || ip === c.probe))) &&
!draft?.members.some(m => memberKey(m) === memberKey(c)))
.map(c => ({ value: memberKey(c), label: label(c) }))
const needsConfirmation = selected.length > 1 && selected.some(c => !c.clientId && !previous?.members.some(m => memberKey(m) === memberKey(c)))
const selectionKey = selected.map(memberKey).sort().join(",")
const issue = error && <p role="alert" className="text-sm text-destructive">{error}</p>
const renderGroups = (clientId: string) => ownedGroups.filter(g => g.clientId === clientId).map(g => <div key={g.id} className="grid gap-1.5">
<span className="font-medium">{g.name} · {modeLabel(g.mode)}</span>
<ol className="grid gap-1 text-sm">{g.members.map((m, i) => {
const c = available.get(memberKey(m))
const role = g.mode === "failover" ? (i ? "Резерв " + i : "Основной") : "Вес " + (g.mode === "weighted" ? m.weight : 1)
return <li key={memberKey(m)}>{role} · {c ? label(c) : m.interfaceName + " · недоступен"}
{c && c.appliedRevision !== m.appliedRevision ? " · изменена ревизия" : ""}</li>
})}</ol>
{!readOnly && <div className="flex flex-wrap gap-2">
<Button size="sm" variant="outline" disabled={busy} onClick={() => open(g)}>Изменить</Button>
<Button size="sm" variant="outline" disabled={busy} onClick={() => void perform(async () => {
const bundle = await requestJson<IxBondBundle>(backendUrl, "/api/ix/segments/" + g.ownerSegmentId + "/linux-bonds/" + g.id + "/export",
{ method: "POST", body: JSON.stringify({ revision: g.revision }) })
download("ix-bond-" + g.id + ".json", JSON.stringify(bundle, null, 2))
})}>Скачать для ix-client</Button>
<Button size="sm" variant="outline" disabled={busy} onClick={() => void perform(async () => {
try {
await copyIxImportLink(backendUrl, `/api/ix/segments/${g.ownerSegmentId}/linux-bonds/${g.id}/export`, { revision: g.revision })
toast.success("Ссылка скопирована. На VPS откройте ix-client → L.")
} catch (error) {
toast.error(error instanceof Error ? error.message : "Не удалось скопировать ссылку")
}
})}>Скопировать ссылку для ix-client</Button>
</div>}
</div>)
const rows = children(binding => {
const k = memberKey({ ...binding, segmentId })
const current = ownedGroups.find(g => g.members.some(m => memberKey(m) === k))
const candidate = available.get(k)
if (current) return { label: "Открыть группу «" + current.name + "»", open: () => open(current) }
if (candidate?.destinations.length) return { label: "Создать группу с этим туннелем", open: () => open(undefined, candidate) }
const site = segments.find(s => s.id === segmentId)?.configuration.sites.find(s => s.serverId === binding.serverId)
const saved = site?.interfaces.find(b => b.name === binding.interfaceName)
if (saved && saved.kind !== "uplink" && !saved.peerServerId && !saved.linux && !saved.provisionWireguard && !saved.provisionGre &&
!saved.provisionTransit && !site?.neighbors.some(p => p.binding === saved.name)) {
return { label: "Создать группу с этим туннелем", open: () => { open(); setInitialInterface(binding); setImporting(true) } }
}
}, catalog, renderGroups, live && !readOnly &&
<Button size="sm" variant="outline" onClick={() => open()}>Создать группу вручную</Button>)
if (!live) return <>{rows}</>
return <>{rows}{!draft && issue}
<Sheet open={!!draft} onOpenChange={value => !value && !busy && setDraft(null)}>
<SheetContent className="data-[side=right]:w-full data-[side=right]:sm:max-w-xl">
<SheetHeader><SheetTitle>Группа туннелей VPS</SheetTitle>
<SheetDescription>Выберите применённые подключения одного VPS. В режиме резервирования первый туннель в списке основной.</SheetDescription>
</SheetHeader>
{draft && <form className="flex min-h-0 flex-1 flex-col" onSubmit={e => {
e.preventDefault()
if (importing || needsConfirmation && confirmedMembers !== selectionKey) return
void perform(async () => {
await requestJson(backendUrl, root, { method: "POST", body: JSON.stringify({ ...draft,
directCidrs: direct.split(/[\s,]+/).filter(Boolean) }) })
setDraft(null); setReload(n => n + 1)
})
}}>
<div className="grid min-h-0 gap-4 overflow-y-auto px-4">
{issue}
<Field><FieldLabel htmlFor="ix-bond-name">Имя группы</FieldLabel><Input id="ix-bond-name" value={draft.name} required maxLength={80} onChange={e => patch({ name: e.target.value })} /></Field>
<Field><FieldLabel htmlFor="ix-bond-mode">Режим</FieldLabel>
<Select value={draft.mode} items={[...modes]} onValueChange={v => v && patch({ mode: v })}>
<SelectTrigger id="ix-bond-mode"><SelectValue /></SelectTrigger>
<SelectContent>{modes.map(m => <SelectItem key={m.value} value={m.value}>{m.label}</SelectItem>)}</SelectContent>
</Select></Field>
{draft.members.map((m, index) => {
const candidate = available.get(memberKey(m))
return <div key={memberKey(m)} className="grid gap-2 rounded-md border p-2 text-sm">
<span>{index + 1}. {candidate ? label(candidate) : m.interfaceName + " · недоступен"}</span>
{draft.mode === "weighted" && <Field><FieldLabel htmlFor={"ix-bond-weight-" + index}>Вес</FieldLabel>
<Input id={"ix-bond-weight-" + index} type="number" min={1} max={100} required value={m.weight}
onChange={e => patch({ members: draft.members.map((item, n) => n === index ? { ...item, weight: Number(e.target.value) } : item) })} /></Field>}
<div className="flex gap-2">
<Button size="sm" variant="outline" type="button" disabled={!index} onClick={() => {
const members = [...draft.members]; members.splice(index - 1, 0, ...members.splice(index, 1)); patch({ members })
}}>Выше</Button>
<Button size="sm" variant="outline" type="button" onClick={() => patch({ members: draft.members.filter((_, i) => i !== index) })}>Исключить</Button>
</div>
</div>
})}
<Field><FieldLabel htmlFor="ix-bond-member">Добавить туннель этого VPS</FieldLabel>
<Select<string> key={draft.members.length} value={null} items={choices} disabled={!choices.length || draft.members.length >= 16} onValueChange={v => {
const c = v && available.get(v)
if (c) patch({ members: [...draft.members, memberRef(c)] })
}}>
<SelectTrigger id="ix-bond-member"><SelectValue placeholder="Выберите интерфейс" /></SelectTrigger>
<SelectContent alignItemWithTrigger={false}>{choices.map(c => <SelectItem key={c.value} value={c.value}>{c.label}</SelectItem>)}</SelectContent>
</Select></Field>
{!choices.length && draft.members.length < 2 && <p className="text-sm text-muted-foreground">Для второго туннеля нужны другой внутренний адрес, то же семейство и одинаковые назначения. Проверьте привязку к VPS и применение подключения на его площадке.</p>}
{importing ? <IxExistingTransport backendUrl={backendUrl} segments={segments} segmentId={segmentId} nodes={nodes} initial={initialInterface}
members={[...draft.members, ...catalog.groups.filter(g => g.id !== draft.id).flatMap(g => g.members)]} destinations={first?.destinations ?? []}
cancel={() => setImporting(false)} add={m => { patch({ members: [...draft.members, m] }); setImporting(false) }} />
: <Button type="button" variant="outline" disabled={draft.members.length >= 16} onClick={() => { setInitialInterface(undefined); setImporting(true) }}>Добавить из интерфейсов RouterOS</Button>}
{needsConfirmation && <Field orientation="horizontal"><Checkbox id="ix-bond-same-vps" checked={confirmedMembers === selectionKey}
onCheckedChange={checked => setConfirmedMembers(checked ? selectionKey : "")} />
<FieldLabel htmlFor="ix-bond-same-vps">Подтверждаю, что выбранные интерфейсы настроены на одном VPS</FieldLabel></Field>}
<Field><FieldLabel htmlFor="ix-bond-direct">Прямой выход для сетей (CIDR)</FieldLabel>
<Textarea id="ix-bond-direct" rows={3} value={direct} onChange={e => setDirect(e.target.value)} /></Field>
</div>
<SheetFooter>
<Button type="submit" disabled={busy || readOnly || importing || draft.members.length < 2 || needsConfirmation && confirmedMembers !== selectionKey}>Сохранить</Button>
{draft.id && <Button type="button" variant="outline" disabled={busy || readOnly} onClick={() => {
if (!remove) { setRemove(true); return }
void perform(async () => {
await requestJson(backendUrl, root + "/" + draft.id, { method: "DELETE", body: JSON.stringify({ revision: draft.revision }) })
setDraft(null); setReload(n => n + 1)
})
}}>{remove ? "Подтвердить удаление группы" : "Удалить группу"}</Button>}
<Button type="button" variant="outline" disabled={busy} onClick={() => setDraft(null)}>Отмена</Button>
</SheetFooter>
</form>}
</SheetContent>
</Sheet>
</>
}
+68
View File
@@ -0,0 +1,68 @@
"use client"
import { useState } from "react"
import { ixExistingTransportSchema, type IxBondEdit, type IxSegment } from "@mmapp/contracts/internet-exchange"
import { Button } from "@/components/ui/button"
import { Field, FieldDescription, FieldLabel } from "@/components/ui/field"
import { Input } from "@/components/ui/input"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Textarea } from "@/components/ui/textarea"
import { nodeLabel, useIxNodeInventory, type IxNode } from "./ix-view"
type Member = IxBondEdit["members"][number]
export function IxExistingTransport({ backendUrl, segmentId, segments, nodes, members, destinations, initial, add, cancel }: {
backendUrl: string; segmentId: string; segments: IxSegment[]; nodes: IxNode[]; members: Member[]; destinations: string[]
add: (ref: Member) => void; cancel: () => void
initial?: Pick<Member, "serverId" | "interfaceName">
}) {
const sites = segments.filter(s => s.appliedRevision).flatMap(segment => segment.configuration.sites.map(site => ({
value: segment.id + "/" + site.serverId, label: segment.configuration.name + " · " + nodeLabel(nodes, site.serverId), segment, site,
})))
const [selection, setSelection] = useState(sites.find(s => s.segment.id === segmentId && (!initial || s.site.serverId === initial.serverId))?.value ?? "")
const site = sites.find(s => s.value === selection)
const inventory = useIxNodeInventory(backendUrl, site?.site.serverId ?? 0, site?.segment.id)
const [iface, setIface] = useState(initial?.interfaceName ?? "")
const [linuxInterface, setLinuxInterface] = useState("")
const [probe, setProbe] = useState("")
const [address, setAddress] = useState("")
const [endpoint, setEndpoint] = useState("")
const [peer, setPeer] = useState("")
const [routes, setRoutes] = useState(destinations.join("\n"))
const interfaces = (inventory.inventory?.interfaces ?? []).filter(i => /^(wg|wireguard|gre|gre-tunnel)$/.test(i.type) && !i.disabled && i.addresses.length &&
!site?.site.interfaces.some(b => b.name === i.name && (b.linux || b.provisionWireguard || b.provisionGre || b.provisionTransit || b.peerServerId)) &&
!site?.site.neighbors.some(p => p.binding === i.name) && !members.some(m => m.serverId === site?.site.serverId && m.interfaceName === i.name))
const active = interfaces.find(i => i.name === iface)
const wg = active?.type === "wg" || active?.type === "wireguard"
const probes = active?.addresses.map(a => a.split("/")[0]) ?? []
const selectedProbe = probes.includes(probe) ? probe : probes[0] ?? ""
const input = ixExistingTransportSchema.safeParse({ ...(wg ? { kind: "wireguard", clientPublicKey: peer.trim() } : { kind: "gre-ipsec", remoteEndpoint: peer.trim() }),
linuxInterface: linuxInterface.trim(), probe: selectedProbe, address: address.trim(), endpoint: endpoint.trim(), destinations: routes.trim().split(/[\s,]+/) })
return <div className="grid gap-3 rounded-md border p-3">
<Field><FieldLabel htmlFor="ix-adopt-site">Площадка и узел IX</FieldLabel>
<Select value={selection} items={sites} onValueChange={v => { setSelection(v ?? ""); setIface(""); setProbe(""); setPeer(""); setEndpoint("") }}>
<SelectTrigger id="ix-adopt-site"><SelectValue /></SelectTrigger><SelectContent>{sites.map(s => <SelectItem key={s.value} value={s.value}>{s.label}</SelectItem>)}</SelectContent>
</Select></Field>
<Field><FieldLabel htmlFor="ix-adopt-interface">Интерфейс RouterOS</FieldLabel>
<Select value={iface || null} items={interfaces.map(i => ({ value: i.name, label: i.name }))} onValueChange={v => {
setIface(v ?? ""); setProbe(interfaces.find(i => i.name === v)?.addresses[0]?.split("/")[0] ?? ""); setPeer("")
}}><SelectTrigger id="ix-adopt-interface"><SelectValue placeholder="Выберите WG или GRE" /></SelectTrigger>
<SelectContent>{interfaces.map(i => <SelectItem value={i.name} key={i.name}>{i.name}</SelectItem>)}</SelectContent></Select>
<FieldDescription>{inventory.error ?? (inventory.loading ? "Читаем интерфейсы узла…" : "Доступны включённые интерфейсы с внутренним IP. Настройки RouterOS сохраняются.")}</FieldDescription></Field>
{active && <>
<Field><FieldLabel htmlFor="ix-adopt-linux">Имя интерфейса на VPS</FieldLabel><Input id="ix-adopt-linux" value={linuxInterface} onChange={e => setLinuxInterface(e.target.value)} /></Field>
<Field><FieldLabel htmlFor="ix-adopt-probe">Адрес IX внутри туннеля</FieldLabel>
<Select value={selectedProbe} items={probes.map(value => ({ value, label: value }))} onValueChange={v => setProbe(v ?? "")}>
<SelectTrigger id="ix-adopt-probe"><SelectValue /></SelectTrigger><SelectContent>{probes.map(v => <SelectItem key={v} value={v}>{v}</SelectItem>)}</SelectContent>
</Select></Field>
<Field><FieldLabel htmlFor="ix-adopt-address">Адрес VPS внутри туннеля</FieldLabel><Input id="ix-adopt-address" value={address} onChange={e => setAddress(e.target.value)} /></Field>
<Field><FieldLabel htmlFor="ix-adopt-endpoint">Внешний адрес IX</FieldLabel><Input id="ix-adopt-endpoint" value={endpoint} onChange={e => setEndpoint(e.target.value)} /></Field>
<Field><FieldLabel htmlFor="ix-adopt-peer">{wg ? "Публичный ключ WireGuard VPS" : "Внешний IPv4 VPS"}</FieldLabel><Input id="ix-adopt-peer" value={peer} onChange={e => setPeer(e.target.value)} /></Field>
<Field><FieldLabel htmlFor="ix-adopt-routes">Назначения через туннель (CIDR)</FieldLabel><Textarea id="ix-adopt-routes" rows={2} value={routes} onChange={e => setRoutes(e.target.value)} /></Field>
</>}
<div className="flex gap-2"><Button type="button" variant="outline" size="sm" disabled={!site || !active || !input.success} onClick={() => {
if (input.success && site?.segment.appliedRevision && active) add({ segmentId: site.segment.id, serverId: site.site.serverId,
appliedRevision: site.segment.appliedRevision, interfaceName: active.name, existing: input.data, weight: 1 })
}}>Включить в список</Button><Button type="button" size="sm" variant="ghost" onClick={cancel}>Отмена выбора</Button></div>
</div>
}
+48 -49
View File
@@ -2,8 +2,6 @@
import { useState } from "react" import { useState } from "react"
import type { IxNodeInventory, IxSegment, IxTransitRequest } from "@mmapp/contracts/internet-exchange" import type { IxNodeInventory, IxSegment, IxTransitRequest } from "@mmapp/contracts/internet-exchange"
import { EmptyState } from "@/components/empty-state"
import { Frame, FrameHeader, FramePanel, FrameTitle } from "@/components/reui/frame"
import { Button } from "@/components/ui/button" import { Button } from "@/components/ui/button"
import { Field, FieldDescription, FieldLabel } from "@/components/ui/field" import { Field, FieldDescription, FieldLabel } from "@/components/ui/field"
import { Input } from "@/components/ui/input" import { Input } from "@/components/ui/input"
@@ -11,9 +9,20 @@ import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@
import { Sheet, SheetContent, SheetDescription, SheetFooter, SheetHeader, SheetTitle } from "@/components/ui/sheet" import { Sheet, SheetContent, SheetDescription, SheetFooter, SheetHeader, SheetTitle } from "@/components/ui/sheet"
import { nodeLabel, useIxNodeInventory, type IxNode } from "./ix-view" import { nodeLabel, useIxNodeInventory, type IxNode } from "./ix-view"
function publicEndpoint(inventory?: IxNodeInventory) { export function publicEndpoint(inventory?: IxNodeInventory) {
const wan = inventory?.defaultRoutes.find(route => route.family === 4) if (!inventory) return ""
return inventory?.interfaces.find(item => item.name === wan?.interface)?.addresses.find(value => !value.includes(":"))?.split("/")[0] ?? "" const wan = new Set(inventory.defaultRoutes.filter(route => route.family === 4).map(route => route.interface))
const addresses = new Set(inventory.interfaces.filter(iface => !iface.disabled && wan.has(iface.name))
.flatMap(iface => iface.addresses.filter(address => !address.includes(":")).map(address => address.split("/")[0])))
return addresses.size === 1 ? [...addresses][0] : ""
}
export function transitName(segment: IxSegment, serverId: number, target: number, family: 4 | 6) {
const used = segment.configuration.sites.find(site => site.serverId === serverId)?.groups ?? []
const base = "via-" + target.toString(36) + "-v" + family
let name = base
for (let i = 2; used.some(group => group.id === name); i++) name = base + "-" + i
return name
} }
function TransitEditor({ segment, nodes, backendUrl, busy, save, cancel }: { function TransitEditor({ segment, nodes, backendUrl, busy, save, cancel }: {
@@ -31,18 +40,17 @@ function TransitEditor({ segment, nodes, backendUrl, busy, save, cancel }: {
const target = useIxNodeInventory(backendUrl, targetServerId, segment.id) const target = useIxNodeInventory(backendUrl, targetServerId, segment.id)
const localEndpoint = local || publicEndpoint(origin.inventory) const localEndpoint = local || publicEndpoint(origin.inventory)
const remoteEndpoint = remote || publicEndpoint(target.inventory) const remoteEndpoint = remote || publicEndpoint(target.inventory)
const exitName = name || transitName(segment, serverId, targetServerId, family)
const sourceChoices = segment.configuration.sites.map(site => ({ value: String(site.serverId), label: nodeLabel(nodes, site.serverId) })) const sourceChoices = segment.configuration.sites.map(site => ({ value: String(site.serverId), label: nodeLabel(nodes, site.serverId) }))
const targets = nodes.filter(node => node.enabled && node.id !== serverId && ["ix-node", "exit-node"].includes(node.type ?? "")) const targets = nodes.filter(node => node.enabled && node.id !== serverId && ["ix-node", "exit-node"].includes(node.type ?? ""))
.map(node => ({ value: String(node.id), label: node.name + (node.type === "ix-node" ? " · IX" : " · ExitNode") })) .map(node => ({ value: String(node.id), label: node.name + (node.type === "ix-node" ? " · IX" : " · ExitNode") }))
return <form className="flex min-h-0 flex-1 flex-col" onSubmit={event => { return <form className="flex min-h-0 flex-1 flex-col" onSubmit={event => {
event.preventDefault() event.preventDefault()
if (!busy && targetServerId && localEndpoint && remoteEndpoint && name) { if (!busy && targetServerId && localEndpoint && remoteEndpoint && exitName) {
save({ revision: segment.revision, name, serverId, targetServerId, localEndpoint, remoteEndpoint, family, probe: probe || undefined }) save({ revision: segment.revision, name: exitName, serverId, targetServerId, localEndpoint, remoteEndpoint, family, probe: probe || undefined })
} }
}}> }}>
<div className="grid min-h-0 gap-4 overflow-y-auto px-4"> <div className="grid min-h-0 gap-4 overflow-y-auto px-4">
<Field><FieldLabel htmlFor="ix-egress-name">Имя выхода</FieldLabel>
<Input id="ix-egress-name" placeholder="via-arn" pattern="[a-z][a-z0-9-]{0,23}" required value={name} onChange={event => setName(event.target.value)} /></Field>
{sourceChoices.length > 1 && <Field><FieldLabel htmlFor="ix-egress-source">Узел входа</FieldLabel> {sourceChoices.length > 1 && <Field><FieldLabel htmlFor="ix-egress-source">Узел входа</FieldLabel>
<Select items={sourceChoices} value={String(serverId)} onValueChange={value => { <Select items={sourceChoices} value={String(serverId)} onValueChange={value => {
if (value) { setServerId(Number(value)); setTargetServerId(0); setLocal(""); setRemote("") } if (value) { setServerId(Number(value)); setTargetServerId(0); setLocal(""); setRemote("") }
@@ -56,56 +64,47 @@ function TransitEditor({ segment, nodes, backendUrl, busy, save, cancel }: {
<SelectTrigger className="w-full" id="ix-egress-target"><SelectValue placeholder="Другой IX или ExitNode" /></SelectTrigger> <SelectTrigger className="w-full" id="ix-egress-target"><SelectValue placeholder="Другой IX или ExitNode" /></SelectTrigger>
<SelectContent>{targets.map(item => <SelectItem key={item.value} value={item.value}>{item.label}</SelectItem>)}</SelectContent> <SelectContent>{targets.map(item => <SelectItem key={item.value} value={item.value}>{item.label}</SelectItem>)}</SelectContent>
</Select></Field> </Select></Field>
<Field><FieldLabel htmlFor="ix-egress-local">Внешний IPv4 узла входа</FieldLabel> <details key={serverId + ":" + targetServerId + ":" + (origin.loading || target.loading)} open={!!targetServerId && (!publicEndpoint(origin.inventory) || !publicEndpoint(target.inventory)) && !origin.loading && !target.loading}>
<Input id="ix-egress-local" value={localEndpoint} required onChange={event => setLocal(event.target.value)} /></Field> <summary className="cursor-pointer text-sm font-medium">Параметры туннеля</summary>
<Field><FieldLabel htmlFor="ix-egress-remote">Внешний IPv4 выходного узла</FieldLabel> <div className="mt-3 grid gap-3">
<Input id="ix-egress-remote" value={remoteEndpoint} required onChange={event => setRemote(event.target.value)} /></Field> <Field><FieldLabel htmlFor="ix-egress-name">Имя выхода</FieldLabel>
<Field><FieldLabel htmlFor="ix-egress-probe">Контрольный адрес</FieldLabel> <Input id="ix-egress-name" value={exitName} pattern="[a-z][a-z0-9-]{0,23}" onChange={event => setName(event.target.value)} /></Field>
<Input id="ix-egress-probe" value={probe} placeholder="Адрес второго конца туннеля" onChange={event => setProbe(event.target.value)} /> <Field><FieldLabel htmlFor="ix-egress-local">Внешний IPv4 узла входа</FieldLabel>
<FieldDescription>Для проверки выхода за пределами туннеля укажите доступную цель за удалённым узлом.</FieldDescription> <Input id="ix-egress-local" value={localEndpoint} required onChange={event => setLocal(event.target.value)} /></Field>
</Field> <Field><FieldLabel htmlFor="ix-egress-remote">Внешний IPv4 выходного узла</FieldLabel>
<Field><FieldLabel htmlFor="ix-egress-family">Семейство трафика</FieldLabel> <Input id="ix-egress-remote" value={remoteEndpoint} required onChange={event => setRemote(event.target.value)} /></Field>
<Select value={String(family)} items={[{ value: "4", label: "IPv4" }, { value: "6", label: "IPv6" }]} <Field><FieldLabel htmlFor="ix-egress-probe">Контрольный адрес</FieldLabel>
onValueChange={value => { setFamily(value === "6" ? 6 : 4); setProbe("") }}> <Input id="ix-egress-probe" value={probe} placeholder="Адрес второго конца туннеля" onChange={event => setProbe(event.target.value)} />
<SelectTrigger className="w-full" id="ix-egress-family"><SelectValue /></SelectTrigger> <FieldDescription>Для проверки выхода за пределами туннеля укажите доступную цель за удалённым узлом.</FieldDescription>
<SelectContent><SelectItem value="4">IPv4</SelectItem><SelectItem value="6">IPv6</SelectItem></SelectContent> </Field>
</Select> <Field><FieldLabel htmlFor="ix-egress-family">Семейство трафика</FieldLabel>
{family === 6 && <FieldDescription>Для выхода в Интернет IPv6 нужен маршрутизируемый префикс Linux с обратным маршрутом до выходной CHR.</FieldDescription>} <Select value={String(family)} items={[{ value: "4", label: "IPv4" }, { value: "6", label: "IPv6" }]}
</Field> onValueChange={value => { setFamily(value === "6" ? 6 : 4); setProbe("") }}>
<SelectTrigger className="w-full" id="ix-egress-family"><SelectValue /></SelectTrigger>
<SelectContent><SelectItem value="4">IPv4</SelectItem><SelectItem value="6">IPv6</SelectItem></SelectContent>
</Select>
{family === 6 && <FieldDescription>Для выхода в Интернет IPv6 нужен маршрутизируемый префикс Linux с обратным маршрутом до выходной CHR.</FieldDescription>}
</Field>
</div>
</details>
{(origin.error || target.error) && <p role="status" className="text-sm text-muted-foreground">{origin.error ?? target.error}</p>} {(origin.error || target.error) && <p role="status" className="text-sm text-muted-foreground">{origin.error ?? target.error}</p>}
</div> </div>
<SheetFooter> <SheetFooter>
<Button type="submit" disabled={busy || !targetServerId || !localEndpoint || !remoteEndpoint}>Проверить план выхода</Button> <Button type="submit" disabled={busy || !targetServerId || !localEndpoint || !remoteEndpoint}>Сохранить</Button>
<Button type="button" variant="outline" disabled={busy} onClick={cancel}>Отмена</Button> <Button type="button" variant="outline" disabled={busy} onClick={cancel}>Отмена</Button>
</SheetFooter> </SheetFooter>
</form> </form>
} }
export function IxExits({ segment, nodes, backendUrl, busy, readOnly, error, save, configure }: { export function IxExits({ segment, nodes, backendUrl, busy, error, save }: {
segment: IxSegment; nodes: IxNode[]; backendUrl: string; busy: boolean; readOnly: boolean; error: string segment: IxSegment; nodes: IxNode[]; backendUrl: string; busy: boolean; error: string
save: (input: IxTransitRequest) => Promise<boolean>; configure: () => void save: (input: IxTransitRequest) => Promise<boolean>
}) { }) {
const [open, setOpen] = useState(false) const [open, setOpen] = useState(false)
return <Frame spacing="sm"> return <>
<FrameHeader className="flex-row flex-wrap items-center justify-between gap-2"> <Button size="sm" className="w-fit" disabled={busy} onClick={() => setOpen(true)}>Добавить удалённый выход</Button>
<FrameTitle>Выходы и резерв</FrameTitle>
{!readOnly && <Button size="sm" disabled={busy} onClick={() => setOpen(true)}>Добавить удалённый выход</Button>}
</FrameHeader>
<FramePanel className="grid gap-3">
{segment.configuration.sites.every(site => !site.groups.length) && <EmptyState title="Групп шлюзов пока нет"
description="При подключении клиента можно выбрать выход через WAN этого IX или создать транзит на другой узел." />}
{segment.configuration.sites.map(site => site.groups.length > 0 && <div key={site.serverId} className="grid gap-2">
<h3 className="text-sm font-medium">{nodeLabel(nodes, site.serverId)}</h3>
{site.groups.map(group => <div key={group.id} className="grid gap-1 border-b pb-2 text-sm">
<span className="font-medium">{group.id}</span>
<span className="text-muted-foreground">Основной · {group.primary.interface} · {group.primary.nextHop}</span>
<span className="text-muted-foreground">Резерв · {group.backup ? group.backup.interface + " · " + group.backup.nextHop : "не задан"}</span>
</div>)}
</div>)}
<Button size="sm" variant="outline" className="w-fit" disabled={busy} onClick={configure}>Открыть настройки групп шлюзов</Button>
</FramePanel>
<Sheet open={open} onOpenChange={value => !busy && setOpen(value)}> <Sheet open={open} onOpenChange={value => !busy && setOpen(value)}>
<SheetContent className="w-full sm:max-w-lg"> <SheetContent className="data-[side=right]:w-full data-[side=right]:sm:max-w-lg" showCloseButton={!busy}>
<SheetHeader><SheetTitle>Удалённый выход</SheetTitle> <SheetHeader><SheetTitle>Удалённый выход</SheetTitle>
<SheetDescription>WireGuard, обратные маршруты и IPv4 SNAT будут подготовлены на обоих узлах.</SheetDescription> <SheetDescription>WireGuard, обратные маршруты и IPv4 SNAT будут подготовлены на обоих узлах.</SheetDescription>
{error && <p className="text-sm text-destructive" role="alert">{error}</p>} {error && <p className="text-sm text-destructive" role="alert">{error}</p>}
@@ -114,5 +113,5 @@ export function IxExits({ segment, nodes, backendUrl, busy, readOnly, error, sav
save={input => void save(input).then(success => { if (success) setOpen(false) })} cancel={() => setOpen(false)} />} save={input => void save(input).then(success => { if (success) setOpen(false) })} cancel={() => setOpen(false)} />}
</SheetContent> </SheetContent>
</Sheet> </Sheet>
</Frame> </>
} }
+12
View File
@@ -0,0 +1,12 @@
import { requestJson } from "@/shared/api/http-client"
export async function copyIxImportLink(backendUrl: string, path: string, params: object) {
const link = new URL(backendUrl.replace(/\/$/, "") + "/api/ix/import", window.location.origin)
if (link.protocol !== "https:" || !navigator.clipboard) throw new Error("Для одноразовой ссылки откройте Manager по HTTPS")
const { code } = await requestJson<{ code: string }>(backendUrl, path, {
method: "POST", body: JSON.stringify({ ...params, importLink: true }),
})
if (!/^[A-Za-z0-9_-]{32}$/.test(code)) throw new Error("Manager вернул неверный код импорта")
link.hash = code
await navigator.clipboard.writeText(link.toString())
}
+264 -103
View File
@@ -1,26 +1,33 @@
"use client" "use client"
import { useMemo, useState } from "react" import { useMemo, useState, type ReactNode } from "react"
import { type ColumnDef, useTable } from "@tanstack/react-table" import { type ColumnDef, useTable } from "@tanstack/react-table"
import { PlusIcon, RefreshCwIcon } from "lucide-react" import { EllipsisIcon, PencilIcon, PlusIcon, RefreshCwIcon } from "lucide-react"
import type { IxLinuxBinding, IxLinuxClientRequest, IxSegment, IxSite } from "@mmapp/contracts/internet-exchange" import type { IxBondCatalog, IxLinuxBinding, IxLinuxClientRequest, IxSegment, IxSite } from "@mmapp/contracts/internet-exchange"
import { DataGridShell } from "@/components/data-grids/shared/data-grid-shell" import { DataGridShell } from "@/components/data-grids/shared/data-grid-shell"
import { Badge } from "@/components/reui/badge" import { Badge } from "@/components/reui/badge"
import { dataGridFeatures, type DataGridFeatures } from "@/components/reui/data-grid" import { dataGridFeatures, type DataGridFeatures } from "@/components/reui/data-grid"
import { Frame, FrameHeader, FramePanel, FrameTitle } from "@/components/reui/frame" import { Frame, FrameHeader, FramePanel, FrameTitle } from "@/components/reui/frame"
import { Button } from "@/components/ui/button" import { Button } from "@/components/ui/button"
import { Field, FieldDescription, FieldLabel } from "@/components/ui/field" import { ButtonGroup } from "@/components/ui/button-group"
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu"
import { Field, FieldDescription, FieldLabel, FieldTitle } from "@/components/ui/field"
import { Input } from "@/components/ui/input" import { Input } from "@/components/ui/input"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select" import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Sheet, SheetContent, SheetDescription, SheetFooter, SheetHeader, SheetTitle } from "@/components/ui/sheet" import { Sheet, SheetContent, SheetDescription, SheetFooter, SheetHeader, SheetTitle } from "@/components/ui/sheet"
import { Textarea } from "@/components/ui/textarea" import { Textarea } from "@/components/ui/textarea"
import { isIpv4String } from "@/lib/gre-endpoint-resolve"
import { formatBytes } from "@/lib/fmt-rate"
import { publicEndpoint, transitName } from "./ix-exits"
import { nodeLabel, useIxNodeInventory, type IxNode } from "./ix-view" import { nodeLabel, useIxNodeInventory, type IxNode } from "./ix-view"
import type { IxRowBondAction } from "./ix-client-bonds"
type Binding = IxSite["interfaces"][number] type Binding = IxSite["interfaces"][number]
type ClientSelection = { site: IxSite; binding: Binding; addProtocol?: boolean; chooseTransport?: boolean }
type FormState = { type FormState = {
serverId: number serverId: number
name: string name: string
kind: IxLinuxClientRequest["kind"] kind: IxLinuxClientRequest["kind"] | "both"
hub: string hub: string
peer: string peer: string
key: string key: string
@@ -30,184 +37,338 @@ type FormState = {
destinations: string destinations: string
exit: string exit: string
enabled: boolean enabled: boolean
transitLocal: string
transitRemote: string
} }
const lines = (value: string) => value.split(/[,\n]/).map(line => line.trim()).filter(Boolean) const lines = (value: string) => value.split(/[,\n]/).map(line => line.trim()).filter(Boolean)
const protocols = [
{ kind: "wireguard", label: "WireGuard" },
{ kind: "gre-ipsec", label: "GRE/IPsec" },
] as const
function choicesFor(site: IxSite | undefined, nodes: IxNode[]) { function hasCompanion(site: IxSite, binding: Binding) {
return [ const clientId = binding.linux?.clientId
{ value: "isolated", label: "Только разрешённые сети" }, return !!clientId && site.interfaces.some(item => item.kind !== binding.kind && item.linux?.clientId === clientId)
{ value: "local-wan", label: "Интернет с этого IX" },
...(site?.groups.filter(group => group.onFailure === "block").map(group => {
const link = site.interfaces.find(binding => binding.name === group.primary.interface)
const peer = nodes.find(node => node.id === link?.peerServerId)
return { value: group.id, label: [group.id, peer?.name, group.backup && "с резервом"].filter(Boolean).join(" · ") }
}) ?? []),
]
} }
function ClientForm({ segment, edit, nodes, backendUrl, busy, save, cancel }: { function groupLabel(group: IxSite["groups"][number], site: IxSite, nodes: IxNode[]) {
segment: IxSegment; edit: { site: IxSite; binding: Binding } | null; nodes: IxNode[]; backendUrl: string const target = site.interfaces.find(binding => binding.name === group.primary.interface)?.peerServerId
const label = target ? "Через " + nodeLabel(nodes, target) : group.primary.viaMain ? "Интернет с этого IX" : group.id
return [label, group.backup && "с резервом"].filter(Boolean).join(" · ")
}
function ClientForm({ segment, edit, setAddProtocol, nodes, backendUrl, catalog, busy, save, cancel }: {
segment: IxSegment; edit: ClientSelection | null; nodes: IxNode[]; backendUrl: string
catalog: IxBondCatalog
setAddProtocol: (add: boolean) => void
busy: boolean; save: (input: IxLinuxClientRequest) => Promise<void>; cancel: () => void busy: boolean; save: (input: IxLinuxClientRequest) => Promise<void>; cancel: () => void
}) { }) {
const binding = edit?.binding const existing = edit?.binding
const [form, setForm] = useState<FormState>(() => ({ const companion = edit?.addProtocol ? existing : undefined
serverId: edit?.site.serverId ?? segment.configuration.sites[0].serverId, const binding = companion ? undefined : existing
name: binding?.linux?.name ?? "", kind: binding?.kind === "gre-ipsec" ? "gre-ipsec" : "wireguard", const paired = !!edit && hasCompanion(edit.site, edit.binding)
hub: binding?.localEndpoint ?? binding?.provisionWireguard?.hubEndpoint ?? "", const initialForm = (addProtocol: boolean): FormState => {
peer: binding?.linux?.peerEndpoint ?? binding?.endpoint ?? "", key: binding?.provisionWireguard?.peerPublicKey ?? "", const current = addProtocol ? undefined : existing
localAddress: (binding?.provisionWireguard ?? binding?.provisionGre)?.localAddress ?? "", const tunnel = current?.provisionWireguard ?? current?.provisionGre
peerAddress: (binding?.provisionWireguard ?? binding?.provisionGre)?.peerAddress ?? "", return {
prefixes: binding?.prefixes.join("\n") ?? "", destinations: binding?.linux?.destinations.join("\n") ?? "", serverId: edit?.site.serverId ?? segment.configuration.sites[0].serverId,
exit: binding?.linux?.exit ?? "isolated", enabled: binding?.linux?.enabled ?? true, name: existing?.linux?.name ?? "",
})) kind: addProtocol ? (existing?.kind === "wireguard" ? "gre-ipsec" : "wireguard")
: current?.kind === "gre-ipsec" ? "gre-ipsec" : "wireguard",
hub: existing?.localEndpoint ?? existing?.provisionWireguard?.hubEndpoint ?? "",
peer: existing?.linux?.peerEndpoint ?? existing?.endpoint ?? "",
key: current?.provisionWireguard?.credentialId ? "" : current?.provisionWireguard?.peerPublicKey ?? "",
localAddress: tunnel?.localAddress ?? "", peerAddress: tunnel?.peerAddress ?? "",
prefixes: current?.prefixes.join("\n") ?? "", destinations: current?.linux?.destinations.join("\n") ?? "",
exit: current?.linux?.exit ?? "isolated", enabled: current?.linux?.enabled ?? true,
transitLocal: "", transitRemote: "",
}
}
const [currentForm, setCurrentForm] = useState(() => initialForm(false))
const [companionForm, setCompanionForm] = useState(() => initialForm(true))
const form = companion ? companionForm : currentForm
const setForm = companion ? setCompanionForm : setCurrentForm
const wireguard = form.kind !== "gre-ipsec"
const gre = form.kind !== "wireguard"
const [rotate, setRotate] = useState(false) const [rotate, setRotate] = useState(false)
const { inventory } = useIxNodeInventory(backendUrl, form.serverId, segment.id) const [vpsId, setVpsId] = useState("")
const currentGroup = edit && catalog.groups.find(g => g.members.some(m => m.segmentId === segment.id &&
m.serverId === edit.site.serverId && m.interfaceName === edit.binding.name))
const currentVps = currentGroup?.clientId ?? existing?.linux?.clientId
const knownVps = useMemo(() => {
const labels = new Map<string, string>()
for (const c of catalog.candidates) if (c.clientId) labels.set(c.clientId, c.name + " · " + c.segmentName)
for (const group of catalog.groups) labels.set(group.clientId, group.name)
if (currentVps && !labels.has(currentVps)) labels.set(currentVps, existing?.linux?.name ?? "Текущий VPS")
return [...labels].map(([value, label]) => ({ value, label: label + " · " + value.slice(0, 8) }))
}, [catalog, currentVps, existing])
const origin = useIxNodeInventory(backendUrl, form.serverId, segment.id)
const site = segment.configuration.sites.find(site => site.serverId === form.serverId) const site = segment.configuration.sites.find(site => site.serverId === form.serverId)
const uplink = inventory?.interfaces.find(item => item.name === inventory.defaultRoutes.find(route => route.family === 4)?.interface) const suggested = publicEndpoint(origin.inventory)
const suggested = uplink?.addresses.find(address => !address.includes(":"))?.split("/")[0] ?? "" const hub = form.hub.trim() || suggested
const targetId = form.exit.startsWith("remote:") ? Number(form.exit.slice(7)) : 0
const target = useIxNodeInventory(backendUrl, targetId, segment.id)
const localEndpoint = form.transitLocal.trim() || suggested || (form.hub.includes(":") ? "" : form.hub.trim())
const remoteEndpoint = form.transitRemote.trim() || publicEndpoint(target.inventory)
const family = form.kind !== "both" && form.peerAddress.includes(":") ? 6 : 4
const patch = (fields: Partial<FormState>) => setForm(value => ({ ...value, ...fields })) const patch = (fields: Partial<FormState>) => setForm(value => ({ ...value, ...fields }))
const nodeChoices = segment.configuration.sites.map(site => ({ value: String(site.serverId), label: nodeLabel(nodes, site.serverId) })) const nodeChoices = segment.configuration.sites.map(site => ({ value: String(site.serverId), label: nodeLabel(nodes, site.serverId) }))
const transports = [{ value: "wireguard", label: "WireGuard" }, { value: "gre-ipsec", label: "GRE/IPsec (IKEv2)" }] const groups = site?.groups.filter(group => group.onFailure === "block" && group.gateway.includes(":") === (family === 6)) ?? []
const exits = choicesFor(site, nodes) const local = groups.find(group => group.id === "ix-wan" + family && group.primary.viaMain)
const valid = !!form.name.trim() && !!(form.hub || suggested) && (form.kind === "wireguard" ? !!form.key : !!form.peer) const targets = nodes.filter(node => node.enabled && node.id !== form.serverId && ["ix-node", "exit-node"].includes(node.type ?? ""))
const exits = [
{ value: "isolated", label: "Только разрешённые сети" },
{ value: local?.id ?? "local-wan", label: local ? groupLabel(local, site!, nodes) : "Интернет с этого IX" },
...groups.filter(group => group !== local).map(group => ({ value: group.id, label: groupLabel(group, site!, nodes) + " · " + group.id })),
...targets.filter(node => !groups.some(group => site?.interfaces.some(link => link.name === group.primary.interface && link.peerServerId === node.id)))
.map(node => ({ value: "remote:" + node.id, label: "Через " + node.name + (node.type === "exit-node" ? " · ExitNode" : " · IX") })),
]
const valid = !!form.name.trim() && !!hub && (!gre || isIpv4String(form.peer.trim()) && isIpv4String(hub)) &&
(!targetId || !!localEndpoint && !!remoteEndpoint) && exits.some(exit => exit.value === form.exit)
const destinationsField = <Field><FieldLabel htmlFor="ix-linux-destinations">Разрешённые сети IX</FieldLabel>
<Textarea id="ix-linux-destinations" rows={2} value={form.destinations} placeholder="По одному CIDR на строку" onChange={event => patch({ destinations: event.target.value })} />
<FieldDescription>Перечислите префиксы для доступа через IX, например 10.2.0.0/24.</FieldDescription></Field>
return <form className="flex min-h-0 flex-1 flex-col" onSubmit={event => { return <form className="flex min-h-0 flex-1 flex-col" onSubmit={event => {
event.preventDefault() event.preventDefault()
if (!valid || busy) return if (!valid || busy) return
void save({ void save({
revision: segment.revision, serverId: form.serverId, interfaceName: binding?.name, name: form.name, revision: segment.revision, serverId: form.serverId, interfaceName: binding?.name, name: form.name,
kind: form.kind, hubEndpoint: form.hub.trim() || suggested, peerEndpoint: form.peer.trim() || undefined, vpsClientId: !companion && vpsId && vpsId !== currentVps ? vpsId : undefined,
peerPublicKey: form.kind === "wireguard" ? form.key.trim() : undefined, kind: wireguard ? "wireguard" : "gre-ipsec", additionalGre: form.kind === "both" || undefined, companionOf: companion?.name,
localAddress: form.localAddress.trim() || undefined, peerAddress: form.peerAddress.trim() || undefined, hubEndpoint: hub, peerEndpoint: form.peer.trim() || undefined,
prefixes: lines(form.prefixes), destinations: lines(form.destinations), exit: form.exit === "isolated" ? undefined : form.exit, peerPublicKey: wireguard ? form.key.trim() || undefined : undefined,
enabled: form.enabled, rotate, localAddress: form.kind === "both" ? undefined : form.localAddress.trim() || undefined,
peerAddress: form.kind === "both" ? undefined : form.peerAddress.trim() || undefined,
prefixes: lines(form.prefixes), destinations: lines(form.destinations), exit: form.exit === "isolated" || targetId ? undefined : form.exit,
transit: targetId ? { targetServerId: targetId, name: transitName(segment, form.serverId, targetId, family), family,
localEndpoint, remoteEndpoint } : undefined,
enabled: form.enabled, rotate: !!binding && rotate,
}) })
}}> }}>
<div className="grid min-h-0 gap-4 overflow-y-auto px-4 pb-4"> <div className="grid min-h-0 gap-4 overflow-y-auto px-4 pb-4">
<Field><FieldLabel htmlFor="ix-linux-name">Имя клиента</FieldLabel> <Field><FieldLabel htmlFor="ix-linux-name">Имя клиента</FieldLabel>
<Input id="ix-linux-name" value={form.name} placeholder="vps-01" required onChange={event => patch({ name: event.target.value })} /></Field> <Input id="ix-linux-name" value={form.name} placeholder="vps-01" readOnly={!!companion} required onChange={event => patch({ name: event.target.value })} /></Field>
{!companion && !!knownVps.length && <Field><FieldLabel htmlFor="ix-linux-vps">Привязка к VPS</FieldLabel>
<Select value={vpsId || currentVps || "separate"} disabled={!!currentGroup} items={[{ value: "separate", label: "Отдельное подключение" }, ...knownVps]}
onValueChange={v => setVpsId(v && v !== "separate" ? v : "")}>
<SelectTrigger id="ix-linux-vps"><SelectValue /></SelectTrigger>
<SelectContent>{!currentVps && <SelectItem value="separate">Отдельное подключение</SelectItem>}
{knownVps.map(v => <SelectItem key={v.value} value={v.value}>{v.label}</SelectItem>)}</SelectContent>
</Select>{currentGroup && <FieldDescription>Привязка задана группой «{currentGroup.name}».</FieldDescription>}</Field>}
{nodeChoices.length > 1 && <Field><FieldLabel htmlFor="ix-linux-node">Узел IX</FieldLabel> {nodeChoices.length > 1 && <Field><FieldLabel htmlFor="ix-linux-node">Узел IX</FieldLabel>
<Select value={String(form.serverId)} items={nodeChoices} disabled={!!edit} <Select value={String(form.serverId)} items={nodeChoices} disabled={!!edit}
onValueChange={value => value && patch({ serverId: Number(value), hub: "", exit: "isolated" })}> onValueChange={value => value && patch({ serverId: Number(value), hub: "", exit: "isolated" })}>
<SelectTrigger id="ix-linux-node" className="w-full"><SelectValue /></SelectTrigger> <SelectTrigger id="ix-linux-node" className="w-full"><SelectValue /></SelectTrigger>
<SelectContent>{nodeChoices.map(item => <SelectItem key={item.value} value={item.value}>{item.label}</SelectItem>)}</SelectContent> <SelectContent>{nodeChoices.map(item => <SelectItem key={item.value} value={item.value}>{item.label}</SelectItem>)}</SelectContent>
</Select></Field>} </Select></Field>}
<Field><FieldLabel htmlFor="ix-linux-transport">Туннель</FieldLabel> <Field>
<Select value={form.kind} items={transports} disabled={!!edit} <FieldTitle id="ix-linux-transport">Протоколы подключения</FieldTitle>
onValueChange={value => (value === "wireguard" || value === "gre-ipsec") && patch({ kind: value })}> <ButtonGroup aria-labelledby="ix-linux-transport" className="max-w-full">
<SelectTrigger id="ix-linux-transport" className="w-full"><SelectValue /></SelectTrigger> {protocols.map(({ kind, label }) => {
<SelectContent>{transports.map(item => <SelectItem key={item.value} value={item.value}>{item.label}</SelectItem>)}</SelectContent> const choosing = !!companion && edit?.chooseTransport
</Select></Field> const selected = choosing ? form.kind === kind : paired || !!companion || form.kind === "both" || form.kind === kind
return <Button key={kind} type="button" size="sm" variant={selected ? "secondary" : "outline"} aria-pressed={selected}
disabled={busy || (choosing ? form.kind === kind : existing ? paired || existing.kind === kind : form.kind === kind)}
onClick={() => choosing ? patch({ kind }) : existing ? setAddProtocol(!companion)
: patch({ kind: form.kind === "both" ? (kind === "wireguard" ? "gre-ipsec" : "wireguard") : "both" })}>{label}</Button>
})}
</ButtonGroup>
{form.kind === "both" ? <FieldDescription>Оба туннеля получат свои адреса в одной VRF сегмента.</FieldDescription>
: companion ? <FieldDescription>Настройки ниже относятся к новому туннелю в той же VRF.</FieldDescription>
: paired ? <FieldDescription>Оба протокола настроены. Здесь редактируется {binding?.kind === "gre-ipsec" ? "GRE/IPsec" : "WireGuard"}.</FieldDescription>
: edit ? <FieldDescription>Выберите второй протокол, чтобы добавить туннель в ту же VRF.</FieldDescription>
: <FieldDescription>Можно отметить оба протокола.</FieldDescription>}
</Field>
<Field><FieldLabel htmlFor="ix-linux-peer">Внешний адрес Linux</FieldLabel> <Field><FieldLabel htmlFor="ix-linux-peer">Внешний адрес Linux</FieldLabel>
<Input id="ix-linux-peer" value={form.peer} placeholder="123.123.123.123" required={form.kind === "gre-ipsec"} onChange={event => patch({ peer: event.target.value })} /></Field> <Input id="ix-linux-peer" value={form.peer} placeholder="123.123.123.123" required={gre} onChange={event => patch({ peer: event.target.value })} />
<Field><FieldLabel htmlFor="ix-linux-hub">Внешний адрес IX</FieldLabel> <FieldDescription>{gre ? "Фиксированный IPv4 на VPS для GRE/IPsec. Ответы на SSH по этому адресу пойдут напрямую." : form.exit === "isolated"
<Input id="ix-linux-hub" value={form.hub || suggested} placeholder="IP узла RouterOS" onChange={event => patch({ hub: event.target.value })} /> ? "Для WireGuard это поле необязательно." : "Укажите публичный IP VPS, чтобы сохранить доступ по SSH при выходе через IX."}</FieldDescription></Field>
{suggested && !form.hub && <FieldDescription>Подставлен адрес из инвентаря CHR.</FieldDescription>}</Field>
{form.kind === "wireguard" && <Field><FieldLabel htmlFor="ix-linux-key">Публичный ключ Linux</FieldLabel>
<Input id="ix-linux-key" value={form.key} required onChange={event => patch({ key: event.target.value })} />
<FieldDescription>Создайте ключ на Linux командой <code>wg genkey</code> и вставьте результат <code>wg pubkey</code>.</FieldDescription>
</Field>}
<Field><FieldLabel htmlFor="ix-linux-exit">Выход трафика</FieldLabel> <Field><FieldLabel htmlFor="ix-linux-exit">Выход трафика</FieldLabel>
<Select value={form.exit} items={exits} onValueChange={value => value && patch({ exit: value })}> <Select value={form.exit} items={exits} onValueChange={value => { if (value) patch({ exit: value, transitLocal: "", transitRemote: "" }) }}>
<SelectTrigger id="ix-linux-exit" className="w-full"><SelectValue /></SelectTrigger> <SelectTrigger id="ix-linux-exit" className="w-full"><SelectValue /></SelectTrigger>
<SelectContent>{exits.map(item => <SelectItem key={item.value} value={item.value}>{item.label}</SelectItem>)}</SelectContent> <SelectContent>{exits.map(item => <SelectItem key={item.value} value={item.value}>{item.label}</SelectItem>)}</SelectContent>
</Select> </Select>
<FieldDescription>Для другого IX или ExitNode выберите настроенную группу шлюзов.</FieldDescription> {!!targetId && <FieldDescription>IX создаст туннель до {nodeLabel(nodes, targetId)} для выхода в Интернет.</FieldDescription>}
</Field> </Field>
<Field><FieldLabel htmlFor="ix-linux-destinations">Разрешённые сети IX</FieldLabel> {!!targetId && !publicEndpoint(target.inventory) && (target.loading ? <p role="status" className="text-sm text-muted-foreground">Читаем WAN выходного узла…</p> :
<Textarea id="ix-linux-destinations" rows={2} value={form.destinations} placeholder="По одному CIDR на строку" onChange={event => patch({ destinations: event.target.value })} /> <Field><FieldLabel htmlFor="ix-transit-target">IPv4 выходного узла</FieldLabel>
<FieldDescription>Для этих сетей используются маршруты IX и BGP.</FieldDescription></Field> <Input id="ix-transit-target" value={form.transitRemote} onChange={event => patch({ transitRemote: event.target.value })} />
<details className="grid gap-3"> <FieldDescription>Укажите адрес интерфейса CHR для межузлового туннеля.</FieldDescription></Field>)}
<summary className="cursor-pointer font-medium">Адреса туннеля и сети за Linux</summary> {!!targetId && !suggested && !origin.loading && <Field><FieldLabel htmlFor="ix-transit-source">IPv4 узла IX для транзита</FieldLabel>
<Input id="ix-transit-source" value={localEndpoint} onChange={event => patch({ transitLocal: event.target.value })} /></Field>}
{form.exit === "isolated" && destinationsField}
<details className="grid gap-3" key={form.serverId + ":" + origin.loading + ":" + gre}
open={!origin.loading && (!hub || gre && !isIpv4String(hub)) || undefined}>
<summary className="cursor-pointer text-sm font-medium">Параметры туннеля</summary>
<div className="mt-3 grid gap-3"> <div className="mt-3 grid gap-3">
<Field><FieldLabel htmlFor="ix-linux-tunnel-local">Адрес IX в туннеле (CIDR)</FieldLabel> <Field><FieldLabel htmlFor="ix-linux-hub">Внешний адрес IX</FieldLabel>
<Input id="ix-linux-hub" value={form.hub || suggested} onChange={event => patch({ hub: event.target.value })} />
<FieldDescription>{origin.loading ? "Читаем адрес WAN с CHR…" : suggested ? "Адрес WAN для подключения VPS." : "Введите адрес IX, доступный с VPS."}</FieldDescription>
</Field>
{wireguard && <Field><FieldLabel htmlFor="ix-linux-key">Публичный ключ Linux</FieldLabel>
<Input id="ix-linux-key" value={form.key} placeholder="Создать автоматически" onChange={event => patch({ key: event.target.value })} />
<FieldDescription>Укажите ключ только для своей пары WireGuard.</FieldDescription></Field>}
{form.exit !== "isolated" && destinationsField}
{form.kind !== "both" && <><Field><FieldLabel htmlFor="ix-linux-tunnel-local">Адрес IX в туннеле (CIDR)</FieldLabel>
<Input id="ix-linux-tunnel-local" value={form.localAddress} placeholder="Автоматический IPv4" onChange={event => patch({ localAddress: event.target.value })} /></Field> <Input id="ix-linux-tunnel-local" value={form.localAddress} placeholder="Автоматический IPv4" onChange={event => patch({ localAddress: event.target.value })} /></Field>
<Field><FieldLabel htmlFor="ix-linux-tunnel-peer">Адрес Linux в туннеле</FieldLabel> <Field><FieldLabel htmlFor="ix-linux-tunnel-peer">Адрес Linux в туннеле</FieldLabel>
<Input id="ix-linux-tunnel-peer" value={form.peerAddress} placeholder="Автоматический IPv4" onChange={event => patch({ peerAddress: event.target.value })} /></Field> <Input id="ix-linux-tunnel-peer" value={form.peerAddress} placeholder="Автоматический IPv4" onChange={event => patch({ peerAddress: event.target.value })} /></Field></>}
<Field><FieldLabel htmlFor="ix-linux-prefixes">Сети за Linux</FieldLabel> <Field><FieldLabel htmlFor="ix-linux-prefixes">Сети за Linux</FieldLabel>
<Textarea id="ix-linux-prefixes" rows={2} value={form.prefixes} onChange={event => patch({ prefixes: event.target.value })} /></Field> <Textarea id="ix-linux-prefixes" rows={2} value={form.prefixes} onChange={event => patch({ prefixes: event.target.value })} /></Field>
</div> </div>
</details> </details>
{edit && <div className="flex flex-wrap gap-2"> {binding && <div className="flex flex-wrap gap-2">
<Button type="button" size="sm" variant={form.enabled ? "outline" : "secondary"} aria-pressed={!form.enabled} <Button type="button" size="sm" variant={form.enabled ? "outline" : "secondary"} aria-pressed={!form.enabled}
onClick={() => patch({ enabled: !form.enabled })}>{form.enabled ? "Приостановить доступ" : "Возобновить доступ"}</Button> onClick={() => patch({ enabled: !form.enabled })}>{form.enabled ? "Приостановить доступ" : "Возобновить доступ"}</Button>
{form.kind === "gre-ipsec" && <Button type="button" size="sm" variant={rotate ? "secondary" : "outline"} {form.kind === "gre-ipsec" && <Button type="button" size="sm" variant={rotate ? "secondary" : "outline"}
aria-pressed={rotate} onClick={() => setRotate(!rotate)}>Выпустить новый PSK</Button>} aria-pressed={rotate} onClick={() => setRotate(!rotate)}>Выпустить новый PSK</Button>}
</div>} </div>}
</div> </div>
<SheetFooter><Button type="submit" disabled={!valid || busy}>{edit ? "Проверить изменения" : "Подготовить доступ"}</Button> <SheetFooter>{(gre || !form.key) && <p className="text-sm text-muted-foreground">После подтверждения файлы подключения будут доступны в таблице.</p>}
<Button type="submit" disabled={!valid || busy}>{companion ? "Добавить туннель" : "Сохранить"}</Button>
<Button type="button" variant="outline" disabled={busy} onClick={cancel}>Отмена</Button></SheetFooter> <Button type="button" variant="outline" disabled={busy} onClick={cancel}>Отмена</Button></SheetFooter>
</form> </form>
} }
export function IxLinuxClients({ segment, nodes, backendUrl, applied, readOnly, busy, error, save, refresh, revoke, view, inspect }: { function TunnelTable({ data, columns, busy }: {
data: IxLinuxBinding[]; columns: ColumnDef<DataGridFeatures, IxLinuxBinding>[]; busy: boolean
}) {
const table = useTable({ features: dataGridFeatures, manualPagination: true, data, columns,
getRowId: row => row.serverId + ":" + row.interfaceName })
return <DataGridShell table={table} recordCount={data.length} isLoading={busy && !data.length} loadingMode="skeleton" emptyMessage="В сегменте пока нет Linux-клиентов" />
}
export function IxLinuxClients({ segment, nodes, backendUrl, applied, readOnly, busy, error, save, refresh, revoke, view, copyImport, inspect, bondAction, catalog, renderGroups, manualGroup }: {
segment: IxSegment; nodes: IxNode[]; backendUrl: string; applied: IxLinuxBinding[]; readOnly: boolean; busy: boolean; error?: string segment: IxSegment; nodes: IxNode[]; backendUrl: string; applied: IxLinuxBinding[]; readOnly: boolean; busy: boolean; error?: string
save: (input: IxLinuxClientRequest) => Promise<boolean>; refresh: () => void save: (input: IxLinuxClientRequest) => Promise<boolean>; refresh: () => void
view: (binding: IxLinuxBinding) => void; revoke: (binding: IxLinuxBinding) => void view: (binding: IxLinuxBinding, transportOnly?: boolean) => void; revoke: (binding: IxLinuxBinding) => void
inspect: (binding: IxLinuxBinding) => void copyImport: (binding: IxLinuxBinding) => void; inspect: (binding: IxLinuxBinding) => void
bondAction: IxRowBondAction; catalog: IxBondCatalog
renderGroups: (clientId: string) => ReactNode; manualGroup: ReactNode
}) { }) {
const [open, setOpen] = useState(false) const [open, setOpen] = useState(false)
const [edit, setEdit] = useState<{ site: IxSite; binding: Binding } | null>(null) const [edit, setEdit] = useState<ClientSelection | null>(null)
const rows = useMemo(() => { const rows = useMemo(() => {
const saved = segment.configuration.sites.flatMap(site => site.interfaces.flatMap(binding => binding.linux ? [{ const saved = segment.configuration.sites.flatMap(site => site.interfaces.flatMap(binding => binding.linux ? [{
serverId: site.serverId, interfaceName: binding.name, kind: binding.kind as IxLinuxBinding["kind"], serverId: site.serverId, interfaceName: binding.name, kind: binding.kind as IxLinuxBinding["kind"],
policy: binding.linux, name: binding.linux.name, enabled: binding.linux.enabled, policy: binding.linux, name: binding.linux.name, enabled: binding.linux.enabled,
connection: applied.find(item => item.serverId === site.serverId && item.interfaceName === binding.name)?.connection, connection: applied.find(item => item.serverId === site.serverId && item.interfaceName === binding.name)?.connection,
}] : [])) }] : []))
return [...saved, ...applied.filter(binding => !binding.policy && !saved.some(item => item.serverId === binding.serverId && item.interfaceName === binding.interfaceName))] return [...saved, ...applied.filter(binding => !saved.some(item => item.serverId === binding.serverId && item.interfaceName === binding.interfaceName))]
}, [segment, applied]) }, [segment, applied])
const clients = new Map<string, { name: string; tunnels: IxLinuxBinding[]; hasGroups: boolean }>()
const relevantGroups = catalog.groups.filter(group => group.members.some(member => member.segmentId === segment.id))
const tunnelKey = (binding: Pick<IxLinuxBinding, "serverId" | "interfaceName">) => binding.serverId + ":" + binding.interfaceName
const affiliations = new Map(relevantGroups.flatMap(group => group.members.filter(member => member.segmentId === segment.id)
.map(member => [tunnelKey(member), group.clientId] as const)))
for (const row of rows) {
const key = affiliations.get(tunnelKey(row)) ?? row.policy?.clientId ?? tunnelKey(row)
const client = clients.get(key) ?? { name: row.name ?? row.interfaceName, tunnels: [], hasGroups: false }
if (row.name && !client.tunnels.some(tunnel => tunnel.name)) client.name = row.name
client.tunnels.push(row)
clients.set(key, client)
}
for (const group of relevantGroups) {
const client = clients.get(group.clientId) ?? { name: group.name, tunnels: [], hasGroups: false }
client.hasGroups = true
clients.set(group.clientId, client)
}
const columns = useMemo<ColumnDef<DataGridFeatures, IxLinuxBinding>[]>(() => [ const columns = useMemo<ColumnDef<DataGridFeatures, IxLinuxBinding>[]>(() => [
{ id: "name", header: "Клиент", cell: ({ row }) => <span className="font-medium">{row.original.name ?? row.original.interfaceName}</span> }, { id: "name", header: "Интерфейс", size: 195, cell: ({ row }) => <div className="grid gap-0.5">
{ id: "node", header: "Узел IX", cell: ({ row }) => nodeLabel(nodes, row.original.serverId) }, <span className="break-all font-medium">{row.original.interfaceName}</span>
{ id: "transport", header: "Туннель", cell: ({ row }) => row.original.kind === "wireguard" ? "WireGuard" : "GRE/IPsec" }, <span className="text-xs text-muted-foreground">{nodeLabel(nodes, row.original.serverId)}</span>
{ id: "egress", header: "Выход", cell: ({ row }) => row.original.policy?.exit ?? "Сети IX" }, </div> },
{ id: "state", header: "Состояние", cell: ({ row }) => { { id: "transport", header: "Туннель", size: 105, cell: ({ row }) => row.original.kind === "wireguard" ? "WireGuard" : "GRE/IPsec" },
const binding = row.original { id: "egress", header: "Выход трафика", size: 205, cell: ({ row }) => {
if (!binding.policy) return <Badge variant="secondary">Прежняя настройка</Badge> const client = row.original
if (!applied.some(item => item.serverId === binding.serverId && item.interfaceName === binding.interfaceName)) return <Badge variant="warning-light">Черновик</Badge> const site = segment.configuration.sites.find(item => item.serverId === client.serverId)
if (!binding.enabled) return <Badge variant="secondary">Приостановлен</Badge> const binding = site?.interfaces.find(item => item.name === client.interfaceName)
return binding.connection?.state === "connected" ? <div className="grid gap-1"> const group = site?.groups.find(item => item.id === client.policy?.exit)
<Badge variant="success-light" className="w-fit">Подключён</Badge> const label = site && group ? groupLabel(group, site, nodes) : client.policy ? client.policy.exit ?? "Только сети IX" : "По настройкам интерфейса"
{binding.connection.rx !== undefined && <span className="text-xs text-muted-foreground">RX {binding.connection.rx} · TX {binding.connection.tx}</span>} return readOnly || !site || !binding?.linux ? label : <Button type="button" size="sm" variant="link" className="max-w-full"
</div> disabled={busy} aria-label={"Доступ и выход клиента " + client.name} onClick={() => { setEdit({ site, binding }); setOpen(true) }}>
: <Badge variant="secondary">{binding.connection?.state === "waiting" ? "Ожидает туннель" : "Нет данных"}</Badge> <span className="truncate">{label}</span><PencilIcon aria-hidden />
</Button>
} }, } },
{ id: "actions", header: "Действия", cell: ({ row }) => { { id: "state", header: "Состояние", size: 160, cell: ({ row }) => {
const binding = row.original
if (!binding.policy) return <div className="grid gap-1"><Badge className="w-fit" variant="secondary">Прежняя настройка</Badge>
{!catalog.candidates.some(c => c.segmentId === segment.id && c.serverId === binding.serverId && c.interfaceName === binding.interfaceName) &&
<span className="text-xs text-muted-foreground">Параметры ручного туннеля проверяются при добавлении из RouterOS.</span>}</div>
const live = applied.find(item => item.serverId === binding.serverId && item.interfaceName === binding.interfaceName)
const site = segment.configuration.sites.find(item => item.serverId === binding.serverId)
if (!site?.interfaces.some(item => item.name === binding.interfaceName)) return <Badge variant="warning-light">Ожидает отзыва</Badge>
if (!live || JSON.stringify(binding.policy) !== JSON.stringify(live.policy)) return <Badge variant="warning-light">Ожидает сохранения</Badge>
if (!binding.enabled) return <Badge variant="secondary">Приостановлен</Badge>
const { state, rx, tx } = binding.connection ?? {}
return <div className="grid gap-1">
<Badge className="w-fit" variant={state === "connected" ? "success-light" : "secondary"}>
{state === "connected" ? "Подключён" : state === "waiting" ? "Ожидает туннель" : "Нет данных"}
</Badge>
{(rx !== undefined || tx !== undefined) && <span className="text-xs text-muted-foreground" title="Счётчики на узле IX">
RX {rx !== undefined ? formatBytes(Number(rx)) : "—"} · TX {tx !== undefined ? formatBytes(Number(tx)) : "—"}
</span>}
</div>
} },
{ id: "actions", header: "Действия", size: 140, cell: ({ row }) => {
const binding = row.original const binding = row.original
const site = segment.configuration.sites.find(site => site.serverId === binding.serverId) const site = segment.configuration.sites.find(site => site.serverId === binding.serverId)
const saved = site?.interfaces.find(candidate => candidate.name === binding.interfaceName) const saved = site?.interfaces.find(candidate => candidate.name === binding.interfaceName)
const canDownload = applied.some(item => item.serverId === binding.serverId && item.interfaceName === binding.interfaceName && item.enabled !== false) const paired = !!site && !!saved && hasCompanion(site, saved)
const live = applied.find(item => item.serverId === binding.serverId && item.interfaceName === binding.interfaceName && item.enabled !== false)
const bond = !readOnly && bondAction(binding)
return <div className="flex flex-wrap gap-1"> return <div className="flex flex-wrap gap-1">
{canDownload && <Button size="sm" variant="outline" disabled={busy} aria-label={"Получить конфиг " + (binding.name ?? binding.interfaceName)} {live && <Button size="sm" variant="outline" disabled={busy} aria-label={"Получить конфиг " + (binding.name ?? binding.interfaceName) +
onClick={() => view(binding)}>Конфиг Linux</Button>} (paired ? binding.kind === "wireguard" ? " · WireGuard" : " · GRE/IPsec" : "")}
{canDownload && binding.policy && <Button size="sm" variant="ghost" disabled={busy} onClick={() => inspect(binding)}>Проверить путь</Button>} onClick={() => view(live)}>Конфиг Linux</Button>}
{!readOnly && site && saved?.linux && <> {(bond || binding.policy && (live || !readOnly && saved?.linux)) && <DropdownMenu>
<Button size="sm" variant="ghost" disabled={busy} onClick={() => { setEdit({ site, binding: saved }); setOpen(true) }}>Доступ и выход</Button> <DropdownMenuTrigger render={<Button type="button" size="icon-sm" variant="ghost" disabled={busy} aria-label={"Действия клиента " +
<Button size="sm" variant="ghost" disabled={busy} onClick={() => revoke(binding)}>Отозвать…</Button> (binding.name ?? binding.interfaceName) + (paired ? " · " + binding.interfaceName : "")} />}>
</>} <EllipsisIcon aria-hidden />
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
{bond && <DropdownMenuItem onClick={bond.open}>{bond.label}</DropdownMenuItem>}
{live && (binding.policy || catalog.candidates.some(c => c.segmentId === segment.id && c.serverId === live.serverId && c.interfaceName === live.interfaceName)) &&
<DropdownMenuItem onClick={() => view(live, true)}>Конфиг для группы ix-client</DropdownMenuItem>}
{!readOnly && live?.policy && (live.managedWireguard || live.kind === "gre-ipsec") &&
<DropdownMenuItem onClick={() => copyImport(live)}>Скопировать ссылку для ix-client</DropdownMenuItem>}
{live?.policy && <DropdownMenuItem onClick={() => inspect(live)}>Проверить путь</DropdownMenuItem>}
{!readOnly && site && saved?.linux && <DropdownMenuItem
onClick={() => { setEdit({ site, binding: saved, addProtocol: true, chooseTransport: true }); setOpen(true) }}>Добавить туннель</DropdownMenuItem>}
{!readOnly && saved?.linux && <DropdownMenuItem variant="destructive" onClick={() => revoke(binding)}>Отозвать доступ…</DropdownMenuItem>}
</DropdownMenuContent>
</DropdownMenu>}
</div> </div>
} }, } },
], [nodes, applied, segment.configuration.sites, readOnly, busy, view, revoke, inspect]) ], [nodes, applied, segment, readOnly, busy, view, copyImport, revoke, inspect, bondAction, catalog.candidates])
const table = useTable({ features: dataGridFeatures, manualPagination: true, data: rows, columns,
getRowId: row => row.serverId + ":" + row.interfaceName })
return <Frame spacing="sm" className="min-w-0"> return <Frame spacing="sm" className="min-w-0">
<FrameHeader className="flex-row flex-wrap items-center justify-between gap-2"> <FrameHeader className="flex-row flex-wrap items-center justify-between gap-2">
<FrameTitle>Linux-клиенты</FrameTitle> <FrameTitle>Linux-клиенты</FrameTitle>
<div className="flex flex-wrap items-center gap-2"> <div className="flex flex-wrap items-center gap-2">
<Button type="button" size="icon-sm" variant="outline" aria-label="Обновить клиентов" disabled={busy || !segment.appliedRevision} onClick={refresh}><RefreshCwIcon /></Button> <Button type="button" size="icon-sm" variant="outline" aria-label="Обновить клиентов" disabled={busy || !segment.appliedRevision} onClick={refresh}><RefreshCwIcon /></Button>
{!readOnly && <Button type="button" size="sm" disabled={busy} onClick={() => { setEdit(null); setOpen(true) }}><PlusIcon />Подключить Linux</Button>} {!readOnly && <Button type="button" size="sm" disabled={busy} onClick={() => { setEdit(null); setOpen(true) }}><PlusIcon />Подключить Linux</Button>}
{manualGroup}
</div> </div>
</FrameHeader> </FrameHeader>
<FramePanel className="min-w-0 p-0"> {clients.size ? [...clients].map(([key, client]) => <FramePanel key={key} className="grid min-w-0 gap-3 p-0">
<DataGridShell table={table} recordCount={rows.length} isLoading={busy && !rows.length} loadingMode="skeleton" emptyMessage="В сегменте пока нет Linux-клиентов" /> <section aria-label={"Клиент " + client.name} className="grid min-w-0 gap-3">
</FramePanel> <h3 className="px-4 pt-3 text-sm font-semibold">{client.name}</h3>
{!!client.tunnels.length && <TunnelTable data={client.tunnels} columns={columns} busy={busy} />}
{client.hasGroups && <div className="grid gap-3 px-4 pb-4">
<h4 className="text-sm font-medium">Группы туннелей</h4>
{renderGroups(key)}
</div>}
</section>
</FramePanel>) : <FramePanel className="min-w-0 p-0"><TunnelTable data={rows} columns={columns} busy={busy} /></FramePanel>}
<Sheet open={open} onOpenChange={value => !busy && setOpen(value)}> <Sheet open={open} onOpenChange={value => !busy && setOpen(value)}>
<SheetContent className="w-full sm:max-w-lg"> <SheetContent className="data-[side=right]:w-full data-[side=right]:sm:max-w-lg" showCloseButton={!busy}>
<SheetHeader><SheetTitle>{edit ? "Доступ и выход клиента" : "Подключить Linux"}</SheetTitle> <SheetHeader><SheetTitle>{edit?.chooseTransport ? "Добавить туннель" : edit?.addProtocol ? "Добавить другой протокол" : edit ? "Доступ и выход клиента" : "Подключить Linux"}</SheetTitle>
<SheetDescription>Настройте туннель и проверьте план перед применением к RouterOS.</SheetDescription> <SheetDescription>Укажите VPS и выберите, куда направлять его трафик.</SheetDescription>
{error && <p className="text-sm text-destructive" role="alert">{error}</p>} {error && <p className="text-sm text-destructive" role="alert">{error}</p>}
</SheetHeader> </SheetHeader>
{open && <ClientForm segment={segment} edit={edit} nodes={nodes} backendUrl={backendUrl} busy={busy} {open && <ClientForm segment={segment} edit={edit} nodes={nodes} backendUrl={backendUrl} catalog={catalog} busy={busy}
setAddProtocol={addProtocol => setEdit(selection => selection && { ...selection, addProtocol })}
save={async input => { if (await save(input)) setOpen(false) }} cancel={() => setOpen(false)} />} save={async input => { if (await save(input)) setOpen(false) }} cancel={() => setOpen(false)} />}
</SheetContent> </SheetContent>
</Sheet> </Sheet>
+37 -32
View File
@@ -1,6 +1,6 @@
"use client" "use client"
import { useId, type ReactNode } from "react" import { useId, useState, type ReactNode } from "react"
import Link from "next/link" import Link from "next/link"
import { PlusIcon, XIcon } from "lucide-react" import { PlusIcon, XIcon } from "lucide-react"
import type { IxNodeInventory, IxSite } from "@mmapp/contracts/internet-exchange" import type { IxNodeInventory, IxSite } from "@mmapp/contracts/internet-exchange"
@@ -62,25 +62,29 @@ function Lines({ label, value, edit }: { label: string; value: string[]; edit: (
</Field> </Field>
} }
function Entries<T>({ title, items, edit, make, addLabel, max, readOnly, children }: { function Entries<T>({ title, items, edit, make, addLabel, max, readOnly, children, label, visible }: {
title: string; items: T[]; edit: (items: T[]) => void; make: () => T title: string; items: T[]; edit: (items: T[]) => void; make: () => T
addLabel: string; max: number; readOnly: boolean; children: (item: T, edit: (item: T) => void) => ReactNode addLabel: string; max: number; readOnly: boolean; children: (item: T, edit: (item: T) => void) => ReactNode
label?: (item: T) => string; visible?: (item: T) => boolean
}) { }) {
return <details className="min-w-0 rounded-lg border"> const [expanded, setExpanded] = useState<number | null>(null)
<summary className="cursor-pointer px-3 py-2 text-sm font-medium">{title} · {items.length}</summary> const rows = items.map((item, index) => ({ item, index })).filter(({ item }) => !visible || visible(item))
<div className="grid gap-3 border-t p-3"> return <section className="grid min-w-0 gap-2 border-t py-3">
{items.map((item, index) => <div className="grid min-w-0 gap-3 rounded-md border p-3" key={index}> <div className="flex flex-wrap items-center justify-between gap-2">
<div className="flex items-center justify-between gap-2 text-sm text-muted-foreground"> <h4 className="text-sm font-medium">{title} <span className="text-muted-foreground">· {rows.length}</span></h4>
<span>Запись {index + 1}</span> {!readOnly && <Button type="button" variant="outline" size="sm" disabled={items.length >= max}
{!readOnly && <Button type="button" size="icon-sm" variant="ghost" aria-label={title + " — удалить запись " + (index + 1)} onClick={() => { setExpanded(items.length); edit([...items, make()]) }}><PlusIcon aria-hidden />{addLabel}</Button>}
onClick={() => edit(items.filter((_, position) => position !== index))}><XIcon aria-hidden /></Button>}
</div>
{children(item, update => edit(items.map((entry, position) => position === index ? update : entry)))}
</div>)}
{!readOnly && <Button type="button" variant="outline" size="sm" className="w-fit" disabled={items.length >= max}
onClick={() => edit([...items, make()])}><PlusIcon aria-hidden />{addLabel}</Button>}
</div> </div>
</details> {rows.map(({ item, index }) => <div key={index} className="min-w-0 border-s-2 ps-3">
<Button type="button" size="sm" variant="ghost" aria-expanded={expanded === index}
onClick={() => setExpanded(expanded === index ? null : index)}>{label?.(item) || "Запись " + (index + 1)}</Button>
{expanded === index && <fieldset disabled={readOnly} className="grid gap-3 py-2">
{children(item, update => edit(items.map((entry, position) => position === index ? update : entry)))}
{!readOnly && <Button type="button" size="sm" className="w-fit" variant="ghost" aria-label={title + " — удалить запись " + (index + 1)}
onClick={() => { setExpanded(null); edit(items.filter((_, position) => position !== index)) }}><XIcon aria-hidden />Удалить</Button>}
</fieldset>}
</div>)}
</section>
} }
const columns = "grid min-w-0 gap-3 sm:grid-cols-2" const columns = "grid min-w-0 gap-3 sm:grid-cols-2"
@@ -156,7 +160,13 @@ function GroupFields({ value, edit, interfaces, inventory, alternatives, readOnl
value: Group; edit: (value: Group) => void; interfaces: Choice[]; inventory: IxNodeInventory["interfaces"] value: Group; edit: (value: Group) => void; interfaces: Choice[]; inventory: IxNodeInventory["interfaces"]
alternatives: Group[]; readOnly: boolean alternatives: Group[]; readOnly: boolean
}) { }) {
const selectedBackup = alternatives.find(other => other.primary.interface === value.backup?.interface &&
other.primary.nextHop === value.backup?.nextHop && other.primary.probe === value.backup?.probe)
return <> return <>
<Pick label="Резервный выход" value={value.backup ? selectedBackup?.id ?? ":manual" : ""} disabled={readOnly}
options={[none, ...alternatives.map(other => ({ value: other.id, label: other.id })), { value: ":manual", label: "Указать другой шлюз" }]}
edit={id => edit({ ...value, backup: id === ":manual" ? emptyPath(interfaces.find(item => item.value !== value.primary.interface)?.value ?? "")
: alternatives.find(other => other.id === id)?.primary })} />
<div className={columns}> <div className={columns}>
<TextField label="Имя группы шлюзов" value={value.id} edit={id => edit({ ...value, id })} /> <TextField label="Имя группы шлюзов" value={value.id} edit={id => edit({ ...value, id })} />
<TextField label="Служебный адрес шлюза" value={value.gateway} edit={gateway => edit({ ...value, gateway })} /> <TextField label="Служебный адрес шлюза" value={value.gateway} edit={gateway => edit({ ...value, gateway })} />
@@ -165,13 +175,8 @@ function GroupFields({ value, edit, interfaces, inventory, alternatives, readOnl
]} edit={onFailure => edit({ ...value, onFailure })} /> ]} edit={onFailure => edit({ ...value, onFailure })} />
</div> </div>
<PathFields title="Основной путь" value={value.primary} interfaces={interfaces} inventory={inventory} readOnly={readOnly} edit={primary => edit({ ...value, primary })} /> <PathFields title="Основной путь" value={value.primary} interfaces={interfaces} inventory={inventory} readOnly={readOnly} edit={primary => edit({ ...value, primary })} />
<Flag label="Резервный путь" checked={!!value.backup} disabled={readOnly} {value.backup && <PathFields title="Резервный путь" value={value.backup} interfaces={interfaces} inventory={inventory}
edit={enabled => edit({ ...value, backup: enabled ? emptyPath(interfaces.find(item => item.value !== value.primary.interface)?.value ?? "") : undefined })} /> readOnly={readOnly} edit={backup => edit({ ...value, backup })} />}
{value.backup && <>
{alternatives.length > 0 && <Pick label="Взять резерв из другого выхода" options={alternatives.map(group => ({ value: group.id, label: group.id }))}
disabled={readOnly} edit={id => { const backup = alternatives.find(group => group.id === id)?.primary; if (backup) edit({ ...value, backup }) }} />}
<PathFields title="Резервный путь" value={value.backup} interfaces={interfaces} inventory={inventory} readOnly={readOnly} edit={backup => edit({ ...value, backup })} />
</>}
</> </>
} }
@@ -212,38 +217,38 @@ export function IxSiteEditor({ site, edit, peers, readOnly, segmentName, invento
}) { }) {
const interfaces = site.interfaces.filter(item => item.name).map(item => ({ value: item.name, label: item.name })) const interfaces = site.interfaces.filter(item => item.name).map(item => ({ value: item.name, label: item.name }))
const groups = site.groups.filter(item => item.id).map(item => ({ value: item.id, label: item.id })) const groups = site.groups.filter(item => item.id).map(item => ({ value: item.id, label: item.id }))
return <fieldset className="grid min-w-0 gap-2" disabled={readOnly}> return <div className="grid min-w-0 gap-2">
<Entries<Binding> title="Подключения" items={site.interfaces} edit={interfaces => edit({ interfaces })} <Entries<Binding> title="Интерфейсы маршрутизации" label={item => item.name} visible={item => !item.linux && !item.provisionTransit} items={site.interfaces} edit={interfaces => edit({ interfaces })}
make={() => ({ name: "", kind: "wireguard", prefixes: [] })} max={80} addLabel="Добавить подключение" readOnly={readOnly}> make={() => ({ name: "", kind: "wireguard", prefixes: [] })} max={80} addLabel="Добавить интерфейс" readOnly={readOnly}>
{(value, update) => <InterfaceFields value={value} edit={update} peers={peers} readOnly={readOnly} segmentName={segmentName} inventory={inventory} />} {(value, update) => <InterfaceFields value={value} edit={update} peers={peers} readOnly={readOnly} segmentName={segmentName} inventory={inventory} />}
</Entries> </Entries>
<Entries<Group> title="Группы шлюзов" items={site.groups} edit={groups => edit({ groups })} <Entries<Group> title="Выходы и резерв" label={item => item.id} items={site.groups} edit={groups => edit({ groups })}
make={() => ({ id: "", gateway: "", primary: emptyPath(interfaces[0]?.value ?? ""), onFailure: "block" })} make={() => ({ id: "", gateway: "", primary: emptyPath(interfaces[0]?.value ?? ""), onFailure: "block" })}
max={24} addLabel="Добавить группу шлюзов" readOnly={readOnly}> max={24} addLabel="Добавить группу шлюзов" readOnly={readOnly}>
{(value, update) => <GroupFields value={value} edit={update} interfaces={interfaces} inventory={inventory} {(value, update) => <GroupFields value={value} edit={update} interfaces={interfaces} inventory={inventory}
alternatives={site.groups.filter(group => group.id !== value.id && group.primary.interface !== value.primary.interface && alternatives={site.groups.filter(group => group.id !== value.id && group.primary.interface !== value.primary.interface &&
group.gateway.includes(":") === value.gateway.includes(":"))} readOnly={readOnly} />} group.gateway.includes(":") === value.gateway.includes(":"))} readOnly={readOnly} />}
</Entries> </Entries>
<Entries title="Статические маршруты" items={site.routes} edit={routes => edit({ routes })} <Entries title="Статические маршруты" label={item => item.prefix} items={site.routes} edit={routes => edit({ routes })}
make={() => ({ prefix: "", group: groups[0]?.value ?? "" })} max={250} addLabel="Добавить маршрут" readOnly={readOnly}> make={() => ({ prefix: "", group: groups[0]?.value ?? "" })} max={250} addLabel="Добавить маршрут" readOnly={readOnly}>
{(route, update) => <div className={columns}> {(route, update) => <div className={columns}>
<TextField label="Префикс маршрута" value={route.prefix} edit={prefix => update({ ...route, prefix })} /> <TextField label="Префикс маршрута" value={route.prefix} edit={prefix => update({ ...route, prefix })} />
<Pick label="Группа шлюзов маршрута" value={route.group} options={groups} edit={group => update({ ...route, group })} disabled={readOnly} /> <Pick label="Группа шлюзов маршрута" value={route.group} options={groups} edit={group => update({ ...route, group })} disabled={readOnly} />
</div>} </div>}
</Entries> </Entries>
<Entries<Peer> title="BGP-соседи" items={site.neighbors} edit={neighbors => edit({ neighbors })} max={16} addLabel="Добавить BGP-соседа" readOnly={readOnly} <Entries<Peer> title="BGP-соседи" label={item => item.id} items={site.neighbors} edit={neighbors => edit({ neighbors })} max={16} addLabel="Добавить BGP-соседа" readOnly={readOnly}
make={() => ({ id: "", type: "member", address: "", localAddress: "", remoteAs: 0, make={() => ({ id: "", type: "member", address: "", localAddress: "", remoteAs: 0,
binding: interfaces[0]?.value ?? "", group: groups[0]?.value, prefixes: [], exportPrefixes: [], rules: [], limit: 1000 })}> binding: interfaces[0]?.value ?? "", group: groups[0]?.value, prefixes: [], exportPrefixes: [], rules: [], limit: 1000 })}>
{(value, update) => <PeerFields value={value} edit={update} interfaces={interfaces} groups={groups} readOnly={readOnly} />} {(value, update) => <PeerFields value={value} edit={update} interfaces={interfaces} groups={groups} readOnly={readOnly} />}
</Entries> </Entries>
<details className="rounded-lg border"> <details className="rounded-lg border">
<summary className="cursor-pointer px-3 py-2 text-sm font-medium">Выходы по умолчанию и маршруты отбрасывания</summary> <summary className="cursor-pointer px-3 py-2 text-sm font-medium">Выходы по умолчанию и маршруты отбрасывания</summary>
<div className="grid gap-3 border-t p-3"> <fieldset disabled={readOnly} className="grid gap-3 border-t p-3">
{[0, 1].map(index => <Pick key={index} label={"Группа выхода " + (index + 1)} value={site.exits[index] ?? ""} {[0, 1].map(index => <Pick key={index} label={"Группа выхода " + (index + 1)} value={site.exits[index] ?? ""}
options={[none, ...groups.filter(group => group.value !== site.exits[1 - index])]} disabled={readOnly} options={[none, ...groups.filter(group => group.value !== site.exits[1 - index])]} disabled={readOnly}
edit={id => { const exits = [...site.exits]; exits[index] = id; edit({ exits: exits.filter(Boolean) }) }} />)} edit={id => { const exits = [...site.exits]; exits[index] = id; edit({ exits: exits.filter(Boolean) }) }} />)}
<Lines label="Префиксы отбрасывания" value={site.discardNetworks} edit={discardNetworks => edit({ discardNetworks })} /> <Lines label="Префиксы отбрасывания" value={site.discardNetworks} edit={discardNetworks => edit({ discardNetworks })} />
</div> </fieldset>
</details> </details>
</fieldset> </div>
} }
+15 -15
View File
@@ -41,8 +41,8 @@ export function SegmentGrid({ rows, nodes, loading, open, empty }: {
</Button> </Button>
) }, ) },
{ id: "sites", header: "Площадки", size: 230, cell: ({ row }) => row.original.configuration.sites.map(site => nodeLabel(nodes, site.serverId)).join(", ") }, { id: "sites", header: "Площадки", size: 230, cell: ({ row }) => row.original.configuration.sites.map(site => nodeLabel(nodes, site.serverId)).join(", ") },
{ id: "neighbors", header: "BGP-соседи", size: 115, cell: ({ row }) => { id: "clients", header: "Linux-клиенты", size: 125, cell: ({ row }) =>
<span className="tabular-nums">{row.original.configuration.sites.reduce((total, site) => total + site.neighbors.length, 0)}</span> }, <span className="tabular-nums">{row.original.configuration.sites.reduce((total, site) => total + site.interfaces.filter(item => item.linux).length, 0)}</span> },
{ id: "state", header: "Состояние", size: 140, cell: ({ row }) => <SegmentStatus segment={row.original} /> }, { id: "state", header: "Состояние", size: 140, cell: ({ row }) => <SegmentStatus segment={row.original} /> },
], [nodes, open]) ], [nodes, open])
const table = useTable({ features: dataGridFeatures, manualPagination: true, data: rows, columns, getRowId: row => row.id }) const table = useTable({ features: dataGridFeatures, manualPagination: true, data: rows, columns, getRowId: row => row.id })
@@ -95,7 +95,8 @@ function IxInventoryFields({ site, segmentId, backendUrl, fieldId, peers, readOn
</> </>
} }
export function ConfigurationFields({ configuration, nodes, peers, readOnly, change, backendUrl, segmentId }: { export function ConfigurationFields({ configuration, nodes, peers, readOnly, change, backendUrl, segmentId, section }: {
section: "configuration" | "routes"
configuration: IxConfiguration; nodes: IxNode[]; peers: IxNode[]; readOnly: boolean; change: (value: IxConfiguration) => void configuration: IxConfiguration; nodes: IxNode[]; peers: IxNode[]; readOnly: boolean; change: (value: IxConfiguration) => void
backendUrl: string; segmentId?: string backendUrl: string; segmentId?: string
}) { }) {
@@ -105,7 +106,7 @@ export function ConfigurationFields({ configuration, nodes, peers, readOnly, cha
const canAddSite = configuration.sites.length < 2 && nodes.filter(node => node.enabled).length > configuration.sites.length const canAddSite = configuration.sites.length < 2 && nodes.filter(node => node.enabled).length > configuration.sites.length
return <div className="grid min-w-0 gap-3"> return <div className="grid min-w-0 gap-3">
<Frame spacing="sm"> {section === "configuration" && <Frame spacing="sm">
<FrameHeader><FrameTitle>Сегмент</FrameTitle></FrameHeader> <FrameHeader><FrameTitle>Сегмент</FrameTitle></FrameHeader>
<FramePanel> <FramePanel>
<Field className="max-w-md"> <Field className="max-w-md">
@@ -115,17 +116,16 @@ export function ConfigurationFields({ configuration, nodes, peers, readOnly, cha
{!readOnly && <FieldDescription>Латинские строчные буквы, цифры и дефисы.</FieldDescription>} {!readOnly && <FieldDescription>Латинские строчные буквы, цифры и дефисы.</FieldDescription>}
</Field> </Field>
</FramePanel> </FramePanel>
</Frame> </Frame>}
{configuration.sites.map((site, index) => { {configuration.sites.map((site, index) => {
const fieldId = `ix-site-${index}` const fieldId = `ix-site-${index}`
const choices = nodes.filter(node => node.id === site.serverId || (node.enabled && !configuration.sites.some((other, i) => i !== index && other.serverId === node.id))) const choices = nodes.filter(node => node.id === site.serverId || (node.enabled && !configuration.sites.some((other, i) => i !== index && other.serverId === node.id)))
return <Frame key={fieldId} spacing="sm"> return <Frame key={fieldId} spacing="sm">
<FrameHeader className="flex-row items-center justify-between gap-2"> <FrameHeader className="flex-row items-center justify-between gap-2">
<div className="min-w-0"> <div className="min-w-0">
<FrameTitle>Площадка {index + 1}</FrameTitle> <FrameTitle>{section === "configuration" ? "Площадка " + (index + 1) : nodeLabel(nodes, site.serverId)}</FrameTitle>
{site.serverId > 0 && <FrameDescription className="wrap-anywhere">{nodeLabel(nodes, site.serverId)}</FrameDescription>}
</div> </div>
{!readOnly && configuration.sites.length > 1 && <Button type="button" size="icon-sm" variant="ghost" {section === "configuration" && !readOnly && configuration.sites.length > 1 && <Button type="button" size="icon-sm" variant="ghost"
aria-label={`Убрать площадку ${index + 1}`} aria-label={`Убрать площадку ${index + 1}`}
onClick={() => change({ ...configuration, sites: configuration.sites.filter((_, position) => position !== index) })}> onClick={() => change({ ...configuration, sites: configuration.sites.filter((_, position) => position !== index) })}>
<XIcon aria-hidden /> <XIcon aria-hidden />
@@ -133,7 +133,7 @@ export function ConfigurationFields({ configuration, nodes, peers, readOnly, cha
</FrameHeader> </FrameHeader>
<FramePanel className="grid gap-4"> <FramePanel className="grid gap-4">
<div className="grid min-w-0 gap-3 sm:grid-cols-2 lg:grid-cols-3"> <div className="grid min-w-0 gap-3 sm:grid-cols-2 lg:grid-cols-3">
<Field className="min-w-0"> {section === "configuration" && <Field className="min-w-0">
<FieldLabel htmlFor={fieldId}>Узел IX</FieldLabel> <FieldLabel htmlFor={fieldId}>Узел IX</FieldLabel>
<Select <Select
value={site.serverId ? String(site.serverId) : null} value={site.serverId ? String(site.serverId) : null}
@@ -146,21 +146,21 @@ export function ConfigurationFields({ configuration, nodes, peers, readOnly, cha
{choices.map(node => <SelectItem key={node.id} value={String(node.id)} disabled={!node.enabled}>{node.name}</SelectItem>)} {choices.map(node => <SelectItem key={node.id} value={String(node.id)} disabled={!node.enabled}>{node.name}</SelectItem>)}
</SelectContent> </SelectContent>
</Select> </Select>
</Field> </Field>}
<Field className="min-w-0"> {section === "routes" && <Field className="min-w-0">
<FieldLabel htmlFor={fieldId + "-asn"}>Локальный ASN</FieldLabel> <FieldLabel htmlFor={fieldId + "-asn"}>Локальный ASN</FieldLabel>
<Input id={fieldId + "-asn"} inputMode="numeric" value={site.autonomousSystem || ""} readOnly={readOnly} <Input id={fieldId + "-asn"} inputMode="numeric" value={site.autonomousSystem || ""} readOnly={readOnly}
onChange={event => { if (/^\d*$/.test(event.target.value)) updateSite(index, { autonomousSystem: Number(event.target.value) }) }} /> onChange={event => { if (/^\d*$/.test(event.target.value)) updateSite(index, { autonomousSystem: Number(event.target.value) }) }} />
</Field> </Field>}
<IxInventoryFields site={site} segmentId={segmentId} backendUrl={backendUrl} fieldId={fieldId} {section !== "configuration" && <IxInventoryFields site={site} segmentId={segmentId} backendUrl={backendUrl} fieldId={fieldId}
readOnly={readOnly} segmentName={configuration.name} edit={fields => updateSite(index, fields)} readOnly={readOnly} segmentName={configuration.name} edit={fields => updateSite(index, fields)}
peers={peers.filter(node => node.id !== site.serverId && (node.enabled || site.interfaces.some(binding => binding.peerServerId === node.id))) peers={peers.filter(node => node.id !== site.serverId && (node.enabled || site.interfaces.some(binding => binding.peerServerId === node.id)))
.map(node => ({ value: String(node.id), label: node.name }))} /> .map(node => ({ value: String(node.id), label: node.name }))} />}
</div> </div>
</FramePanel> </FramePanel>
</Frame> </Frame>
})} })}
{!readOnly && canAddSite && <Button type="button" variant="outline" size="sm" className="w-fit" {section === "configuration" && !readOnly && canAddSite && <Button type="button" variant="outline" size="sm" className="w-fit"
onClick={() => change({ ...configuration, sites: [...configuration.sites, newSite()] })}> onClick={() => change({ ...configuration, sites: [...configuration.sites, newSite()] })}>
<PlusIcon aria-hidden />Добавить площадку <PlusIcon aria-hidden />Добавить площадку
</Button>} </Button>}
+156 -137
View File
@@ -12,6 +12,7 @@ import { ServerRailLayout, ServerRailMobileButton } from "@/components/server-ra
import { ALL_SERVERS_ID } from "@/components/server-tile-rail" import { ALL_SERVERS_ID } from "@/components/server-tile-rail"
import { Button } from "@/components/ui/button" import { Button } from "@/components/ui/button"
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, AlertDialogTrigger } from "@/components/ui/alert-dialog" import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, AlertDialogTrigger } from "@/components/ui/alert-dialog"
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog"
import { Input } from "@/components/ui/input" import { Input } from "@/components/ui/input"
import { Skeleton } from "@/components/ui/skeleton" import { Skeleton } from "@/components/ui/skeleton"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs" import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
@@ -22,8 +23,10 @@ import { requestJson } from "@/shared/api/http-client"
import { ConfigurationFields, newSite, nodeLabel, RouteGrid, SegmentGrid, SegmentStatus, type IxNode } from "./ix-view" import { ConfigurationFields, newSite, nodeLabel, RouteGrid, SegmentGrid, SegmentStatus, type IxNode } from "./ix-view"
import { IxLinuxClients } from "./ix-linux-clients" import { IxLinuxClients } from "./ix-linux-clients"
import { IxExits } from "./ix-exits" import { IxExits } from "./ix-exits"
import { IxClientBonds } from "./ix-client-bonds"
import { copyIxImportLink } from "./ix-import-link"
type Tab = "configuration" | "routes" | "changes" | "linux" | "exits" type Tab = "configuration" | "routes" | "linux"
const title = "Точки обмена трафиком" const title = "Точки обмена трафиком"
const describe = (error: unknown) => error instanceof Error ? error.message : "Не удалось выполнить операцию IX" const describe = (error: unknown) => error instanceof Error ? error.message : "Не удалось выполнить операцию IX"
@@ -73,10 +76,10 @@ export default function IxPage() {
const [activeNode, setActiveNode] = useState(ALL_SERVERS_ID) const [activeNode, setActiveNode] = useState(ALL_SERVERS_ID)
const [observations, setObservations] = useState<IxSiteObservation[] | null>(null) const [observations, setObservations] = useState<IxSiteObservation[] | null>(null)
const [linuxBindings, setLinuxBindings] = useState<IxLinuxBinding[]>([]) const [linuxBindings, setLinuxBindings] = useState<IxLinuxBinding[]>([])
const [linux, setLinux] = useState<(IxLinuxAccess & IxLinuxBinding) | null>(null) const [linux, setLinux] = useState<(IxLinuxAccess & IxLinuxBinding & { transportOnly: boolean }) | null>(null)
const [linuxPath, setLinuxPath] = useState<(IxLinuxPath & Pick<IxLinuxBinding, "name" | "interfaceName">) | null>(null) const [linuxPath, setLinuxPath] = useState<(IxLinuxPath & Pick<IxLinuxBinding, "name" | "interfaceName">) | null>(null)
const [revoke, setRevoke] = useState<IxLinuxBinding | null>(null) const [review, setReview] = useState("")
const [clientReview, setClientReview] = useState<IxLinuxBinding | null>(null) const [reviewError, setReviewError] = useState("")
const [plan, setPlan] = useState<IxWebPlan | null>(null) const [plan, setPlan] = useState<IxWebPlan | null>(null)
const [removalPlan, setRemovalPlan] = useState<IxWebPlan | null>(null) const [removalPlan, setRemovalPlan] = useState<IxWebPlan | null>(null)
const [tab, setTab] = useState<Tab>("configuration") const [tab, setTab] = useState<Tab>("configuration")
@@ -138,12 +141,13 @@ export default function IxPage() {
function invalidateReview() { function invalidateReview() {
setPlan(null) setPlan(null)
setClientReview(null) setReview("")
setReviewError("")
setRemovalPlan(null) setRemovalPlan(null)
setNotice("") setNotice("")
} }
function open(segment: IxSegment | null, defaultTab: Tab = "configuration") { function open(segment: IxSegment | null, defaultTab: Tab = segment ? "linux" : "configuration") {
focusAfterNavigation.current = !inDetail focusAfterNavigation.current = !inDetail
setSelected(segment) setSelected(segment)
setDraft(segment?.configuration ?? { name: "", sites: [{ ...newSite(), serverId: enabledNodes.length === 1 ? enabledNodes[0].id : 0 }] }) setDraft(segment?.configuration ?? { name: "", sites: [{ ...newSite(), serverId: enabledNodes.length === 1 ? enabledNodes[0].id : 0 }] })
@@ -182,20 +186,24 @@ export default function IxPage() {
} }
async function save() { async function save() {
if (selected && !dirty) {
await reviewSegment(selected, selected.configuration.name)
return
}
const { segment } = await requestJson<{ segment: IxSegment }>(backendUrl, "/api/ix/segments", post(change())) const { segment } = await requestJson<{ segment: IxSegment }>(backendUrl, "/api/ix/segments", post(change()))
open(segment) await reviewSegment(segment, segment.configuration.name)
setSegments(current => current.some(item => item.id === segment.id)
? current.map(item => item.id === segment.id ? segment : item)
: [segment, ...current])
setNotice("Черновик сохранён")
} }
async function prepare(resume = false) { async function prepare(segment: IxSegment, resume = false) {
if (!selected || !canPlan) return
setPlan(null) setPlan(null)
setPlan(await requestJson<IxWebPlan>(backendUrl, "/api/ix/segments/" + selected.id + "/plan", post({ setReviewError("")
revision: selected.revision, ...(resume && { resume }), try {
}))) setPlan(await requestJson<IxWebPlan>(backendUrl, "/api/ix/segments/" + segment.id + "/plan", post({
revision: segment.revision, ...(resume && { resume }),
})))
} catch (error) {
setReviewError(describe(error))
}
} }
async function prepareRemoval() { async function prepareRemoval() {
@@ -228,21 +236,23 @@ export default function IxPage() {
setLinuxPath(null) setLinuxPath(null)
setLinuxBindings([]) setLinuxBindings([])
setSegments(current => current.map(item => item.id === segment.id ? segment : item)) setSegments(current => current.map(item => item.id === segment.id ? segment : item))
setReview("")
setReviewError("")
setNotice("Конфигурация IX применена") setNotice("Конфигурация IX применена")
if (clientReview) { if (tab === "linux" || selected.appliedRevision === null) {
setTab("linux") setTab("linux")
setClientReview(null) await loadLinuxBindings(segment).catch(error => setError(describe(error)))
const clients = await requestJson<{ items: IxLinuxBinding[] }>(backendUrl, `/api/ix/segments/${segment.id}/linux`).catch(() => null) } else if (tab === "routes") {
if (clients) setLinuxBindings(clients.items) await observe(segment).catch(error => setError(describe(error)))
} }
} catch (error) { } catch (error) {
throw new Error(describe(error) + " Проверьте состояние сегмента перед повторным применением.") setReviewError(describe(error))
} }
} }
async function observe() { async function observe(segment = selected) {
if (!selected?.appliedRevision) return if (!segment?.appliedRevision) return
const { sites } = await requestJson<{ sites: IxSiteObservation[] }>(backendUrl, `/api/ix/segments/${selected.id}/status`) const { sites } = await requestJson<{ sites: IxSiteObservation[] }>(backendUrl, `/api/ix/segments/${segment.id}/status`)
setObservations(sites) setObservations(sites)
} }
@@ -253,15 +263,31 @@ export default function IxPage() {
setLinuxBindings(items) setLinuxBindings(items)
} }
async function exportLinux(binding: IxLinuxBinding) { async function exportLinux(binding: IxLinuxBinding, transportOnly = false) {
if (!selected) return if (!selected) return
setLinux(null) setLinux(null)
const query = new URLSearchParams({ serverId: String(binding.serverId), interfaceName: binding.interfaceName }) const query = new URLSearchParams({ serverId: String(binding.serverId), interfaceName: binding.interfaceName })
if (transportOnly) query.set("transportOnly", "true")
if (binding.managedWireguard && write) {
const access = await requestJson<IxLinuxAccess>(backendUrl, `/api/ix/segments/${selected.id}/linux/credential`,
post({ serverId: binding.serverId, interfaceName: binding.interfaceName, ...(transportOnly && { transportOnly }) }))
download(access.filename, access.template)
setNotice("Конфигурация WireGuard скачана")
return
}
const access = binding.policy && binding.kind === "gre-ipsec" && write const access = binding.policy && binding.kind === "gre-ipsec" && write
? await requestJson<IxLinuxAccess>(backendUrl, `/api/ix/segments/${selected.id}/linux/credential`, ? await requestJson<IxLinuxAccess>(backendUrl, `/api/ix/segments/${selected.id}/linux/credential`,
post({ serverId: binding.serverId, interfaceName: binding.interfaceName })) post({ serverId: binding.serverId, interfaceName: binding.interfaceName, ...(transportOnly && { transportOnly }) }))
: await requestJson<IxLinuxAccess>(backendUrl, `/api/ix/segments/${selected.id}/linux?${query}`) : await requestJson<IxLinuxAccess>(backendUrl, `/api/ix/segments/${selected.id}/linux?${query}`)
setLinux({ ...binding, ...access }) setLinux({ ...binding, ...access, transportOnly })
}
async function copyLinuxImport(binding: IxLinuxBinding) {
if (!selected) return
await copyIxImportLink(backendUrl, `/api/ix/segments/${selected.id}/linux/credential`, {
serverId: binding.serverId, interfaceName: binding.interfaceName,
})
setNotice("Ссылка скопирована. На VPS откройте ix-client → L. Ссылка действует до 5 минут.")
} }
async function inspectLinux(binding: IxLinuxBinding) { async function inspectLinux(binding: IxLinuxBinding) {
@@ -279,38 +305,52 @@ export default function IxPage() {
? await requestJson<{ segment: IxSegment; interfaceName: string }>(backendUrl, path + "/linux", post(input)) ? await requestJson<{ segment: IxSegment; interfaceName: string }>(backendUrl, path + "/linux", post(input))
: await requestJson<{ segment: IxSegment }>(backendUrl, path + "/linux/revoke", : await requestJson<{ segment: IxSegment }>(backendUrl, path + "/linux/revoke",
post({ revision: selected.revision, serverId: input.serverId, interfaceName: input.interfaceName })) post({ revision: selected.revision, serverId: input.serverId, interfaceName: input.interfaceName }))
setClientReview({ serverId: input.serverId, kind: input.kind, await reviewSegment(result.segment, "revision" in input ? "Доступ клиента " + input.name : "Отзыв доступа " + (input.name ?? input.interfaceName))
interfaceName: "interfaceName" in result ? String(result.interfaceName) : input.interfaceName ?? "" })
await reviewSegment(result.segment)
} }
async function stageTransit(input: IxTransitRequest) { async function stageTransit(input: IxTransitRequest) {
if (!selected || dirty || !write) return if (!selected || dirty || !write) return
const { segment } = await requestJson<{ segment: IxSegment }>(backendUrl, const { segment } = await requestJson<{ segment: IxSegment }>(backendUrl,
`/api/ix/segments/${selected.id}/transit`, post(input)) `/api/ix/segments/${selected.id}/transit`, post(input))
setClientReview(null) await reviewSegment(segment, "Выход через " + nodeLabel(peers, input.targetServerId))
await reviewSegment(segment)
} }
async function reviewSegment(segment: IxSegment) { async function reviewSegment(segment: IxSegment, title: string) {
setSelected(segment) setSelected(segment)
setDraft(segment.configuration) setDraft(segment.configuration)
setSegments(current => current.map(item => item.id === segment.id ? segment : item)) setAdvanced(null)
setSegments(current => current.some(item => item.id === segment.id)
? current.map(item => item.id === segment.id ? segment : item) : [segment, ...current])
setLinux(null) setLinux(null)
setLinuxPath(null)
setReview(title)
await prepare(segment)
}
function closeReview() {
if (busy) return
setReview("")
setPlan(null) setPlan(null)
setTab("changes") setReviewError("")
setNotice("Изменения сохранены в черновике") setNotice("Изменения сохранены в черновике. Нажмите «Сохранить», чтобы вернуться к подтверждению.")
setPlan(await requestJson<IxWebPlan>(backendUrl, `/api/ix/segments/${segment.id}/plan`, post({ revision: segment.revision })))
} }
function showTab(next: Tab) { function showTab(next: Tab) {
if (next === tab || busy) return if (next === tab || busy) return
if (advanced !== null) {
try { setDraft(change().configuration); setAdvanced(null) } catch (error) { setError(describe(error)); return }
}
setError("") setError("")
setTab(next) setTab(next)
if (next === "routes" && observations === null && selected?.appliedRevision) void perform(observe) if (next === "routes" && observations === null && selected?.appliedRevision) void perform(observe)
if (next === "linux" && selected?.appliedRevision) void perform(loadLinuxBindings) if (next === "linux" && selected?.appliedRevision) void perform(loadLinuxBindings)
} }
const settingsProps = draft && {
configuration: draft, nodes, peers, backendUrl, segmentId: selected?.id, readOnly: !live || !write || busy,
change: (value: IxConfiguration) => { setDraft(value); invalidateReview() },
}
const listEmpty = error ? "Не удалось загрузить список" : const listEmpty = error ? "Не удалось загрузить список" :
filter.trim() ? "Сегменты не найдены" : !live ? "Подключите backend" : "Нет сегментов IX" filter.trim() ? "Сегменты не найдены" : !live ? "Подключите backend" : "Нет сегментов IX"
const listDescription = error ? "Повторите загрузку списка." : filter.trim() ? "Попробуйте другое имя сегмента." : const listDescription = error ? "Повторите загрузку списка." : filter.trim() ? "Попробуйте другое имя сегмента." :
@@ -328,7 +368,7 @@ export default function IxPage() {
header={<PageHeader crumbs={inDetail ? [{ label: "Сегменты IX" }, { label: selected?.configuration.name ?? "Новый сегмент" }] : [{ label: title }]} header={<PageHeader crumbs={inDetail ? [{ label: "Сегменты IX" }, { label: selected?.configuration.name ?? "Новый сегмент" }] : [{ label: title }]}
actions={<ServerRailMobileButton />} />}> actions={<ServerRailMobileButton />} />}>
<div className="min-h-0 min-w-0 flex-1 overflow-y-auto"> <div className="min-h-0 min-w-0 flex-1 overflow-y-auto">
<div className="mx-auto flex w-full max-w-6xl min-w-0 flex-col gap-4 p-4 md:gap-5 md:p-6" aria-busy={busy}> <div className="flex w-full min-w-0 flex-col gap-4 p-4 md:gap-5 md:p-6" aria-busy={busy}>
{inDetail && <Button type="button" variant="ghost" size="sm" className="w-fit" disabled={busy} onClick={close}> {inDetail && <Button type="button" variant="ghost" size="sm" className="w-fit" disabled={busy} onClick={close}>
<ArrowLeftIcon aria-hidden />Все сегменты <ArrowLeftIcon aria-hidden />Все сегменты
</Button>} </Button>}
@@ -341,30 +381,33 @@ export default function IxPage() {
{inDetail && selected && <SegmentStatus segment={selected} />} {inDetail && selected && <SegmentStatus segment={selected} />}
</div> </div>
{inDetail ? (selected && <p className="mt-1 text-sm text-muted-foreground"> {inDetail ? (selected && <p className="mt-1 text-sm text-muted-foreground">
Ревизия {selected.revision}{selected.appliedRevision ? ` · Применена ревизия ${selected.appliedRevision}` : ""} Ревизия {selected.revision}{selected.appliedRevision && selected.appliedRevision !== selected.revision ? ` · Применена ревизия ${selected.appliedRevision}` : ""}
</p>) : <p className="mt-1 text-sm text-muted-foreground">Сегменты IX, площадки и маршрутизация</p>} </p>) : <p className="mt-1 text-sm text-muted-foreground">Сегменты IX, площадки и маршрутизация</p>}
</div> </div>
{inDetail && selected && live && write && <AlertDialog open={removalPlan !== null} {inDetail && live && write && <div className="flex flex-wrap items-center gap-2">
onOpenChange={open => { if (open) void perform(prepareRemoval); else setRemovalPlan(null) }}> {(dirty || canPlan) && <Button type="button" size="sm" disabled={busy} onClick={() => void perform(save)}>Сохранить</Button>}
<AlertDialogTrigger render={<Button type="button" variant="outline" size="sm" disabled={busy} />}> {selected && <AlertDialog open={removalPlan !== null}
<Trash2Icon aria-hidden />Удалить сегмент onOpenChange={open => { if (open) void perform(prepareRemoval); else setRemovalPlan(null) }}>
</AlertDialogTrigger> <AlertDialogTrigger render={<Button type="button" variant="outline" size="sm" disabled={busy} />}>
<AlertDialogContent> <Trash2Icon aria-hidden />Удалить сегмент
<AlertDialogHeader> </AlertDialogTrigger>
<AlertDialogTitle className="wrap-anywhere">Удалить {selected.configuration.name}?</AlertDialogTitle> <AlertDialogContent>
<AlertDialogDescription> <AlertDialogHeader>
{selected.appliedRevision <AlertDialogTitle className="wrap-anywhere">Удалить {selected.configuration.name}?</AlertDialogTitle>
? "Этот сегмент перестанет передавать трафик. Управляемая конфигурация будет удалена с узлов IX." <AlertDialogDescription>
: "Черновик будет удалён из списка сегментов. Конфигурация роутеров останется прежней."} {selected.appliedRevision
</AlertDialogDescription> ? "Этот сегмент перестанет передавать трафик. Управляемая конфигурация будет удалена с узлов IX."
</AlertDialogHeader> : "Черновик будет удалён из списка сегментов. Конфигурация роутеров останется прежней."}
{removalPlan && <RouterOsChanges changes={removalPlan.changes} nodes={nodes} />} </AlertDialogDescription>
<AlertDialogFooter> </AlertDialogHeader>
<AlertDialogCancel>Отмена</AlertDialogCancel> {removalPlan && <RouterOsChanges changes={removalPlan.changes} nodes={nodes} />}
<AlertDialogAction variant="destructive" disabled={busy} onClick={() => void perform(removeSegment)}>Удалить</AlertDialogAction> <AlertDialogFooter>
</AlertDialogFooter> <AlertDialogCancel>Отмена</AlertDialogCancel>
</AlertDialogContent> <AlertDialogAction variant="destructive" disabled={busy} onClick={() => void perform(removeSegment)}>Удалить</AlertDialogAction>
</AlertDialog>} </AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>}
</div>}
{!inDetail && <div className="flex flex-wrap items-center gap-2"> {!inDetail && <div className="flex flex-wrap items-center gap-2">
<Button type="button" size="icon-sm" variant="outline" disabled={busy || loading || !live} aria-label="Обновить список" <Button type="button" size="icon-sm" variant="outline" disabled={busy || loading || !live} aria-label="Обновить список"
onClick={() => void perform(() => load())}><RefreshCwIcon aria-hidden /></Button> onClick={() => void perform(() => load())}><RefreshCwIcon aria-hidden /></Button>
@@ -391,17 +434,16 @@ export default function IxPage() {
</Frame> : <Tabs value={tab} onValueChange={value => showTab(value as Tab)} className="min-w-0 gap-3"> </Frame> : <Tabs value={tab} onValueChange={value => showTab(value as Tab)} className="min-w-0 gap-3">
<div className="min-w-0 overflow-x-auto border-b pb-1"> <div className="min-w-0 overflow-x-auto border-b pb-1">
<TabsList variant="line" aria-label="Разделы сегмента"> <TabsList variant="line" aria-label="Разделы сегмента">
<TabsTrigger value="configuration">Конфигурация</TabsTrigger> {selected && <>
<TabsTrigger value="linux">Linux-клиенты</TabsTrigger> <TabsTrigger value="linux">Linux-клиенты</TabsTrigger>
<TabsTrigger value="exits">Выходы и резерв</TabsTrigger> <TabsTrigger value="routes">Маршрутизация</TabsTrigger>
<TabsTrigger value="routes">Маршруты и BGP</TabsTrigger> </>}
<TabsTrigger value="changes">План изменений</TabsTrigger> <TabsTrigger value="configuration">Настройки IX</TabsTrigger>
</TabsList> </TabsList>
</div> </div>
<TabsContent value="configuration" className="grid min-w-0 gap-3"> <TabsContent value="configuration" className="grid min-w-0 gap-3">
{advanced === null ? <ConfigurationFields configuration={draft} nodes={nodes} peers={peers} backendUrl={backendUrl} segmentId={selected?.id} readOnly={!live || !write || busy} {advanced === null ? settingsProps && <ConfigurationFields {...settingsProps} section="configuration" /> : <Frame spacing="sm">
change={value => { setDraft(value); invalidateReview() }} /> : <Frame spacing="sm">
<FrameHeader><FrameTitle>Конфигурация JSON</FrameTitle><FrameDescription>Интерфейсы, группы шлюзов, маршруты и BGP-политики.</FrameDescription></FrameHeader> <FrameHeader><FrameTitle>Конфигурация JSON</FrameTitle><FrameDescription>Интерфейсы, группы шлюзов, маршруты и BGP-политики.</FrameDescription></FrameHeader>
<FramePanel> <FramePanel>
<Textarea aria-label="Конфигурация JSON" spellCheck={false} readOnly={!live || !write || busy} rows={14} <Textarea aria-label="Конфигурация JSON" spellCheck={false} readOnly={!live || !write || busy} rows={14}
@@ -409,7 +451,6 @@ export default function IxPage() {
</FramePanel> </FramePanel>
</Frame>} </Frame>}
<div className="flex flex-wrap items-center gap-2"> <div className="flex flex-wrap items-center gap-2">
{write && <Button type="button" size="sm" disabled={busy || !live} onClick={() => void perform(save)}>Сохранить черновик</Button>}
{advanced === null ? <Button type="button" size="sm" variant="outline" disabled={busy} onClick={() => setAdvanced(json(draft))}> {advanced === null ? <Button type="button" size="sm" variant="outline" disabled={busy} onClick={() => setAdvanced(json(draft))}>
{write ? "Редактировать JSON" : "Показать JSON"} {write ? "Редактировать JSON" : "Показать JSON"}
</Button> : <Button type="button" size="sm" variant="outline" disabled={busy} onClick={() => void perform(async () => { </Button> : <Button type="button" size="sm" variant="outline" disabled={busy} onClick={() => void perform(async () => {
@@ -419,15 +460,11 @@ export default function IxPage() {
</div> </div>
</TabsContent> </TabsContent>
<TabsContent value="exits" className="grid min-w-0 gap-3">
{selected ? <IxExits segment={selected} nodes={peers} backendUrl={backendUrl} busy={busy} readOnly={!live || !write || dirty}
error={error} save={input => perform(() => stageTransit(input))} configure={() => showTab("configuration")} />
: <EmptyState title="Сохраните сегмент" description="После сохранения можно добавлять выходы." />}
</TabsContent>
<TabsContent value="routes" className="grid min-w-0 gap-3"> <TabsContent value="routes" className="grid min-w-0 gap-3">
{!selected?.appliedRevision ? <EmptyState title="Конфигурация ещё не применена" {selected && !dirty && live && write && <IxExits segment={selected} nodes={peers} backendUrl={backendUrl} busy={busy}
description="Маршруты и BGP-сессии появятся после применения плана." className="py-8" /> : <> error={error} save={input => perform(() => stageTransit(input))} />}
{settingsProps && <ConfigurationFields {...settingsProps} section="routes" />}
{!!selected?.appliedRevision && <>
<div className="flex flex-wrap gap-2"> <div className="flex flex-wrap gap-2">
<Button type="button" size="sm" variant="outline" disabled={busy} onClick={() => void perform(observe)}> <Button type="button" size="sm" variant="outline" disabled={busy} onClick={() => void perform(observe)}>
<RefreshCwIcon aria-hidden />Обновить состояние <RefreshCwIcon aria-hidden />Обновить состояние
@@ -439,23 +476,17 @@ export default function IxPage() {
</TabsContent> </TabsContent>
<TabsContent value="linux" className="grid min-w-0 gap-3"> <TabsContent value="linux" className="grid min-w-0 gap-3">
{selected ? <IxLinuxClients key={selected.id} segment={selected} nodes={peers} backendUrl={backendUrl} {selected ? <IxClientBonds key={selected.id + ":" + selected.appliedRevision} segmentId={selected.id} segments={segments}
backendUrl={backendUrl} nodes={peers} readOnly={!write || busy || dirty} live={live} download={download}>
{(bondAction, catalog, renderGroups, manualGroup) => <IxLinuxClients segment={selected} nodes={peers} backendUrl={backendUrl}
bondAction={bondAction} catalog={catalog} renderGroups={renderGroups} manualGroup={manualGroup}
applied={linuxBindings} busy={busy} error={error} readOnly={!live || !write || dirty} applied={linuxBindings} busy={busy} error={error} readOnly={!live || !write || dirty}
save={input => perform(() => stageClient(input))} revoke={setRevoke} save={input => perform(() => stageClient(input))} revoke={binding => void perform(() => stageClient(binding))}
refresh={() => void perform(loadLinuxBindings)} view={binding => void perform(() => exportLinux(binding))} refresh={() => void perform(loadLinuxBindings)} view={(binding, transportOnly) => void perform(() => exportLinux(binding, transportOnly))}
inspect={binding => void perform(() => inspectLinux(binding))} /> copyImport={binding => void perform(() => copyLinuxImport(binding))}
: <EmptyState title="Сохраните сегмент" description="После сохранения можно подключать клиентов." />} inspect={binding => void perform(() => inspectLinux(binding))} />}
<AlertDialog open={!!revoke} onOpenChange={value => { if (!value) setRevoke(null) }}> </IxClientBonds>
<AlertDialogContent> : <EmptyState title="Сохраните сегмент" description="После сохранения можно подключать клиентов." />}
<AlertDialogHeader>
<AlertDialogTitle>Отозвать доступ {revoke?.name}?</AlertDialogTitle>
<AlertDialogDescription>После применения клиент потеряет туннель и маршруты. Остальные подключения останутся в плане.</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter><AlertDialogCancel>Отмена</AlertDialogCancel>
<AlertDialogAction onClick={() => { if (revoke) void perform(() => stageClient(revoke)) }}>Проверить отзыв</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
{linuxPath && <Frame spacing="sm"> {linuxPath && <Frame spacing="sm">
<FrameHeader> <FrameHeader>
<FrameTitle>Маршруты клиента · {linuxPath.name ?? linuxPath.interfaceName}</FrameTitle> <FrameTitle>Маршруты клиента · {linuxPath.name ?? linuxPath.interfaceName}</FrameTitle>
@@ -474,18 +505,24 @@ export default function IxPage() {
<FrameDescription>Ревизия {linux.revision} · {nodeLabel(nodes, linux.serverId)}</FrameDescription> <FrameDescription>Ревизия {linux.revision} · {nodeLabel(nodes, linux.serverId)}</FrameDescription>
</FrameHeader> </FrameHeader>
<FramePanel className="grid min-w-0 gap-3"> <FramePanel className="grid min-w-0 gap-3">
<p className="text-sm text-muted-foreground">{linux.kind === "wireguard" <p className="text-sm text-muted-foreground">{linux.transportOnly
? "Подставьте приватный ключ Linux. После установки проверьте, куда направляются трафик и соединение управления." ? "Подготовьте туннель на VPS с указанным именем интерфейса. Маршруты назначит ix-client после включения группы."
: linux.policy && write ? "Подключите файл к strongSwan. Храните конфиг с PSK с правами доступа только для root." : linux.kind === "wireguard"
? linux.managedWireguard ? "Готовый файл с ключом доступен пользователю с правом управления сетью."
: "Подставьте приватный ключ Linux. После установки проверьте, куда направляются трафик и соединение управления."
: linux.policy && write ? "Скачайте оба файла в одну папку на VPS. Скрипт установит профиль strongSwan и поднимет GRE. SSH по внешнему IPv4 VPS останется прямым."
: "Для подключения нужен индивидуальный PSK, выданный оператором."}</p> : "Для подключения нужен индивидуальный PSK, выданный оператором."}</p>
{(!linux.policy || linux.kind === "wireguard") && <pre className="max-h-64 min-w-0 overflow-auto rounded-md border p-3 text-xs">{linux.template}</pre>} {(!linux.policy || linux.kind === "wireguard") && <pre className="max-h-64 min-w-0 overflow-auto rounded-md border p-3 text-xs">{linux.template}</pre>}
<Button type="button" variant="outline" size="sm" className="w-fit" onClick={() => download(linux.filename, linux.template)}> <Button type="button" variant="outline" size="sm" className="w-fit" onClick={() => download(linux.filename, linux.template)}>
Скачать {linux.filename} Скачать {linux.managedWireguard ? "шаблон" : linux.filename}
</Button> </Button>
{linux.setup && <> {linux.setup && <>
<pre className="min-w-0 overflow-auto rounded-md border p-3 text-xs">{linux.setup}</pre> {linux.policy && write ? <pre className="min-w-0 overflow-auto rounded-md border p-3 text-xs">{
"sudo apt install charon-systemd strongswan-swanctl\nsudo systemctl start strongswan\nsudo sh ./" +
linux.filename.replace(/\.conf$/, "-setup.sh")
}</pre> : <pre className="min-w-0 overflow-auto rounded-md border p-3 text-xs">{linux.setup}</pre>}
<Button type="button" variant="outline" size="sm" className="w-fit" <Button type="button" variant="outline" size="sm" className="w-fit"
onClick={() => download(linux.filename.replace(/\.conf$/, "-setup.sh"), "#!/bin/sh\nset -eu\n" + linux.setup + "\n")}>Скачать команды настройки</Button> onClick={() => download(linux.filename.replace(/\.conf$/, "-setup.sh"), "#!/bin/sh\nset -eu\n" + linux.setup + "\n")}>Скачать скрипт GRE</Button>
</>} </>}
{linux.bgp && <p className="wrap-anywhere text-sm text-muted-foreground"> {linux.bgp && <p className="wrap-anywhere text-sm text-muted-foreground">
BGP · ASN Linux {linux.bgp.localAs} · ASN IX {linux.bgp.remoteAs} · сосед {linux.bgp.neighbor} BGP · ASN Linux {linux.bgp.localAs} · ASN IX {linux.bgp.remoteAs} · сосед {linux.bgp.neighbor}
@@ -495,46 +532,28 @@ export default function IxPage() {
</Frame>} </Frame>}
</TabsContent> </TabsContent>
<TabsContent value="changes" className="grid min-w-0 gap-3">
<Frame spacing="sm">
<FrameHeader>
<FrameTitle>Изменения RouterOS</FrameTitle>
<FrameDescription>Предпросмотр сравнивает сохранённую ревизию с текущим состоянием узлов.</FrameDescription>
</FrameHeader>
<FramePanel className="grid min-w-0 gap-3">
{!write ? <p className="text-sm text-muted-foreground">Нужно право изменять сетевую конфигурацию.</p>
: dirty ? <p className="text-sm text-muted-foreground">Сохраните черновик на вкладке «Конфигурация».</p>
: selected?.appliedRevision === selected?.revision ? <p className="text-sm text-muted-foreground">Текущая ревизия применена.</p>
: <div className="flex flex-wrap gap-2">
<Button type="button" size="sm" variant="outline" disabled={!canPlan || busy}
onClick={() => void perform(prepare)}>Построить предпросмотр</Button>
{error && <Button type="button" size="sm" variant="outline" disabled={!canPlan || busy}
onClick={() => void perform(() => prepare(true))}>Сверить и продолжить</Button>}
</div>}
{plan && <div className="grid min-w-0 gap-3 border-t pt-3">
<p className="text-sm font-medium">Ревизия {plan.revision} · операций RouterOS: {plan.changes.length}</p>
{plan.changes.length === 0 && <p className="text-sm text-muted-foreground">Конфигурация RouterOS совпадает с черновиком. Применение обновит ревизию в MikrotikManager.</p>}
<RouterOsChanges changes={plan.changes} nodes={nodes} />
<AlertDialog>
<AlertDialogTrigger render={<Button type="button" size="sm" className="w-fit" disabled={busy || !canPlan} />}>
Применить план
</AlertDialogTrigger>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Применить конфигурацию IX?</AlertDialogTitle>
<AlertDialogDescription>Будет применена ревизия {plan.revision} сегмента {selected?.configuration.name}. Операций RouterOS: {plan.changes.length}.</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Отмена</AlertDialogCancel>
<AlertDialogAction onClick={() => void perform(apply)}>Применить</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</div>}
</FramePanel>
</Frame>
</TabsContent>
</Tabs>} </Tabs>}
<Dialog open={!!review} onOpenChange={open => { if (!open) closeReview() }}>
<DialogContent showCloseButton={!busy} className="max-h-[85dvh] overflow-y-auto sm:max-w-xl">
<DialogHeader>
<DialogTitle>Подтвердите сохранение</DialogTitle>
<DialogDescription>{review} · ревизия {selected?.revision}. После подтверждения изменения вступят в силу на узлах IX.</DialogDescription>
</DialogHeader>
{reviewError ? <Alert variant="destructive"><AlertTitle>Не удалось подтвердить состояние IX</AlertTitle>
<AlertDescription>{reviewError}</AlertDescription></Alert>
: plan ? <>
<p className="text-sm font-medium">{plan.changes.length ? "Операций RouterOS: " + plan.changes.length : "RouterOS уже настроена. Будет отмечена применённая ревизия."}</p>
<RouterOsChanges changes={plan.changes} nodes={peers} />
</> : <p role="status" className="text-sm text-muted-foreground">{busy ? "Проверяем конфигурацию на узлах…" : "Обновите сравнение перед сохранением."}</p>}
<DialogFooter>
<Button type="button" variant="outline" disabled={busy} onClick={closeReview}>Отмена</Button>
{reviewError && selected && <Button type="button" variant="outline" disabled={busy}
onClick={() => void perform(() => prepare(selected, true))}>Сверить и продолжить</Button>}
{plan ? <Button type="button" disabled={busy || !canPlan} onClick={() => void perform(apply)}>Подтвердить</Button>
: reviewError && selected && <Button type="button" disabled={busy} onClick={() => void perform(() => prepare(selected))}>Повторить проверку</Button>}
</DialogFooter>
</DialogContent>
</Dialog>
</div> </div>
</div> </div>
</ServerRailLayout> </ServerRailLayout>
File diff suppressed because it is too large. Load diff
+202 -168
View File
@@ -1,17 +1,22 @@
"use client" "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 { useSearchParams } from "next/navigation"
import { import {
ActivityIcon, ActivityIcon,
ChartColumnIcon,
DatabaseIcon, DatabaseIcon,
GaugeIcon, GaugeIcon,
GlobeIcon,
ServerIcon, ServerIcon,
UsersIcon, UsersIcon,
} from "lucide-react" } from "lucide-react"
import { Button } from "@/components/ui/button" import { Button } from "@/components/ui/button"
import { PageHeader } from "@/components/page-header" import { PageHeader } from "@/components/page-header"
import { PageTitle } from "@/components/page-title"
import { KpiStatGrid } from "@/components/reui-kit/kpi-stat-grid" 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 { DataPageCard } from "@/components/data-page-card"
import { DataPageToolbar } from "@/components/data-page-toolbar" import { DataPageToolbar } from "@/components/data-page-toolbar"
import { SegmentedControl } from "@/components/form-kit" import { SegmentedControl } from "@/components/form-kit"
@@ -35,6 +40,7 @@ import {
} from "@/lib/statistics-dims" } from "@/lib/statistics-dims"
import { statisticsContextError, STATISTICS_CONTEXT_KEYS } from "@/lib/statistics-context" import { statisticsContextError, STATISTICS_CONTEXT_KEYS } from "@/lib/statistics-context"
import { readStatisticsRange } from "@/lib/statistics-range" import { readStatisticsRange } from "@/lib/statistics-range"
import { demoStatistics, demoStatisticsPivot } from "@/lib/statistics-demo"
import { useDataSource } from "@/lib/data-source" import { useDataSource } from "@/lib/data-source"
import { fmtBps, formatBytes } from "@/lib/fmt-rate" import { fmtBps, formatBytes } from "@/lib/fmt-rate"
import { import {
@@ -102,8 +108,13 @@ function readDim(sp: URLSearchParams): StatisticsSliceKind {
return t && isStatisticsSliceKind(t) ? t : "users" return t && isStatisticsSliceKind(t) ? t : "users"
} }
function readView(sp: URLSearchParams): "explore" | "pivot" { type StatisticsView = "overview" | "explore" | "pivot"
return sp.get("view") === "pivot" ? "pivot" : "explore"
/** Вкладка макета 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" { function readPlanes(sp: URLSearchParams): "unique" | "all" {
@@ -241,7 +252,9 @@ function StatisticsPageInner() {
const pivotCol = useMemo(() => readPivotDim(searchParams, "pivotCol", "service"), [searchParams]) const pivotCol = useMemo(() => readPivotDim(searchParams, "pivotCol", "service"), [searchParams])
const [retry, setRetry] = useState(0) 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<{ const [result, setResult] = useState<{
key: string; data: StatisticsDto; pivot: StatisticsPivotDto; error: string | null key: string; data: StatisticsDto; pivot: StatisticsPivotDto; error: string | null
} | null>(null) } | null>(null)
@@ -249,7 +262,9 @@ function StatisticsPageInner() {
const loading = isLive && !rangeError && !paramsError && current === null const loading = isLive && !rangeError && !paramsError && current === null
const error = rangeError ?? paramsError ?? current?.error ?? null const error = rangeError ?? paramsError ?? current?.error ?? null
const dataReady = isLive && current !== null && !error 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( const updateParams = useCallback(
(patch: Record<string, string | undefined>) => { (patch: Record<string, string | undefined>) => {
@@ -295,7 +310,7 @@ function StatisticsPageInner() {
const dto = await getStatistics(backendUrl, query) const dto = await getStatistics(backendUrl, query)
if (cancelled) return if (cancelled) return
let matrix = EMPTY_PIVOT let matrix = EMPTY_PIVOT
if (view === "pivot" && pivotRow !== pivotCol) { if (pivotView && pivotRow !== pivotCol) {
matrix = await getStatisticsPivot(backendUrl, { matrix = await getStatisticsPivot(backendUrl, {
...query, ...query,
row: pivotRow, row: pivotRow,
@@ -313,11 +328,11 @@ function StatisticsPageInner() {
return () => { return () => {
cancelled = true 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 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) { function handleRowClick(kind: StatisticsSliceKind, row: StatisticsBreakdownRow) {
if (kind === "users" && row.id === STATISTICS_UNBOUND_USER_ID) return if (kind === "users" && row.id === STATISTICS_UNBOUND_USER_ID) return
@@ -348,175 +363,194 @@ function StatisticsPageInner() {
: sliced : sliced
? `${STATISTICS_DIMS.filter((d) => !hiddenKinds(slices).has(d.id)).length} разрезов` ? `${STATISTICS_DIMS.filter((d) => !hiddenKinds(slices).has(d.id)).length} разрезов`
: `${rowsForKind(viewData, dim).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 ( return (
<div className="flex h-full flex-col"> <div className="flex h-full flex-col">
<PageHeader <PageHeader crumbs={[{ label: "Главная", href: "/dashboard" }, { label: "Обзор" }, { label: "Статистика" }]} />
crumbs={[{ label: "Обзор", href: "/dashboard" }, { label: "Статистика" }]}
actions={rangeError ? <Button type="button" variant="outline" onClick={() => setRange(rangeForPreset("7d"))}>Выбрать последние 7 дней</Button> : <PeriodSelector range={range} onChange={setRange} />}
/>
<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"> <div className="flex flex-1 flex-col gap-6 overflow-y-auto px-4 pt-5 pb-10 md:px-7 md:pt-6">
{!isLive ? ( <PageTitle
<Alert> icon={<ChartColumnIcon />}
<AlertTitle>Живые данные выключены</AlertTitle> title="Статистика"
<AlertDescription> description="Куб NetFlow: измерения, срезы и период · уникальный объём без дублей"
Куб статистики строится из IPFIX. Переключитесь на живой источник, чтобы увидеть отчёт. actions={
</AlertDescription> <>
</Alert> {rangeError ? <Button type="button" variant="outline" onClick={() => setRange(rangeForPreset("7d"))}>Выбрать последние 7 дней</Button> : <PeriodSelector range={range} onChange={setRange} />}
) : null} <Button type="button" variant="outline" onClick={resetContext} disabled={!hasContext}>Сбросить параметры отчёта</Button>
</>
}
/>
{error ? ( <div className="flex flex-col gap-5">
<Alert variant="destructive" role="alert"> {!isLive ? (
<AlertTitle>{rangeError ? "Некорректный период" : paramsError ? "Параметры отчёта требуют внимания" : "Ошибка загрузки"}</AlertTitle> <Alert variant="warning">
<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> <AlertTitle>Живые данные выключены</AlertTitle>
</Alert> <AlertDescription>
) : null} Показан демо-куб. Статистика строится из IPFIX — переключитесь на живой источник, чтобы увидеть свой отчёт.
</AlertDescription>
</Alert>
) : null}
{!slices.serverId && dataReady && !emptyCube ? ( {error ? (
<Alert> <Alert variant={paramsError ? "warning" : "destructive"} role="alert">
<AlertTitle>Уникальный объём</AlertTitle> <AlertTitle>{rangeError ? "Некорректный период" : paramsError ? "Параметры отчёта требуют внимания" : "Ошибка загрузки"}</AlertTitle>
<AlertDescription> <AlertDescription>{error}{!rangeError && !paramsError && <Button type="button" variant="outline" size="sm" onClick={() => setRetry(n => n + 1)}>Повторить загрузку</Button>}</AlertDescription>
Объём — трафик клиентов на GRE/WG, без повторного учёта JH↔EN и WAN. </Alert>
</AlertDescription> ) : null}
</Alert>
) : null}
{(dataReady || loading) && <KpiStatGrid {(dataReady || loading || (demo && !paramsError)) && <KpiStatGrid
aria-label="Сводка трафика" aria-label="Сводка трафика"
isLoading={loading} isLoading={loading}
skeletonCount={5} skeletonCount={4}
items={[ items={[
{ {
id: "bytes", id: "bytes",
label: "Объём", label: planes === "all" ? "Объём" : "Уникальный объём",
value: formatBytes(kpis.bytes), value: formatBytes(kpis.bytes),
hint: "GRE/WG клиентов, без hops", hint: slices.serverId ? (kpis.ifaces ? `${kpis.ifaces} iface` : undefined) : planes === "all" ? "WAN и дубли в списке" : "без WAN и overlay",
icon: <DatabaseIcon />, icon: <DatabaseIcon />,
iconClassName: "text-muted-foreground", iconClassName: planes === "all" ? "text-muted-foreground" : "text-success",
}, },
{ {
id: "packets", id: "packets",
label: "Пакеты", label: "Пакеты",
value: kpis.packets.toLocaleString("ru-RU"), value: kpis.packets.toLocaleString("ru-RU"),
hint: kpis.topService ? `топ: ${kpis.topService}` : undefined, hint: kpis.topService ? `топ: ${kpis.topService}` : undefined,
icon: <ActivityIcon />, icon: <ActivityIcon />,
iconClassName: "text-muted-foreground", iconClassName: "text-muted-foreground",
}, },
{ {
id: "bps", id: "bps",
label: "Средний bitrate", label: "Средний bitrate",
value: fmtBps(kpis.avgBps), value: fmtBps(kpis.avgBps),
icon: <GaugeIcon />, icon: <GaugeIcon />,
iconClassName: "text-muted-foreground", iconClassName: "text-muted-foreground",
}, },
{ {
id: "users", id: "users",
label: "Пользователи", label: "Пользователи",
value: String(kpis.users), value: String(kpis.users),
icon: <UsersIcon />, hint: `Серверы: ${kpis.servers}`,
iconClassName: "text-muted-foreground", 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 && <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> <TabsContent value="overview" className="flex flex-col gap-5">
<DataPageToolbar {cubeState ?? (
leading={ <>
<div className="flex flex-wrap items-center gap-3"> <StatisticsVolumeChart series={viewData.series} grain={viewData.grain} scope={scope} actions={planesControl} />
<SegmentedControl <CapacityGrid
value={view} label="Доли объёма"
onChange={(next) => updateParams({ view: next === "pivot" ? "pivot" : "explore" })} items={[
options={[ bytesItem("users", "Пользователи", "GRE/WG клиентов, без hops", bytesOf(viewData.users), <UsersIcon />),
{ value: "explore", label: "Разрез" }, bytesItem("servers", "Серверы", planes === "all" ? "WAN и дубли в списке" : "без WAN и overlay", bytesOf(viewData.servers), <ServerIcon />),
{ value: "pivot", label: "Сводка" }, bytesItem("countries", "Страны", "Топ-10", bytesOf([...viewData.countries].sort((a, b) => b.bytes - a.bytes).slice(0, 10)), <GlobeIcon />),
]} ]}
/>
<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 })}
/> />
) : null} </>
{view === "pivot" ? ( )}
<> </TabsContent>
<PivotDimSelect
label="Строки" <TabsContent value="pivot">
value={pivotRow} <DataPageCard>
exclude={pivotCol} <DataPageToolbar
onChange={(next) => updateParams({ pivotRow: next })} leading={
/> <div className="flex flex-wrap items-center gap-3">
<PivotDimSelect {planesControl}
label="Колонки" <PivotDimSelect label="Строки" value={pivotRow} exclude={pivotCol} onChange={(next) => updateParams({ pivotRow: next })} />
value={pivotCol} <PivotDimSelect label="Колонки" value={pivotCol} exclude={pivotRow} onChange={(next) => updateParams({ pivotCol: next })} />
exclude={pivotRow} </div>
onChange={(next) => updateParams({ pivotCol: next })} }
/> filterControl={filters}
</> countLabel={dataReady ? countLabel : undefined}
) : null} />
</div> {sliceChips}
} {cubeState ?? <StatisticsPivotGrid data={pivot} onCellClick={handlePivotCell} isLoading={loading} />}
filterControl={<StatisticsFilters key={JSON.stringify(slices)} slices={slices} onApply={setSlices} />} </DataPageCard>
countLabel={dataReady ? countLabel : undefined} </TabsContent>
/>
<SliceChips <TabsContent value="explore">
chips={chips} <DataPageCard>
onRemove={(key) => { <DataPageToolbar
const next = { ...slices } leading={
delete next[key as keyof CubeSlices] <div className="flex flex-wrap items-center gap-3">
setSlices(next) {planesControl}
}} {!sliced ? <DimensionSelect label="Критерий" value={dim} onChange={(next) => updateParams({ dim: next, tab: undefined })} /> : null}
/> </div>
{isLive && !dataReady ? ( }
<div role="status" className="p-6 text-sm text-muted-foreground">{loading ? "Загрузка статистики…" : rangeError || paramsError ? "Исправьте параметры отчёта для загрузки статистики." : "Статистика недоступна. Повторите загрузку."}</div> filterControl={filters}
) : emptyCube ? ( countLabel={dataReady ? countLabel : undefined}
<EmptyState />
title="Нет данных куба" {sliceChips}
description="За выбранный период нет IPFIX-фактов. Куб заполняется с момента деплоя, без бэкфилла за год." {cubeState ?? (sliced ? (
/> <BreakdownDashboard
) : view === "pivot" ? ( data={viewData}
<StatisticsPivotGrid data={isLive ? pivot : EMPTY_PIVOT} onCellClick={handlePivotCell} isLoading={loading} /> hidden={hiddenKinds(slices)}
) : sliced ? ( selectedIdFor={(kind) => selectedIdForKind(kind, slices)}
<BreakdownDashboard onRowClick={handleRowClick}
data={viewData} isLoading={loading}
hidden={hiddenKinds(slices)} />
selectedIdFor={(kind) => selectedIdForKind(kind, slices)} ) : (
onRowClick={handleRowClick} <StatisticsBreakdownDataGrid
isLoading={loading} rows={rowsForKind(viewData, dim)}
/> kind={dim}
) : ( selectedId={selectedIdForKind(dim, slices)}
<StatisticsBreakdownDataGrid onRowClick={(row) => handleRowClick(dim, row)}
rows={rowsForKind(viewData, dim)} isLoading={loading}
kind={dim} />
selectedId={selectedIdForKind(dim, slices)} ))}
onRowClick={(row) => handleRowClick(dim, row)} </DataPageCard>
isLoading={loading} </TabsContent>
/> </Tabs>
)} </div>
</DataPageCard>
</div> </div>
</div> </div>
) )
+241 -180
View File
@@ -1,13 +1,15 @@
"use client" "use client"
import { useState, useMemo, useEffect, type ReactNode } from "react" import { useState, useMemo, useEffect, useRef, type ReactNode } from "react"
import { Alert, AlertTitle, AlertDescription } from "@/components/reui/alert" import { Alert, AlertTitle, AlertDescription } from "@/components/reui/alert"
import { peakOfCombinedTraffic, projectTrafficObservations, type TrafficObservationMeta } from "@/lib/traffic-observations" import { peakOfCombinedTraffic, projectTrafficObservations, sumObservedTraffic, type TrafficObservationMeta } from "@/lib/traffic-observations"
import { projectTrafficBindingStatus } from "@/lib/traffic-binding-status" import { projectTrafficBindingStatus } from "@/lib/traffic-binding-status"
import { TrafficObservationStatus } from "@/components/traffic/traffic-observation-status" import { TrafficObservationStatus } from "@/components/traffic/traffic-observation-status"
import { TrafficDataTime } from "@/components/traffic/traffic-data-time" import { TrafficDataTime } from "@/components/traffic/traffic-data-time"
import { PageHeader } from "@/components/page-header" 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 { KpiStatGrid } from "@/components/reui-kit/kpi-stat-grid"
import { TrafficMiniChart } from "@/components/reui-kit/traffic-mini-chart" import { TrafficMiniChart } from "@/components/reui-kit/traffic-mini-chart"
import { TrafficRxTxChart } from "@/components/reui-kit/traffic-rx-tx-chart" import { TrafficRxTxChart } from "@/components/reui-kit/traffic-rx-tx-chart"
@@ -16,7 +18,7 @@ import { Sparkline } from "@/components/sparkline"
import { StatusDot } from "@/components/status-dot" import { StatusDot } from "@/components/status-dot"
import { Flag } from "@/components/flag" import { Flag } from "@/components/flag"
import { import {
RefreshCwIcon, TrendingUpIcon, TrendingDownIcon, RefreshCwIcon, TrendingUpIcon, ChartPieIcon,
ArrowUpIcon, ArrowDownIcon, ActivityIcon, UsersIcon, CableIcon, ServerIcon, SearchIcon, GitBranchIcon, PlusIcon, ArrowUpIcon, ArrowDownIcon, ActivityIcon, UsersIcon, CableIcon, ServerIcon, SearchIcon, GitBranchIcon, PlusIcon,
} from "lucide-react" } from "lucide-react"
import { cn } from "@/lib/utils" import { cn } from "@/lib/utils"
@@ -341,17 +343,6 @@ type SortDir = "asc" | "desc"
// ─── shared sub-components ──────────────────────────────────────────────────── // ─── 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 ────────────────────────────────────────────────── // ─── left-panel entity cards ──────────────────────────────────────────────────
@@ -368,22 +359,22 @@ function ServerCard({ s, selected, onClick }: { s: ServerTraffic; selected: bool
<StatusDot status={s.status} /> <StatusDot status={s.status} />
<span className="text-xs font-medium truncate">{s.name}</span> <span className="text-xs font-medium truncate">{s.name}</span>
</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={s.country} />{s.site} <Flag code={s.country} />{s.site}
</span> </span>
</div> </div>
<TrafficMiniChart rx={s.rxSeries} tx={s.txSeries} /> <TrafficMiniChart rx={s.rxSeries} tx={s.txSeries} />
<div className="flex justify-between mt-2 gap-2"> <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" /> <ArrowDownIcon className="size-3 text-emerald-500" />
<span className="font-mono font-medium text-foreground">{fmtRate(s.rxNow)}</span> <span className="font-mono font-medium text-foreground">{fmtRate(s.rxNow)}</span>
</div> </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" /> <ArrowUpIcon className="size-3 text-blue-500" />
<span className="font-mono font-medium text-foreground">{fmtRate(s.txNow)}</span> <span className="font-mono font-medium text-foreground">{fmtRate(s.txNow)}</span>
</div> </div>
{s.boundIfaces.length > 0 && ( {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} <CableIcon className="size-3" />{s.boundIfaces.length}
</div> </div>
)} )}
@@ -407,10 +398,10 @@ function UserCard({ u, selected, onClick }: { u: UserTraffic; selected: boolean;
</div> </div>
<div className="min-w-0"> <div className="min-w-0">
<p className="text-xs font-medium truncate">{u.login}</p> <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> </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} <CableIcon className="size-3" />{u.interfaces.length}
</div> </div>
</div> </div>
@@ -418,18 +409,18 @@ function UserCard({ u, selected, onClick }: { u: UserTraffic; selected: boolean;
<> <>
<TrafficMiniChart rx={u.rxSeries} tx={u.txSeries} /> <TrafficMiniChart rx={u.rxSeries} tx={u.txSeries} />
<div className="flex justify-between mt-2 gap-2"> <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" /> <ArrowDownIcon className="size-3 text-emerald-500" />
<span className="font-mono font-medium text-foreground">{fmtRate(u.rxNow)}</span> <span className="font-mono font-medium text-foreground">{fmtRate(u.rxNow)}</span>
</div> </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" /> <ArrowUpIcon className="size-3 text-blue-500" />
<span className="font-mono font-medium text-foreground">{fmtRate(u.txNow)}</span> <span className="font-mono font-medium text-foreground">{fmtRate(u.txNow)}</span>
</div> </div>
</div> </div>
</> </>
) : ( ) : (
<p className="text-[10px] text-muted-foreground">Нет привязанных интерфейсов</p> <p className="text-xs text-muted-foreground">Нет привязанных интерфейсов</p>
)} )}
</button> </button>
) )
@@ -447,20 +438,20 @@ function IfaceCard({ c, selected, onClick }: { c: BoundIfaceTraffic; selected: b
<StatusDot status={c.status} /> <StatusDot status={c.status} />
<div className="min-w-0"> <div className="min-w-0">
<p className="text-xs font-mono font-medium truncate">{boundIfaceLabel(c)}</p> <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>
</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} <Flag code={c.serverCountry} />{c.serverSite}
</span> </span>
</div> </div>
<TrafficMiniChart rx={c.rxSeries} tx={c.txSeries} /> <TrafficMiniChart rx={c.rxSeries} tx={c.txSeries} />
<div className="flex justify-between mt-2 gap-2"> <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" /> <ArrowDownIcon className="size-3 text-emerald-500" />
<span className="font-mono font-medium text-foreground">{fmtRate(c.rxNow)}</span> <span className="font-mono font-medium text-foreground">{fmtRate(c.rxNow)}</span>
</div> </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" /> <ArrowUpIcon className="size-3 text-blue-500" />
<span className="font-mono font-medium text-foreground">{fmtRate(c.txNow)}</span> <span className="font-mono font-medium text-foreground">{fmtRate(c.txNow)}</span>
</div> </div>
@@ -487,12 +478,12 @@ function IfaceRow({ c, showServer = false }: { c: BoundIfaceTraffic; showServer?
<span className="text-xs font-mono font-semibold break-all">{boundIfaceLabel(c)}</span> <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> <Badge variant={TYPE_VARIANT[c.interfaceType]} size="sm">{IFACE_TYPE_LABEL[c.interfaceType]}</Badge>
{showServer && ( {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} <Flag code={c.serverCountry} />{c.serverSite}
</span> </span>
)} )}
</div> </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>
<div className="shrink-0 text-right leading-tight"> <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"> <div className="flex items-center gap-1 justify-end text-xs font-mono font-medium text-emerald-600 dark:text-emerald-400">
@@ -502,12 +493,12 @@ function IfaceRow({ c, showServer = false }: { c: BoundIfaceTraffic; showServer?
<ArrowUpIcon className="size-3" />{fmtRate(c.txNow)} <ArrowUpIcon className="size-3" />{fmtRate(c.txNow)}
</div> </div>
</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.rxTotal)}</p>
<p className="tabular-nums">{fmtGiB(c.txTotal)}</p> <p className="tabular-nums">{fmtGiB(c.txTotal)}</p>
</div> </div>
<span className={cn( <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" ? "bg-success/10 text-success" : "bg-muted text-muted-foreground",
)}> )}>
{c.status === "online" ? "Работает" : c.status === "unknown" ? "Нет данных" : "Неактивен"} {c.status === "online" ? "Работает" : c.status === "unknown" ? "Нет данных" : "Неактивен"}
@@ -516,6 +507,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 }) { function BoundIfacesList({ clients, showServer = false }: { clients: BoundIfaceTraffic[]; showServer?: boolean }) {
if (clients.length === 0) if (clients.length === 0)
return <p className="text-xs text-muted-foreground py-1">Нет привязанных интерфейсов</p> return <p className="text-xs text-muted-foreground py-1">Нет привязанных интерфейсов</p>
@@ -528,24 +574,46 @@ function BoundIfacesList({ clients, showServer = false }: { clients: BoundIfaceT
// ─── detail panel helpers ───────────────────────────────────────────────────── // ─── detail panel helpers ─────────────────────────────────────────────────────
function DetailHeader({ range, setRange, children }: { function DetailHeader({ range, setRange, children, status }: {
range: Range; setRange: (r: Range) => void; children: ReactNode range: Range; setRange: (r: Range) => void; children: ReactNode; status?: ReactNode
}) { }) {
return ( return (
<div className="flex flex-wrap items-start justify-between mb-3 gap-3"> <div className="mb-3 flex flex-wrap items-center gap-3">
<div className="flex items-center gap-2 flex-wrap min-w-0">{children}</div> <div className="flex min-w-0 flex-1 flex-wrap items-center gap-2">{children}</div>
<div className="flex flex-wrap gap-1"> {status}
<div className="bg-muted inline-flex h-9 items-center gap-0.5 rounded-lg p-[3px]">
{TRAFFIC_RANGE_KEYS.map((r) => ( {TRAFFIC_RANGE_KEYS.map((r) => (
<Button key={r} type="button" aria-pressed={range === r} size="sm" variant={r === range ? "default" : "ghost"} <button key={r} type="button" aria-pressed={range === r} onClick={() => setRange(r)}
className="h-7 px-2 text-xs" 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]} {TRAFFIC_RANGE_LABELS[r]}
</Button> </button>
))} ))}
</div> </div>
</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 }) { function OfflinePlaceholder({ text = "Нет данных — объект недоступен" }: { text?: string }) {
return ( return (
<div className="flex items-center justify-center h-[220px] text-muted-foreground/40"> <div className="flex items-center justify-center h-[220px] text-muted-foreground/40">
@@ -596,63 +664,24 @@ function ServerDetail({
const txNow = liveTx ?? sel.txNow const txNow = liveTx ?? sel.txNow
return ( return (
<> <>
<DetailHeader range={range} setRange={setRange}> <DetailHeader range={range} setRange={setRange} status={<ToneBadge tone={SERVER_STATUS[sel.status].tone} size="lg">{SERVER_STATUS[sel.status].label}</ToneBadge>}>
<StatusDot status={sel.status} /> <div className="min-w-0">
<h2 className="text-base font-semibold break-all">{sel.name}</h2> <h2 className="text-sm 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"> <p className="text-muted-foreground flex items-center gap-1 text-[0.78rem]"><Flag code={sel.country} />{sel.site}</p>
<Flag code={sel.country} />{sel.site} </div>
</span>
</DetailHeader> </DetailHeader>
<TrafficObservationStatus observations={sel.observations} unknown={sel.rxNow == null || sel.txNow == null} /> <TrafficObservationStatus observations={sel.observations} unknown={sel.rxNow == null || sel.txNow == null} />
<TrafficRxTxChart rx={sel.rxSeries} tx={sel.txSeries} range={range} /> <TrafficRxTxChart rx={sel.rxSeries} tx={sel.txSeries} range={range} />
<div className="mt-4 pt-4 border-t"> <KvStats
<KpiStatGrid label="Скорость выбранного сервера"
aria-label="Скорость выбранного сервера" items={[
items={[ { id: "rx-now", label: "RX сейчас", value: fmtRate(rxNow), hint: liveHint },
{ { id: "tx-now", label: "TX сейчас", value: fmtRate(txNow), hint: liveHint },
id: "rx-now", { id: "rx-peak", label: "Пик RX", value: fmtRate(sel.rxPeak) },
label: "RX", { id: "tx-peak", label: "Пик TX", value: fmtRate(sel.txPeak) },
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>
<TotalsRow rxTotal={sel.rxTotal} txTotal={sel.txTotal} rxSeries={sel.rxSeries} txSeries={sel.txSeries} /> <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 +695,7 @@ function UserDetail({ sel, range, setRange }: { sel: UserTraffic; range: Range;
<UsersIcon className="size-4 text-muted-foreground" /> <UsersIcon className="size-4 text-muted-foreground" />
</div> </div>
<div className="leading-tight"> <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> <p className="text-xs text-muted-foreground break-all">{sel.displayName} · {sel.role}</p>
</div> </div>
</DetailHeader> </DetailHeader>
@@ -675,12 +704,15 @@ function UserDetail({ sel, range, setRange }: { sel: UserTraffic; range: Range;
) : ( ) : (
<> <>
<TrafficRxTxChart rx={sel.rxSeries} tx={sel.txSeries} range={range} /> <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"> <KvStats
<StatChip icon={<ArrowDownIcon className="size-3.5 text-emerald-500" />} label="RX" value={fmtRate(sel.rxNow)} /> label="Скорость выбранного клиента"
<StatChip icon={<ArrowUpIcon className="size-3.5 text-blue-500" />} label="TX" value={fmtRate(sel.txNow)} /> items={[
<StatChip icon={<TrendingUpIcon className="size-3.5 text-amber-500" />} label="Пик RX" value={fmtRate(sel.rxPeak)} /> { id: "rx", label: "RX сейчас", value: fmtRate(sel.rxNow) },
<StatChip icon={<CableIcon className="size-3.5 text-purple-500" />} label="Интерфейсы" value={`${sel.interfaces.length}`} /> { id: "tx", label: "TX сейчас", value: fmtRate(sel.txNow) },
</div> { 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} /> <TotalsRow rxTotal={sel.rxTotal} txTotal={sel.txTotal} rxSeries={sel.rxSeries} txSeries={sel.txSeries} />
<div className="mt-4 pt-4 border-t"> <div className="mt-4 pt-4 border-t">
<h3 className="text-sm font-semibold mb-2 flex items-center gap-2"> <h3 className="text-sm font-semibold mb-2 flex items-center gap-2">
@@ -702,7 +734,7 @@ function IfaceDetail({ sel, range, setRange }: { sel: BoundIfaceTraffic; range:
<DetailHeader range={range} setRange={setRange}> <DetailHeader range={range} setRange={setRange}>
<StatusDot status={sel.status} /> <StatusDot status={sel.status} />
<div className="leading-tight min-w-0"> <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> <p className="text-xs text-muted-foreground truncate">{sel.comment || sel.userLogin}</p>
</div> </div>
<Badge variant={TYPE_VARIANT[sel.interfaceType]} size="sm">{IFACE_TYPE_LABEL[sel.interfaceType]}</Badge> <Badge variant={TYPE_VARIANT[sel.interfaceType]} size="sm">{IFACE_TYPE_LABEL[sel.interfaceType]}</Badge>
@@ -711,12 +743,15 @@ function IfaceDetail({ sel, range, setRange }: { sel: BoundIfaceTraffic; range:
</span> </span>
</DetailHeader> </DetailHeader>
<TrafficRxTxChart rx={sel.rxSeries} tx={sel.txSeries} range={range} /> <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"> <KvStats
<StatChip icon={<ArrowDownIcon className="size-3.5 text-emerald-500" />} label="RX" value={fmtRate(sel.rxNow)} /> label="Скорость выбранного интерфейса"
<StatChip icon={<ArrowUpIcon className="size-3.5 text-blue-500" />} label="TX" value={fmtRate(sel.txNow)} /> items={[
<StatChip icon={<TrendingUpIcon className="size-3.5 text-amber-500" />} label="Пик RX" value={fmtRate(sel.rxPeak)} /> { id: "rx", label: "RX сейчас", value: fmtRate(sel.rxNow) },
<StatChip icon={<TrendingUpIcon className="size-3.5 text-amber-500" />} label="Пик TX" value={fmtRate(sel.txPeak)} /> { id: "tx", label: "TX сейчас", value: fmtRate(sel.txNow) },
</div> { 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} /> <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 className="mt-4 pt-4 border-t grid grid-cols-2 sm:grid-cols-3 gap-4">
<div> <div>
@@ -797,6 +832,7 @@ export default function TrafficPage() {
const [sortField, setSortField] = useState<SortField>("rx") const [sortField, setSortField] = useState<SortField>("rx")
const [sortDir, setSortDir] = useState<SortDir>("desc") const [sortDir, setSortDir] = useState<SortDir>("desc")
const [selectedId, setSelectedId] = useState("srv1") const [selectedId, setSelectedId] = useState("srv1")
const initialServerApplied = useRef(false)
const [range, setRange] = useState<Range>("1h") const [range, setRange] = useState<Range>("1h")
const [search, setSearch] = useState("") const [search, setSearch] = useState("")
const [trafficRetry, setTrafficRetry] = useState(0) const [trafficRetry, setTrafficRetry] = useState(0)
@@ -903,9 +939,13 @@ export default function TrafficPage() {
setLiveUsers(mappedUsers) setLiveUsers(mappedUsers)
setLiveBoundIfaces(liveIfaces) setLiveBoundIfaces(liveIfaces)
setTrafficState({ key, status: "ready", receivedAt: Date.now(), peaks: srvRes.peaks }) setTrafficState({ key, status: "ready", receivedAt: Date.now(), peaks: srvRes.peaks })
const requestedServer = groupMode === "servers" && mapped.length && !initialServerApplied.current
? new URLSearchParams(window.location.search).get("server") : null
if (groupMode === "servers" && mapped.length) initialServerApplied.current = true
setSelectedId((prev) => { setSelectedId((prev) => {
if (groupMode === "users") return mappedUsers.some((x) => x.id === prev) ? prev : (mappedUsers[0]?.id ?? "") 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 ?? "") if (groupMode === "ifaces") return liveIfaces.some((x) => x.id === prev) ? prev : (liveIfaces[0]?.id ?? "")
if (requestedServer && mapped.some((x) => x.id === requestedServer)) return requestedServer
return mapped.some((x) => x.id === prev) ? prev : (mapped[0]?.id ?? "") return mapped.some((x) => x.id === prev) ? prev : (mapped[0]?.id ?? "")
}) })
} catch (e) { } catch (e) {
@@ -1143,11 +1183,17 @@ export default function TrafficPage() {
: effectiveMode === "ifaces" : effectiveMode === "ifaces"
? activeBoundIfaces ? activeBoundIfaces
: activeServerTraffic : activeServerTraffic
const totalRx = kpiSource.length && kpiSource.every(s => s.rxNow !== null) ? kpiSource.reduce((a, s) => a + (s.rxNow ?? 0), 0) : null const allowPartialKpi = effectiveMode === "ifaces"
const totalTx = kpiSource.length && kpiSource.every(s => s.txNow !== null) ? kpiSource.reduce((a, s) => a + (s.txNow ?? 0), 0) : null const totalRx = sumObservedTraffic(kpiSource.map(s => s.rxNow))
const totalTx = sumObservedTraffic(kpiSource.map(s => s.txNow))
const exactPeaks = effectiveMode === "servers" && trafficReady ? trafficState?.peaks : undefined const exactPeaks = effectiveMode === "servers" && trafficReady ? trafficState?.peaks : undefined
const peakRx = exactPeaks ? exactPeaks.rx : peakOfCombinedTraffic(kpiSource.map(s => s.rxSeries)) const peakRx = exactPeaks ? { value: exactPeaks.rx, observed: kpiSource.length } : peakOfCombinedTraffic(kpiSource.map(s => s.rxSeries), allowPartialKpi)
const peakTx = exactPeaks ? exactPeaks.tx : peakOfCombinedTraffic(kpiSource.map(s => s.txSeries)) const peakTx = exactPeaks ? { value: exactPeaks.tx, observed: kpiSource.length } : peakOfCombinedTraffic(kpiSource.map(s => s.txSeries), allowPartialKpi)
const coverageHint = (observed: number) => allowPartialKpi && observed > 0 && observed < kpiSource.length
? `${observed} из ${kpiSource.length} интерф.`
: undefined
const totalHint = effectiveMode === "servers" ? "Интерфейсы и туннели" : undefined
const peakHint = exactPeaks ? "По общим замерам" : "По интервалам графика"
const visibleSortFields = SORT_FIELDS.filter(s => !s.modesOnly || s.modesOnly.includes(effectiveMode)) const visibleSortFields = SORT_FIELDS.filter(s => !s.modesOnly || s.modesOnly.includes(effectiveMode))
const ingestLine = flowIngestLine(collectorStatus) const ingestLine = flowIngestLine(collectorStatus)
@@ -1192,77 +1238,88 @@ export default function TrafficPage() {
{ {
id: "rx", id: "rx",
label: "Сумма RX", label: "Сумма RX",
value: fmtRate(totalRx), value: fmtRate(allowPartialKpi || totalRx.observed === kpiSource.length ? totalRx.value : null),
hint: effectiveMode === "servers" ? "Интерфейсы и туннели" : undefined, hint: coverageHint(totalRx.observed) ?? totalHint,
icon: <ArrowDownIcon className="size-4" />, icon: <ArrowDownIcon className="size-4" />,
iconClassName: "text-success", iconClassName: "text-success",
}, },
{ {
id: "tx", id: "tx",
label: "Сумма TX", label: "Сумма TX",
value: fmtRate(totalTx), value: fmtRate(allowPartialKpi || totalTx.observed === kpiSource.length ? totalTx.value : null),
hint: effectiveMode === "servers" ? "Интерфейсы и туннели" : undefined, hint: coverageHint(totalTx.observed) ?? totalHint,
icon: <ArrowUpIcon className="size-4" />, icon: <ArrowUpIcon className="size-4" />,
iconClassName: "text-info", iconClassName: "text-info",
}, },
{ {
id: "peak-rx", id: "peak-rx",
label: "Пик суммы RX", label: "Пик суммы RX",
value: fmtRate(peakRx), value: fmtRate(peakRx.value),
hint: exactPeaks ? "По общим замерам" : "По интервалам графика", hint: coverageHint(peakRx.observed) ?? peakHint,
icon: <TrendingUpIcon className="size-4" />, icon: <TrendingUpIcon className="size-4" />,
iconClassName: "text-warning", iconClassName: "text-warning",
}, },
{ {
id: "peak-tx", id: "peak-tx",
label: "Пик суммы TX", label: "Пик суммы TX",
value: fmtRate(peakTx), value: fmtRate(peakTx.value),
hint: exactPeaks ? "По общим замерам" : "По интервалам графика", hint: coverageHint(peakTx.observed) ?? peakHint,
icon: <TrendingUpIcon className="size-4" />, icon: <TrendingUpIcon className="size-4" />,
iconClassName: "text-warning", iconClassName: "text-warning",
}, },
] ]
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 : trafficLoading)
const listTitle = effectiveMode === "servers" ? "Серверы" : effectiveMode === "users" ? "Клиенты" : "Интерфейсы"
const listShown = effectiveMode === "servers" ? sortedServers.length : effectiveMode === "users" ? sortedUsers.length : sortedIfaces.length
return ( return (
<div className="flex flex-col h-full"> <div className="flex flex-col h-full">
<PageHeader <PageHeader crumbs={[{ label: "Главная", href: "/dashboard" }, { label: "Обзор" }, { label: "Трафик" }]} />
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>
</>
}
/>
{/* ── mode tab bar ── */} <div className="flex-1 min-w-0 overflow-y-auto px-4 pt-5 pb-10 md:px-7 md:pt-6">
<div className="border-b bg-background shrink-0"> <div className="flex flex-col gap-6">
<div role="group" aria-label="Разделы трафика" className="flex items-center overflow-x-auto px-3 sm:px-6"> <PageTitle
{GROUP_MODES.map(({ mode, icon, label }) => ( icon={<ActivityIcon />}
<button type="button" aria-pressed={effectiveMode === mode} key={mode} onClick={() => handleModeChange(mode)} title="Трафик"
className={cn( description="Счётчики интерфейсов и потоки IPFIX по серверам, клиентам и интерфейсам"
"flex items-center gap-2 px-4 py-3 text-sm font-medium border-b-2 transition-colors -mb-px", actions={
effectiveMode === mode <>
? "border-primary text-foreground" <Button type="button" variant="outline" onClick={() => { handleModeChange("flows"); setRange("30d") }}>Месячный отчёт</Button>
: "border-transparent text-muted-foreground hover:text-foreground hover:border-border", <Button
)}> type="button"
{icon}{label} onClick={() => {
</button> if (effectiveMode === "flows") setFlowRetry(value => value + 1)
))} else setTrafficRetry(value => value + 1)
</div> }}
</div> disabled={refreshBusy}
>
<div className="flex-1 min-w-0 overflow-y-auto p-3 sm:p-6"> <RefreshCwIcon className={cn("size-4", refreshBusy && "animate-spin")} />Обновить
</Button>
</>
}
/>
<div className="flex flex-col gap-5"> <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>
{!(effectiveMode === "flows" && range === "30d") && (!isLive || !(effectiveMode === "flows" ? liveError : trafficError)) && <KpiStatGrid {!(effectiveMode === "flows" && range === "30d") && (!isLive || !(effectiveMode === "flows" ? liveError : trafficError)) && <KpiStatGrid
isLoading={isLive && (effectiveMode === "flows" ? liveBusy : trafficLoading)} isLoading={isLive && (effectiveMode === "flows" ? liveBusy : trafficLoading)}
aria-label="Сводка трафика" aria-label="Сводка трафика"
@@ -1291,15 +1348,15 @@ export default function TrafficPage() {
{flowError} {flowError}
</div> </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 xl:grid-cols-[300px_minmax(0,1fr)] gap-4 items-start">
<div className="flex flex-col gap-3"> <SectionFrame title={flowScope === "users" ? "Клиенты" : "Экспортёры"} description="Потоки IPFIX · сортировка и поиск" panelClassName="flex flex-col gap-3 p-2.5">
<div role="group" aria-label="Источник потоков" className="flex gap-1"> <div role="group" aria-label="Источник потоков" className="flex gap-1">
<button <button
type="button" type="button"
aria-pressed={flowScope === "servers"} aria-pressed={flowScope === "servers"}
onClick={() => { setFlowScope("servers"); setFlowIface("__all__") }} onClick={() => { setFlowScope("servers"); setFlowIface("__all__") }}
className={cn( 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" flowScope === "servers"
? "border-primary bg-primary/10 text-primary font-medium" ? "border-primary bg-primary/10 text-primary font-medium"
: "border-border text-muted-foreground hover:text-foreground", : "border-border text-muted-foreground hover:text-foreground",
@@ -1312,7 +1369,7 @@ export default function TrafficPage() {
aria-pressed={flowScope === "users"} aria-pressed={flowScope === "users"}
onClick={() => { setFlowScope("users"); setFlowIface("__all__"); if (range === "30d") setRange("1h") }} onClick={() => { setFlowScope("users"); setFlowIface("__all__"); if (range === "30d") setRange("1h") }}
className={cn( 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" flowScope === "users"
? "border-primary bg-primary/10 text-primary font-medium" ? "border-primary bg-primary/10 text-primary font-medium"
: "border-border text-muted-foreground hover:text-foreground", : "border-border text-muted-foreground hover:text-foreground",
@@ -1332,14 +1389,14 @@ export default function TrafficPage() {
/> />
</div> </div>
<div className={cn("flex gap-1 flex-wrap", range === "30d" && "hidden")}> <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 }) => ( {visibleSortFields.map(({ field, label }) => (
<button <button
key={field} key={field}
type="button" type="button"
onClick={() => toggleSort(field)} onClick={() => toggleSort(field)}
className={cn( 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 sortField === field
? "border-primary bg-primary/10 text-primary font-medium" ? "border-primary bg-primary/10 text-primary font-medium"
: "border-border text-muted-foreground hover:text-foreground", : "border-border text-muted-foreground hover:text-foreground",
@@ -1365,8 +1422,8 @@ export default function TrafficPage() {
</p> </p>
) : null} ) : null}
</div> </div>
</div> </SectionFrame>
<Frame dense className="w-full min-w-0 flex flex-col"> <SectionFrame bare className="w-full min-w-0">
<FramePanel className="flex-1 min-w-0 p-3 sm:p-5"> <FramePanel className="flex-1 min-w-0 p-3 sm:p-5">
{analyticsLoading && <p role="status">Загрузка аналитики…</p>} {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>} {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>}
@@ -1393,7 +1450,7 @@ export default function TrafficPage() {
emptyHint={analyticsLoading ? "Загрузка аналитики…" : currentAnalytics?.error ? "Не удалось получить данные выбранного среза" : flowEmptyHint(collectorStatus)} emptyHint={analyticsLoading ? "Загрузка аналитики…" : currentAnalytics?.error ? "Не удалось получить данные выбранного среза" : flowEmptyHint(collectorStatus)}
/> />
</FramePanel> </FramePanel>
</Frame> </SectionFrame>
</div> </div>
<FlowOverlaySheet <FlowOverlaySheet
open={overlayOpen} open={overlayOpen}
@@ -1404,9 +1461,10 @@ export default function TrafficPage() {
/> />
</div> </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 xl:grid-cols-[300px_minmax(0,1fr)] gap-4 items-start">
{/* ── left panel ── */} {/* ── 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 */} {/* search */}
<div className="relative"> <div className="relative">
@@ -1416,20 +1474,17 @@ export default function TrafficPage() {
value={search} value={search}
onChange={e => setSearch(e.target.value)} onChange={e => setSearch(e.target.value)}
aria-label="Поиск трафика" placeholder="Поиск…" 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> </div>
{/* sort controls */} {/* sort controls */}
<div className="flex gap-1 flex-wrap"> <div role="group" aria-label="Сортировка" className="bg-muted inline-flex h-9 w-fit items-center gap-0.5 rounded-lg p-[3px]">
<span className="text-[10px] text-muted-foreground self-center mr-0.5">Сортировка:</span>
{visibleSortFields.map(({ field, label }) => ( {visibleSortFields.map(({ field, label }) => (
<button type="button" aria-pressed={sortField === field} key={field} onClick={() => toggleSort(field)} <button type="button" aria-pressed={sortField === field} key={field} onClick={() => toggleSort(field)}
className={cn( className={cn(
"text-[10px] px-2 py-0.5 rounded border transition-colors", "text-muted-foreground hover:text-foreground h-[30px] rounded-md px-2.5 text-[13px] font-medium transition-colors",
sortField === field sortField === field && "bg-background text-foreground shadow-sm",
? "border-primary bg-primary/10 text-primary font-medium"
: "border-border text-muted-foreground hover:text-foreground",
)}> )}>
{label}{sortField === field ? (sortDir === "desc" ? " ↓" : " ↑") : ""} {label}{sortField === field ? (sortDir === "desc" ? " ↓" : " ↑") : ""}
</button> </button>
@@ -1455,20 +1510,23 @@ export default function TrafficPage() {
<IfaceCard key={c.id} c={c} selected={c.id === selectedId} onClick={() => setSelectedId(c.id)} /> <IfaceCard key={c.id} c={c} selected={c.id === selectedId} onClick={() => setSelectedId(c.id)} />
))} ))}
</div> </div>
</SectionFrame>
{effectiveMode === "servers" ? <RxShareFrame servers={activeServerTraffic} /> : null}
</div> </div>
{/* ── detail panel ── */} {/* ── 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"> <FramePanel className="flex-1 min-w-0 p-3 sm:p-5">
{isLive && effectiveMode === "servers" && ( {isLive && effectiveMode === "servers" && (
<div className="mb-3 pb-3 border-b"> <div className="mb-3 pb-3 border-b">
<div className="flex items-center gap-2 flex-wrap"> <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 <button
type="button" aria-pressed={hideDisabledIfaces} type="button" aria-pressed={hideDisabledIfaces}
onClick={() => setHideDisabledIfaces((v) => !v)} onClick={() => setHideDisabledIfaces((v) => !v)}
className={cn( 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 hideDisabledIfaces
? "bg-muted text-foreground border-border" ? "bg-muted text-foreground border-border"
: "text-muted-foreground border-border hover:text-foreground hover:border-foreground/40", : "text-muted-foreground border-border hover:text-foreground hover:border-foreground/40",
@@ -1480,7 +1538,7 @@ export default function TrafficPage() {
type="button" aria-pressed={selectedIface === "__all__"} type="button" aria-pressed={selectedIface === "__all__"}
onClick={() => setSelectedIface("__all__")} onClick={() => setSelectedIface("__all__")}
className={cn( 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__" selectedIface === "__all__"
? "bg-foreground text-background border-foreground" ? "bg-foreground text-background border-foreground"
: "border-border text-muted-foreground hover:text-foreground hover:border-foreground/40", : "border-border text-muted-foreground hover:text-foreground hover:border-foreground/40",
@@ -1496,7 +1554,7 @@ export default function TrafficPage() {
type="button" aria-pressed={active} type="button" aria-pressed={active}
onClick={() => setSelectedIface(iface.name)} onClick={() => setSelectedIface(iface.name)}
className={cn( 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 active
? "bg-foreground text-background border-foreground" ? "bg-foreground text-background border-foreground"
: "border-border text-muted-foreground hover:text-foreground hover:border-foreground/40", : "border-border text-muted-foreground hover:text-foreground hover:border-foreground/40",
@@ -1508,7 +1566,7 @@ export default function TrafficPage() {
</button> </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>
</div> </div>
)} )}
@@ -1544,11 +1602,14 @@ export default function TrafficPage() {
{effectiveMode === "users" && selUser && <UserDetail sel={selUser} range={range} setRange={setRange} />} {effectiveMode === "users" && selUser && <UserDetail sel={selUser} range={range} setRange={setRange} />}
{effectiveMode === "ifaces" && selIface && <IfaceDetail sel={selIface} range={range} setRange={setRange} />} {effectiveMode === "ifaces" && selIface && <IfaceDetail sel={selIface} range={range} setRange={setRange} />}
</FramePanel> </FramePanel>
</Frame> </SectionFrame>
{effectiveMode === "servers" && detailServer && detailServer.boundIfaces.length > 0 ? <ServerIfacesFrame server={detailServer} /> : null}
</div>
</div> </div>
)} )}
</div> </div>
</div>
</div> </div>
</div> </div>
) )
+38 -3
View File
@@ -464,6 +464,20 @@
], ],
"reason": "Общий listRevisions с REST: только метаданные, максимум 50 записей; серверная область и права проверяются до SQL, payload ревизии не выдаётся." "reason": "Общий listRevisions с REST: только метаданные, максимум 50 записей; серверная область и права проверяются до SQL, payload ревизии не выдаётся."
}, },
{
"method": "POST",
"path": "/api/ix/import",
"status": "excluded",
"operations": [],
"reason": "Одноразовый импорт Linux-клиента: выдаёт конфигурацию только по коду, созданному оператором IX."
},
{
"method": "GET",
"path": "/api/ix/linux-bonds",
"status": "excluded",
"operations": [],
"reason": "Каталог для формы выбора туннелей одного VPS в WebUI. Оператор сопоставляет подключения разных площадок со своими локальными интерфейсами."
},
{ {
"method": "GET", "method": "GET",
"path": "/api/ix/nodes", "path": "/api/ix/nodes",
@@ -1120,7 +1134,7 @@
"operations": [ "operations": [
"traffic.live.read" "traffic.live.read"
], ],
"reason": "Общий readTrafficLiveSample; MCP возвращает ограниченную серию до трёх срезов вместо бесконечного SSE. Полнота суммы, направление RX/TX, отзыв доступа и смена источника проверяются перед каждым новым native-запросом." "reason": "Общий readTrafficLiveSample для разового чтения интерфейса, SSE и ограниченной MCP-серии. Источник проверяется перед каждым новым native-запросом."
}, },
{ {
"method": "GET", "method": "GET",
@@ -1618,6 +1632,27 @@
"operations": [], "operations": [],
"reason": "Локальный предпросмотр объектов из компилятора. План MCP дополнительно фиксирует состояние площадок и требует подтверждения." "reason": "Локальный предпросмотр объектов из компилятора. План MCP дополнительно фиксирует состояние площадок и требует подтверждения."
}, },
{
"method": "POST",
"path": "/api/ix/segments/:id/linux-bonds",
"status": "excluded",
"operations": [],
"reason": "WebUI сохраняет выбранные оператором интерфейсы и порядок путей для последующего импорта и подтверждения в локальном ix-client."
},
{
"method": "DELETE",
"path": "/api/ix/segments/:id/linux-bonds/:bondId",
"status": "excluded",
"operations": [],
"reason": "Оператор удаляет сохранённое описание группы из WebUI. Снятие политики на самом VPS подтверждается отдельно в ix-client."
},
{
"method": "POST",
"path": "/api/ix/segments/:id/linux-bonds/:bondId/export",
"status": "excluded",
"operations": [],
"reason": "Оператор скачивает JSON группы из WebUI и локально сопоставляет его с интерфейсами VPS в ix-client."
},
{ {
"method": "POST", "method": "POST",
"path": "/api/ix/segments/:id/plan", "path": "/api/ix/segments/:id/plan",
@@ -1637,14 +1672,14 @@
"path": "/api/ix/segments/:id/linux", "path": "/api/ix/segments/:id/linux",
"status": "excluded", "status": "excluded",
"operations": [], "operations": [],
"reason": "Мастер WebUI подготавливает черновик подключения Linux. Записи на RouterOS идут после отдельного подтверждения плана." "reason": "WebUI сохраняет одной ревизией клиента Linux и выбранный транзит. Записи на RouterOS идут после подтверждения изменений."
}, },
{ {
"method": "POST", "method": "POST",
"path": "/api/ix/segments/:id/linux/credential", "path": "/api/ix/segments/:id/linux/credential",
"status": "excluded", "status": "excluded",
"operations": [], "operations": [],
"reason": "Действующий PSK выдаётся оператору WebUI с правом изменения сети и записью в журнале. Инструменты MCP не получают секрет." "reason": "WebUI выдаёт действующий PSK или ключ WireGuard оператору с правом изменения сети и записью в журнале. Для WireGuard MCP возвращает защищённую ссылку через network.wireguard.export."
}, },
{ {
"method": "POST", "method": "POST",
+2 -1
View File
@@ -60,6 +60,7 @@
"test:ipsec": "tsx src/services/ipsec-config.test.ts && tsx src/services/ipsec-state.test.ts && tsx src/routes/ipsec-history.test.ts && tsx src/services/ipsec-restore.test.ts && tsx src/services/ipsec-operation.test.ts && tsx src/routes/ipsec-mutation.test.ts && tsx src/routes/ipsec-nat.test.ts && tsx src/routes/ipsec-group.test.ts && tsx src/services/ipsec-peer-delete.test.ts && tsx src/modules/mcp/ipsec-peer-delete-actions.test.ts && tsx src/services/ipsec-user-delete.test.ts && tsx src/modules/mcp/ipsec-user-delete-actions.test.ts && tsx src/services/ipsec-certificate-delete.test.ts && tsx src/modules/mcp/ipsec-certificate-delete-actions.test.ts && tsx src/services/ipsec-peer-update.test.ts && tsx src/modules/mcp/ipsec-peer-update-actions.test.ts && tsx src/services/ipsec-user-update-model.test.ts && tsx src/modules/mcp/ipsec-user-update-actions.test.ts && tsx src/services/ipsec-server-delete-model.test.ts && tsx src/modules/mcp/ipsec-server-delete-actions.test.ts && tsx src/services/ipsec-proof-telemetry.test.ts && tsx src/services/ipsec-user-create-model.test.ts", "test:ipsec": "tsx src/services/ipsec-config.test.ts && tsx src/services/ipsec-state.test.ts && tsx src/routes/ipsec-history.test.ts && tsx src/services/ipsec-restore.test.ts && tsx src/services/ipsec-operation.test.ts && tsx src/routes/ipsec-mutation.test.ts && tsx src/routes/ipsec-nat.test.ts && tsx src/routes/ipsec-group.test.ts && tsx src/services/ipsec-peer-delete.test.ts && tsx src/modules/mcp/ipsec-peer-delete-actions.test.ts && tsx src/services/ipsec-user-delete.test.ts && tsx src/modules/mcp/ipsec-user-delete-actions.test.ts && tsx src/services/ipsec-certificate-delete.test.ts && tsx src/modules/mcp/ipsec-certificate-delete-actions.test.ts && tsx src/services/ipsec-peer-update.test.ts && tsx src/modules/mcp/ipsec-peer-update-actions.test.ts && tsx src/services/ipsec-user-update-model.test.ts && tsx src/modules/mcp/ipsec-user-update-actions.test.ts && tsx src/services/ipsec-server-delete-model.test.ts && tsx src/modules/mcp/ipsec-server-delete-actions.test.ts && tsx src/services/ipsec-proof-telemetry.test.ts && tsx src/services/ipsec-user-create-model.test.ts",
"test:live-maps": "tsx src/services/gre-revision-restore.test.ts && tsx src/services/gre-native-mutation.test.ts && tsx src/services/gre-mutation.test.ts && tsx src/services/filter-rules-observed.test.ts && tsx src/services/firewall-revision-restore.test.ts && tsx src/services/firewall-address-write.test.ts && tsx src/services/firewall-rule-write.test.ts && tsx src/services/gre-observed-read.test.ts && tsx src/services/network-observed-read.test.ts && tsx src/services/firewall-rule-move.test.ts && tsx src/services/ospf-state-read.test.ts && tsx src/modules/mcp/readiness-http.test.ts && tsx src/services/probe-interface-model.test.ts && tsx src/services/wan-runtime-model.test.ts && tsx src/services/gre-keepalive.test.ts && tsx src/services/gre-read.test.ts && tsx src/services/ospf-route-parse.test.ts && tsx src/services/vxlan-live.test.ts && tsx src/routes/vxlan.test.ts && tsx src/services/containers-live.test.ts && tsx src/services/firewall-poll.test.ts && tsx src/services/gre-catalog-poll.test.ts && tsx src/routes/filters-gre-catalog.test.ts && tsx src/routes/bgp-catalog.test.ts && tsx src/services/bgp-catalog-parse.test.ts && tsx src/routes/ospf-catalog.test.ts && tsx src/services/ospf-observed-values.test.ts && tsx src/routes/ospf-legacy.test.ts", "test:live-maps": "tsx src/services/gre-revision-restore.test.ts && tsx src/services/gre-native-mutation.test.ts && tsx src/services/gre-mutation.test.ts && tsx src/services/filter-rules-observed.test.ts && tsx src/services/firewall-revision-restore.test.ts && tsx src/services/firewall-address-write.test.ts && tsx src/services/firewall-rule-write.test.ts && tsx src/services/gre-observed-read.test.ts && tsx src/services/network-observed-read.test.ts && tsx src/services/firewall-rule-move.test.ts && tsx src/services/ospf-state-read.test.ts && tsx src/modules/mcp/readiness-http.test.ts && tsx src/services/probe-interface-model.test.ts && tsx src/services/wan-runtime-model.test.ts && tsx src/services/gre-keepalive.test.ts && tsx src/services/gre-read.test.ts && tsx src/services/ospf-route-parse.test.ts && tsx src/services/vxlan-live.test.ts && tsx src/routes/vxlan.test.ts && tsx src/services/containers-live.test.ts && tsx src/services/firewall-poll.test.ts && tsx src/services/gre-catalog-poll.test.ts && tsx src/routes/filters-gre-catalog.test.ts && tsx src/routes/bgp-catalog.test.ts && tsx src/services/bgp-catalog-parse.test.ts && tsx src/routes/ospf-catalog.test.ts && tsx src/services/ospf-observed-values.test.ts && tsx src/routes/ospf-legacy.test.ts",
"test": "node scripts/test.mjs", "test": "node scripts/test.mjs",
"test:ix": "tsx --test src/services/internet-exchange-plan.test.ts src/services/internet-exchange-execution.test.ts src/services/internet-exchange-bonds.test.ts src/services/ix-bond-transport.test.ts src/services/ix-import-links.test.ts",
"test:evolution": "tsx src/services/evobgp-catalog.test.ts && tsx src/services/evobgp-client.test.ts && tsx src/routes/evobgp-catalog.test.ts && tsx src/routes/evobgp-settings.test.ts && tsx src/plugins/auth.evolution-settings.test.ts", "test:evolution": "tsx src/services/evobgp-catalog.test.ts && tsx src/services/evobgp-client.test.ts && tsx src/routes/evobgp-catalog.test.ts && tsx src/routes/evobgp-settings.test.ts && tsx src/plugins/auth.evolution-settings.test.ts",
"test:netflow-purge": "tsx src/db/operation-lock.test.ts && tsx src/services/traffic-flow-purge-execution.test.ts && tsx src/services/flow-purge-partitions.test.ts && tsx --test src/services/traffic-flow-worker-lifecycle.test.ts && tsx src/routes/traffic-flow-purge.test.ts", "test:netflow-purge": "tsx src/db/operation-lock.test.ts && tsx src/services/traffic-flow-purge-execution.test.ts && tsx src/services/flow-purge-partitions.test.ts && tsx --test src/services/traffic-flow-worker-lifecycle.test.ts && tsx src/routes/traffic-flow-purge.test.ts",
"test:netflow-settings": "tsx src/services/traffic-flow-host-file-builders.test.ts && tsx src/services/traffic-flow-key-execution.test.ts && tsx src/routes/traffic-flow-settings.test.ts && tsx src/plugins/auth.netflow-settings.test.ts && tsx src/services/traffic-flow-agent-install.test.ts && tsx src/services/traffic-flow-agent-client.test.ts && tsx src/services/traffic-flow-operation-queue.test.ts && tsx src/routes/traffic-flow-host.test.ts && tsx src/services/traffic-flow-settings-execution.test.ts && tsx src/modules/mcp/flow-host-keys-actions.test.ts && tsx src/services/traffic-flow-lifecycle-fence.test.ts && tsx src/services/traffic-flow-settings-store.test.ts && tsx src/services/traffic-flow-settings-service.test.ts && tsx src/modules/mcp/flow-settings-actions.test.ts", "test:netflow-settings": "tsx src/services/traffic-flow-host-file-builders.test.ts && tsx src/services/traffic-flow-key-execution.test.ts && tsx src/routes/traffic-flow-settings.test.ts && tsx src/plugins/auth.netflow-settings.test.ts && tsx src/services/traffic-flow-agent-install.test.ts && tsx src/services/traffic-flow-agent-client.test.ts && tsx src/services/traffic-flow-operation-queue.test.ts && tsx src/routes/traffic-flow-host.test.ts && tsx src/services/traffic-flow-settings-execution.test.ts && tsx src/modules/mcp/flow-host-keys-actions.test.ts && tsx src/services/traffic-flow-lifecycle-fence.test.ts && tsx src/services/traffic-flow-settings-store.test.ts && tsx src/services/traffic-flow-settings-service.test.ts && tsx src/modules/mcp/flow-settings-actions.test.ts",
@@ -68,7 +69,7 @@
"test:containers": "tsx src/services/containers-live.test.ts && tsx src/services/containers-state.test.ts && tsx src/services/container-removal.test.ts && tsx src/routes/containers-state.test.ts", "test:containers": "tsx src/services/containers-live.test.ts && tsx src/services/containers-state.test.ts && tsx src/services/container-removal.test.ts && tsx src/routes/containers-state.test.ts",
"test:certificates": "tsx src/services/certificate-installation.test.ts && tsx src/services/certificate-renew-collector.test.ts && tsx src/services/certificate-issue-execution.test.ts && tsx src/services/certificate-issue-request.test.ts && tsx src/routes/certificates-issue.test.ts && tsx src/services/certificate-issue-dto.test.ts && tsx src/services/certificate-parse.test.ts && tsx src/services/certificates-state.test.ts && tsx src/routes/certificates-state.test.ts && tsx src/services/acme-settings-test.test.ts && tsx src/services/acme-settings-update-model.test.ts && tsx src/modules/mcp/acme-settings-actions.test.ts", "test:certificates": "tsx src/services/certificate-installation.test.ts && tsx src/services/certificate-renew-collector.test.ts && tsx src/services/certificate-issue-execution.test.ts && tsx src/services/certificate-issue-request.test.ts && tsx src/routes/certificates-issue.test.ts && tsx src/services/certificate-issue-dto.test.ts && tsx src/services/certificate-parse.test.ts && tsx src/services/certificates-state.test.ts && tsx src/routes/certificates-state.test.ts && tsx src/services/acme-settings-test.test.ts && tsx src/services/acme-settings-update-model.test.ts && tsx src/modules/mcp/acme-settings-actions.test.ts",
"test:system-database": "tsx src/services/bounded-database-dump.test.ts && tsx src/services/database-dump-connection.test.ts && tsx src/services/system-database-partition-restore.test.ts && tsx src/services/system-database-cache.test.ts && tsx src/services/database-background-work.test.ts && tsx src/services/database-request-gate.test.ts && tsx --test src/services/detached-database-admission.test.ts && tsx src/services/traffic-flow-worker-shutdown.test.ts && tsx src/services/system-database-restore-execution.test.ts && tsx src/services/system-database-operation.test.ts && tsx src/services/system-database-schema-readiness.test.ts && tsx --test src/routes/mcp-oauth-database-admission.test.ts && tsx src/routes/system-database.test.ts && tsx src/plugins/auth.system-database.test.ts && tsx src/services/database-control-archive-boundary.test.ts && tsx src/db/database-schema-control-model.test.ts && tsx src/db/database-schema-control.test.ts && tsx src/db/controlled-migrations.test.ts && tsx src/db/controlled-schema-verification.test.ts && tsx --test src/db/migration-data-inventory.test.ts && tsx --test src/services/database-maintenance-startup.test.ts && tsx --test src/services/database-restore-audit.test.ts && tsx --test src/services/database-maintenance-resolution.test.ts && tsx --test scripts/database-maintenance-resolution.test.mts && tsx src/db/database-runtime-schema.test.ts", "test:system-database": "tsx src/services/bounded-database-dump.test.ts && tsx src/services/database-dump-connection.test.ts && tsx src/services/system-database-partition-restore.test.ts && tsx src/services/system-database-cache.test.ts && tsx src/services/database-background-work.test.ts && tsx src/services/database-request-gate.test.ts && tsx --test src/services/detached-database-admission.test.ts && tsx src/services/traffic-flow-worker-shutdown.test.ts && tsx src/services/system-database-restore-execution.test.ts && tsx src/services/system-database-operation.test.ts && tsx src/services/system-database-schema-readiness.test.ts && tsx --test src/routes/mcp-oauth-database-admission.test.ts && tsx src/routes/system-database.test.ts && tsx src/plugins/auth.system-database.test.ts && tsx src/services/database-control-archive-boundary.test.ts && tsx src/db/database-schema-control-model.test.ts && tsx src/db/database-schema-control.test.ts && tsx src/db/controlled-migrations.test.ts && tsx src/db/controlled-schema-verification.test.ts && tsx --test src/db/migration-data-inventory.test.ts && tsx --test src/services/database-maintenance-startup.test.ts && tsx --test src/services/database-restore-audit.test.ts && tsx --test src/services/database-maintenance-resolution.test.ts && tsx --test scripts/database-maintenance-resolution.test.mts && tsx src/db/database-runtime-schema.test.ts",
"test:all": "npm run test:logs && npm run test:probes && npm run test:exec && npm run test:alert-engine && npm run test:alerts-telegram && npm run test:auth && npm run test:wireguard && npm run test:ipsec && npm run test:traffic-rate && npm run test:traffic-flow && npm run test:users && npm run test:pg && npm run test:sidebar-counts && npm run test:backups && npm run test:scheduler && npm run test:live-maps && npm run test:ospf-optimizer && npm run test:recursive-routes && npm run test:config-sync && npm run test:ros-file && npm run test:containers && npm run test:certificates && npm run test:netflow-settings && npm run test:netflow-purge && npm run test:evolution && npm run test:system-database && npm run test:server-privacy && npm run test:mcp:module-completion && npm run test:mcp:loopback-agent && npm run test:server-probe-management && npm run test:server-poll-management && npm run test:mcp:routing-authority && npm run test:mcp:native-readers && npm run test:mcp:chr-acquisition && npm run test:mcp:shared-context && npm run test:mcp:telemetry-configuration", "test:all": "npm run test:ix && npm run test:logs && npm run test:probes && npm run test:exec && npm run test:alert-engine && npm run test:alerts-telegram && npm run test:auth && npm run test:wireguard && npm run test:ipsec && npm run test:traffic-rate && npm run test:traffic-flow && npm run test:users && npm run test:pg && npm run test:sidebar-counts && npm run test:backups && npm run test:scheduler && npm run test:live-maps && npm run test:ospf-optimizer && npm run test:recursive-routes && npm run test:config-sync && npm run test:ros-file && npm run test:containers && npm run test:certificates && npm run test:netflow-settings && npm run test:netflow-purge && npm run test:evolution && npm run test:system-database && npm run test:server-privacy && npm run test:mcp:module-completion && npm run test:mcp:loopback-agent && npm run test:server-probe-management && npm run test:server-poll-management && npm run test:mcp:routing-authority && npm run test:mcp:native-readers && npm run test:mcp:chr-acquisition && npm run test:mcp:shared-context && npm run test:mcp:telemetry-configuration",
"test:server-privacy": "tsx ../packages/contracts/src/servers.test.ts && tsx src/routes/server-secrets-sql.test.ts && tsx --test src/services/server-connection-test.test.ts", "test:server-privacy": "tsx ../packages/contracts/src/servers.test.ts && tsx src/routes/server-secrets-sql.test.ts && tsx --test src/services/server-connection-test.test.ts",
"test:mcp:flow-rebuild:pg": "node scripts/test-mcp-postgres.mjs --flow-rebuild-mcp", "test:mcp:flow-rebuild:pg": "node scripts/test-mcp-postgres.mjs --flow-rebuild-mcp",
"test:mcp:flow-host-keys:pg": "node scripts/test-mcp-postgres.mjs --flow-host-keys", "test:mcp:flow-host-keys:pg": "node scripts/test-mcp-postgres.mjs --flow-host-keys",
+290 -10
View File
@@ -1,7 +1,7 @@
import assert from "node:assert/strict" import assert from "node:assert/strict"
import { randomBytes, randomUUID } from "node:crypto" import { createPrivateKey, createPublicKey, randomBytes, randomUUID } from "node:crypto"
import { mkdtemp } from "node:fs/promises" import { mkdtemp, writeFile } from "node:fs/promises"
import { createServer } from "node:http" import { createServer, type RequestListener } from "node:http"
import { tmpdir } from "node:os" import { tmpdir } from "node:os"
import { join } from "node:path" import { join } from "node:path"
import { setTimeout as delay } from "node:timers/promises" import { setTimeout as delay } from "node:timers/promises"
@@ -23,7 +23,8 @@ Object.assign(process.env, {
}) })
await pg.initialise() await pg.initialise()
await pg.start() await pg.start()
const rows: Record<string, Record<string, string>[]> = { type RouterRows = Record<string, Record<string, string>[]>
const rows: RouterRows = {
"/ip/vrf": [{ ".id": "*1", name: "main", interfaces: "all", builtin: "true" }], "/ip/vrf": [{ ".id": "*1", name: "main", interfaces: "all", builtin: "true" }],
"/interface": [{ ".id": "*A0", name: "gre-client", type: "gre", comment: "IX:ix-web-fixture" }], "/interface": [{ ".id": "*A0", name: "gre-client", type: "gre", comment: "IX:ix-web-fixture" }],
"/interface/gre": [{ ".id": "*A0", name: "gre-client", "local-address": "192.0.2.20", "remote-address": "192.0.2.21", "allow-fast-path": "false" }], "/interface/gre": [{ ".id": "*A0", name: "gre-client", "local-address": "192.0.2.20", "remote-address": "192.0.2.21", "allow-fast-path": "false" }],
@@ -34,26 +35,47 @@ let writes = 0
let deletes = 0 let deletes = 0
let failPutAt = -1 let failPutAt = -1
let failDeleteAt = -1 let failDeleteAt = -1
const router = createServer(async (request, response) => { const fixtureHubPublicKey = Buffer.alloc(32, 11).toString("base64")
const serveRouter = (rows: RouterRows): RequestListener => async (request, response) => {
try { try {
const path = new URL(request.url!, "http://127.0.0.1").pathname.replace(/^\/rest/, "") const path = new URL(request.url!, "http://127.0.0.1").pathname.replace(/^\/rest/, "")
let result: unknown let result: unknown
if (request.method === "GET") result = rows[path] ?? [] if (request.method === "GET") result = rows[path] ?? []
else if (request.method === "POST" && path === "/interface/print") {
let raw = ""
for await (const chunk of request) raw += chunk
const body = JSON.parse(raw)
assert.equal(body.stats, "")
result = (rows["/interface"] ?? []).map(row => {
const gre = rows["/interface/gre"]?.some(item => item.name === row.name)
return { name: row.name, "rx-byte": gre ? "1536" : "9000", "tx-byte": gre ? "2048" : "8000" }
})
}
else if (request.method === "PUT") { else if (request.method === "PUT") {
if (writes === failPutAt) throw Error("Synthetic RouterOS apply failure") if (writes === failPutAt) throw Error("Synthetic RouterOS apply failure")
let raw = "" let raw = ""
for await (const chunk of request) raw += chunk for await (const chunk of request) raw += chunk
const { "place-before": place, ...fields } = JSON.parse(raw) const { "place-before": place, ...fields } = JSON.parse(raw)
const row = { ...fields, ...(path === "/interface/wireguard" && { "public-key": "B".repeat(43) + "=" }), const row = { ...fields, ...(path === "/interface/wireguard" && { "public-key": fixtureHubPublicKey }),
".id": "*" + (++writes + 1).toString(16).toUpperCase() } ".id": "*" + (++writes + 1).toString(16).toUpperCase() }
const list = rows[path] ??= [] const list = rows[path] ??= []
const index = list.findIndex(entry => entry[".id"] === place) const index = list.findIndex(entry => entry[".id"] === place)
list.splice(index < 0 ? list.length : index, 0, row) list.splice(index < 0 ? list.length : index, 0, row)
if (path === "/ip/vrf" || path === "/interface/wireguard" || path === "/interface/bridge") { if (["/ip/vrf", "/interface/wireguard", "/interface/bridge", "/interface/gre"].includes(path)) {
rows["/interface"].push({ ".id": row[".id"], name: row.name, rows["/interface"].push({ ".id": row[".id"], name: row.name,
type: path === "/interface/wireguard" ? "wg" : path.split("/").at(-1)!, comment: row.comment }) type: path === "/interface/wireguard" ? "wg" : path.split("/").at(-1)!, comment: row.comment })
} }
result = row result = row
} else if (request.method === "PATCH") {
const parent = path.slice(0, path.lastIndexOf("/"))
const id = decodeURIComponent(path.slice(path.lastIndexOf("/") + 1))
const row = rows[parent]?.find(entry => entry[".id"] === id)
assert(row)
let raw = ""
for await (const chunk of request) raw += chunk
Object.assign(row, JSON.parse(raw))
writes++
result = row
} else if (request.method === "DELETE") { } else if (request.method === "DELETE") {
if (deletes === failDeleteAt) throw Error("Synthetic RouterOS deletion failure") if (deletes === failDeleteAt) throw Error("Synthetic RouterOS deletion failure")
const parent = path.slice(0, path.lastIndexOf("/")) const parent = path.slice(0, path.lastIndexOf("/"))
@@ -73,7 +95,16 @@ const router = createServer(async (request, response) => {
response.statusCode = 500 response.statusCode = 500
response.end(JSON.stringify({ error: String(error) })) response.end(JSON.stringify({ error: String(error) }))
} }
}) }
const router = createServer(serveRouter(rows))
const backupRows: RouterRows = {
"/ip/vrf": [{ ".id": "*1", name: "main", interfaces: "all", builtin: "true" }],
"/interface": [{ ".id": "*2", name: "ether1", type: "ether", running: "true" }],
"/ip/address": [{ ".id": "*3", interface: "ether1", address: "198.51.100.20/24" }],
"/ip/route": [{ ".id": "*4", "routing-table": "main", "dst-address": "0.0.0.0/0",
gateway: "198.51.100.1%ether1", "immediate-gw": "198.51.100.1%ether1", active: "true" }],
}
const backupRouter = createServer(serveRouter(backupRows))
const { initDatabase } = await import("../../src/db/bootstrap.js") const { initDatabase } = await import("../../src/db/bootstrap.js")
const { pool } = await import("../../src/db/index.js") const { pool } = await import("../../src/db/index.js")
let app: Awaited<ReturnType<typeof import("../../src/index.js").buildApp>> | undefined let app: Awaited<ReturnType<typeof import("../../src/index.js").buildApp>> | undefined
@@ -157,6 +188,7 @@ try {
assert.match(wg.template, /Endpoint = 192\.0\.2\.20:51820/) assert.match(wg.template, /Endpoint = 192\.0\.2\.20:51820/)
assert.match(wg.template, /Table = off/) assert.match(wg.template, /Table = off/)
assert(!wg.template.includes("A".repeat(43))) assert(!wg.template.includes("A".repeat(43)))
await post(path + "/linux/credential", { serverId: Number(server.id), interfaceName: "wg-ix-web" }, 404)
const gre = await linux("gre-client") const gre = await linux("gre-client")
assert.match(gre.template, /local_ts = 192\.0\.2\.21\/32\[47\]/) assert.match(gre.template, /local_ts = 192\.0\.2\.21\/32\[47\]/)
assert.match(gre.template, /remote_ts = 192\.0\.2\.20\/32\[47\]/) assert.match(gre.template, /remote_ts = 192\.0\.2\.20\/32\[47\]/)
@@ -250,7 +282,7 @@ try {
} }
const { token: mcpToken } = await mcpPost("connections", { name: "IX removal acceptance", mode: "approval", const { token: mcpToken } = await mcpPost("connections", { name: "IX removal acceptance", mode: "approval",
permissions: ["mm:network:write", "mm:network:read"], expiresAt: new Date(Date.now() + 300_000).toISOString(), permissions: ["mm:network:write", "mm:network:read"], expiresAt: new Date(Date.now() + 300_000).toISOString(),
scope: { allowGlobal: false, serverIds: [Number(server.id)], operationIds: ["network.ix.delete", "changes.apply", "operations.read"] } }) scope: { allowGlobal: false, serverIds: [Number(server.id)], operationIds: ["network.ix.delete", "network.wireguard.export", "changes.apply", "operations.read"] } })
mcp = new Client({ name: "ix-removal-acceptance", version: "1.0.0" }) mcp = new Client({ name: "ix-removal-acceptance", version: "1.0.0" })
await mcp.connect(new StreamableHTTPClientTransport(new URL(origin + "/mcp"), await mcp.connect(new StreamableHTTPClientTransport(new URL(origin + "/mcp"),
{ requestInit: { headers: { authorization: "Bearer " + mcpToken } } })) { requestInit: { headers: { authorization: "Bearer " + mcpToken } } }))
@@ -275,13 +307,261 @@ try {
assert.equal(terminal.state, "applied", JSON.stringify(terminal)) assert.equal(terminal.state, "applied", JSON.stringify(terminal))
assert.equal(terminal.verification, "passed") assert.equal(terminal.verification, "passed")
assert.equal(deletes, writes) assert.equal(deletes, writes)
const managed = (await post("", { revision: 0, configuration: { name: "ix-web-managed", sites: [
{ serverId: Number(server.id), autonomousSystem: 64512, routerId: "192.0.2.6" },
] } }, 200)).segment
const managedPath = "/" + managed.id
rows["/interface"].push({ ".id": "*FA", name: "ether1", type: "ether", running: "true" })
;(rows["/ip/address"] ??= []).push(
{ ".id": "*FB", interface: "ether1", address: "192.0.2.20/24" },
{ ".id": "*FC", interface: "ether1", address: "192.0.2.30/24" },
)
;(rows["/ip/route"] ??= []).push({ ".id": "*FD", "routing-table": "main", "dst-address": "0.0.0.0/0",
gateway: "192.0.2.1%ether1", "immediate-gw": "192.0.2.1%ether1", active: "true" })
const clientInput = { serverId: Number(server.id), name: "linux-auto", kind: "wireguard", hubEndpoint: "192.0.2.20",
peerEndpoint: "192.0.2.40", exit: "local-wan", prefixes: [], destinations: ["203.0.113.0/24"], enabled: true }
const staged = await post(managedPath + "/linux", { ...clientInput, revision: managed.revision }, 200)
assert.match(staged.interfaceName, /^il-wg-[a-z0-9-]+-[0-9a-f]{12}$/)
assert.ok(staged.segment.configuration.sites[0].interfaces[0].linux.clientId)
const clientKey = { serverId: clientInput.serverId, interfaceName: staged.interfaceName }
await post(managedPath + "/linux/credential", clientKey, 409)
await post(managedPath + "/linux/credential", clientKey, 403, reader)
const edited = await post(managedPath + "/linux", { ...clientInput, ...clientKey, revision: staged.segment.revision, name: "linux-renamed" }, 200)
const provision = edited.segment.configuration.sites[0].interfaces[0].provisionWireguard
assert.deepEqual(provision, staged.segment.configuration.sites[0].interfaces[0].provisionWireguard)
const plan = await post(managedPath + "/plan", { revision: edited.segment.revision }, 200)
await post(managedPath + "/apply", { revision: edited.segment.revision, digest: plan.digest }, 200)
const credential = await post(managedPath + "/linux/credential", clientKey, 200)
const privateKey = credential.template.match(/^PrivateKey = ([A-Za-z0-9+/]{43}=)$/m)?.[1]
assert.ok(privateKey)
const scalar = Buffer.from(privateKey, "base64")
const key = createPrivateKey({ key: Buffer.concat([Buffer.from("302e020100300506032b656e04220420", "hex"), scalar]),
format: "der", type: "pkcs8" })
const publicKey = createPublicKey(key).export({ format: "der", type: "spki" }).subarray(-32).toString("base64")
assert.equal(publicKey, provision.peerPublicKey)
assert.equal(rows["/interface/wireguard/peers"].find(row => row.interface === clientKey.interfaceName)?.["public-key"], publicKey)
assert(!JSON.stringify([edited, plan, rows]).includes(privateKey))
const templateResponse = await fetch(origin + "/api/ix/segments" + managedPath + "/linux?" + new URLSearchParams({
serverId: String(clientKey.serverId), interfaceName: clientKey.interfaceName,
}), { headers: { authorization: "Bearer " + reader } })
assert.equal(templateResponse.status, 200)
assert.match((await templateResponse.json()).template, /PrivateKey = <локальный_приватный_ключ>/)
const exportPlan = await call<{ planId: string; state: string }>("mm_wireguard_export_plan",
{ ...clientKey, ixSegmentId: managed.id, format: "peer-conf" })
assert.equal(exportPlan.state, "awaiting-approval")
assert(!JSON.stringify(exportPlan).includes(privateKey))
await mcpPost("plans/" + exportPlan.planId + "/decision", { approve: true })
const exportOperation = await call<Operation>("mm_change_apply", { planId: exportPlan.planId, idempotencyKey: randomUUID() })
let exported = exportOperation
for (let attempts = 0; attempts < 50 && ["pending", "running"].includes(exported.state); attempts++) {
await delay(200)
exported = await call<Operation>("mm_operation_get", { operationId: exportOperation.id })
}
assert.equal(exported.state, "applied", JSON.stringify(exported))
assert(!JSON.stringify(exported).includes(privateKey))
const { rows: [{ result: receipt }] } = await pool.query("SELECT result FROM mcp_operation_steps WHERE operation_id=$1", [exported.id])
assert.equal(receipt.humanDownloadOnly, true)
const secretRecords = await pool.query(`SELECT to_jsonb(s) AS record FROM mcp_operation_steps s WHERE operation_id=$1
UNION ALL SELECT to_jsonb(p) FROM mcp_plans p WHERE id=$2
UNION ALL SELECT to_jsonb(a) FROM mcp_artifacts a WHERE id=$3
UNION ALL SELECT to_jsonb(a) FROM mcp_audit a WHERE actor_id IN ('ix-web-owner','ix-mcp-owner')`,
[exported.id, exportPlan.planId, receipt.artifactId])
assert(!JSON.stringify(secretRecords.rows).includes(privateKey))
const download = await fetch(origin + receipt.downloadPath, { headers: { authorization: "Bearer " + mcpJwt } })
assert.equal(download.status, 200)
assert.equal(await download.text(), credential.template)
assert.equal(download.headers.get("cache-control"), "private, no-store")
const denied = await fetch(origin + receipt.downloadPath, { headers: { authorization: "Bearer " + otherWriter } })
assert.equal(denied.status, 403)
const appliedPeer = rows["/interface/wireguard/peers"].find(row => row.interface === clientKey.interfaceName)!
appliedPeer.disabled = "true"
const inactive = await fetch(origin + receipt.downloadPath, { headers: { authorization: "Bearer " + mcpJwt } })
assert.equal(inactive.status, 409)
delete appliedPeer.disabled
const companionInput = { ...clientInput, kind: "gre-ipsec", companionOf: clientKey.interfaceName }
const canceled = await post(managedPath + "/linux", { ...companionInput, revision: credential.revision }, 200)
const canceledKey = { serverId: clientKey.serverId, interfaceName: canceled.interfaceName }
const reverted = await post(managedPath + "/linux/revoke", { ...canceledKey, revision: canceled.segment.revision }, 200)
const noChanges = await post(managedPath + "/plan", { revision: reverted.segment.revision }, 200)
assert.deepEqual(noChanges.changes, [])
const resumed = await post(managedPath + "/apply", { revision: reverted.segment.revision, digest: noChanges.digest }, 200)
const paired = await post(managedPath + "/linux", { ...companionInput, revision: resumed.segment.revision }, 200)
const bindings = paired.segment.configuration.sites[0].interfaces
const [wireguard, greBinding] = bindings
assert.match(greBinding.name, /^il-gre-[a-z0-9-]+-[0-9a-f]{12}$/)
assert.ok(wireguard.linux.clientId)
const original = resumed.segment.configuration.sites[0].interfaces[0]
assert.deepEqual(wireguard, { ...original, linux: { ...original.linux, clientId: wireguard.linux.clientId } })
assert.equal(wireguard.linux.clientId, greBinding.linux.clientId)
assert.notEqual(wireguard.provisionWireguard.peerAddress, greBinding.provisionGre.peerAddress)
const foreignRoute = { ".id": "*FE", "routing-table": "main", "dst-address": "198.51.100.0/24",
gateway: "10.254.0.2%" + clientKey.interfaceName }
rows["/ip/route"].push(foreignRoute)
const blockedForeign = await post(managedPath + "/plan", { revision: paired.segment.revision }, 409)
assert.match(blockedForeign.error, /другой маршрутизацией/)
assert.equal(rows["/ip/route"].pop(), foreignRoute)
const pairPlan = await post(managedPath + "/plan", { revision: paired.segment.revision }, 200)
assert(!pairPlan.changes.some(change => change.path.startsWith("/interface/wireguard")))
const pairedApplied = await post(managedPath + "/apply", { revision: paired.segment.revision, digest: pairPlan.digest }, 200)
const countersResponse = await fetch(origin + "/api/ix/segments" + managedPath + "/linux", { headers: { authorization: "Bearer " + reader } })
assert.equal(countersResponse.status, 200)
const observedGre = (await countersResponse.json()).items.find(item => item.interfaceName === greBinding.name)
assert.equal(observedGre.connection.rx, "1536")
assert.equal(observedGre.connection.tx, "2048")
const pairVrf = rows["/ip/vrf"].find(row => row.interfaces?.includes(wireguard.name))!
assert(pairVrf.interfaces.split(",").includes(greBinding.name))
const greCredential = await post(managedPath + "/linux/credential",
{ serverId: clientKey.serverId, interfaceName: paired.interfaceName }, 200)
assert.match(greCredential.template, /secret = "[a-f0-9]{64}"/)
assert.match(greCredential.setup, /install -m 0600 "\$conf" \/etc\/swanctl\/conf\.d\//)
assert.match(greCredential.setup, /ip -4 rule add pref \d+ from 192\.0\.2\.40\/32 lookup main/)
assert.match(greCredential.setup, /ip -4 route replace default dev ixg\w+ src \S+ table \d+/)
assert(greCredential.setup.indexOf(" lookup main\n") < greCredential.setup.indexOf("swanctl --initiate"))
assert.equal((await post(managedPath + "/linux/credential", clientKey, 200)).template, credential.template)
const bondPath = managedPath + "/linux-bonds"
const bondInput = { revision: 0, name: "mixed", mode: "weighted", directCidrs: ["192.0.2.0/24"],
members: [wireguard, greBinding].map((binding, i) => ({ segmentId: managed.id, serverId: clientKey.serverId,
interfaceName: binding.name, weight: i ? 1 : 3, appliedRevision: pairedApplied.segment.revision })) }
await post(bondPath, bondInput, 403, reader)
const bond = await post(bondPath, bondInput, 200)
assert.equal(bond.clientId, wireguard.linux.clientId)
await post(bondPath, bondInput, 409)
const bundlePath = bondPath + "/" + bond.id + "/export"
const bundle = await post(bundlePath, { revision: 1 }, 200)
assert.deepEqual(bundle.members.map(member => [member.kind, member.weight]), [["wireguard", 3], ["gre-ipsec", 1]])
assert.equal(bundle.members[0].peerPublicKey, fixtureHubPublicKey)
assert.deepEqual(bundle.destinations, ["0.0.0.0/0"])
assert(!JSON.stringify(bundle).includes(privateKey))
if (process.env.IX_BOND_TEST_EXPORT) {
await writeFile(process.env.IX_BOND_TEST_EXPORT, JSON.stringify(bundle, null, 2) + "\n", { flag: "wx" })
}
await post(bundlePath, { revision: 1 }, 403, reader)
await post(managedPath + "/removal-plan", { revision: pairedApplied.segment.revision }, 409)
const { rows: [exit] } = await pool.query(`INSERT INTO servers
(name,host,port,enabled,type,username,password,use_ssl,verify_ssl)
VALUES('owned-exit','127.0.0.1',$1,true,'exit-node','synthetic','synthetic',false,true) RETURNING id`, [port])
const transit = { targetServerId: Number(exit.id), localEndpoint: "192.0.2.20", remoteEndpoint: "192.0.2.30", family: 4, name: "remote-exit" }
const appliedRevision = pairedApplied.segment.revision
const remoteClient = { ...clientInput, name: "linux-remote", revision: appliedRevision, exit: undefined, transit }
const beforeStage = writes
await post(managedPath + "/linux", { ...remoteClient, localAddress: "10.254.21.1/30" }, 400)
const stagedRemote = await post(managedPath + "/linux", remoteClient, 200)
assert(!Object.hasOwn(stagedRemote.segment.configuration, "linuxBonds"))
assert.deepEqual(await post(bundlePath, { revision: 1 }, 200), bundle)
const racing = await Promise.all(["equal", "failover"].map(mode => fetch(origin + "/api/ix/segments" + bondPath, {
method: "POST", headers: { authorization: "Bearer " + writer, "content-type": "application/json" },
body: JSON.stringify({ ...bondInput, id: bond.id, revision: 1, mode }),
})))
assert.deepEqual(racing.map(r => r.status).sort(), [200, 409])
const revised = await racing.find(r => r.ok)!.json()
assert.equal(revised.revision, 2)
await post(bundlePath, { revision: 1 }, 409)
await post(bondPath + "/" + bond.id, { revision: 2 }, 204, writer, "DELETE")
await post(bundlePath, { revision: 2 }, 409)
assert.equal(writes, beforeStage)
assert.equal(stagedRemote.segment.revision, appliedRevision + 1)
assert.equal(stagedRemote.segment.appliedRevision, appliedRevision)
const remoteSite = stagedRemote.segment.configuration.sites[0]
assert.equal(remoteSite.interfaces.find(row => row.name === stagedRemote.interfaceName).linux.exit, transit.name)
const transitBinding = remoteSite.interfaces.find(row => row.name === remoteSite.groups.find(group => group.id === transit.name).primary.interface)
assert.equal(transitBinding.peerServerId, Number(exit.id))
const { ixReservedTunnelBindings } = await import("../../src/services/internet-exchange-store.js")
assert((await ixReservedTunnelBindings(Number(exit.id))).some(binding => binding.name === transitBinding.name))
const remotePlan = await post(managedPath + "/plan", { revision: stagedRemote.segment.revision }, 200)
assert(remotePlan.changes.some(change => change.serverId === Number(exit.id) &&
change.path === "/ip/firewall/nat" && change.fields["out-interface"] === "ether1"))
assert(remotePlan.changes.some(change => change.serverId === Number(server.id) && change.path === "/interface/wireguard"))
assert.equal(writes, beforeStage)
const both = await post(managedPath + "/linux", { ...clientInput, name: "both", peerEndpoint: "192.0.2.41",
revision: stagedRemote.segment.revision, additionalGre: true }, 200)
const added = both.segment.configuration.sites[0].interfaces.filter(binding => binding.linux?.name === "both")
assert.deepEqual(added.map(binding => binding.kind), ["wireguard", "gre-ipsec"])
assert.ok(added[0].linux.clientId)
assert.equal(added[0].linux.clientId, added[1].linux.clientId)
await new Promise<void>(resolve => backupRouter.listen(0, "127.0.0.1", resolve))
const { rows: [secondIx] } = await pool.query(`INSERT INTO servers
(name,host,port,enabled,type,username,password,use_ssl,verify_ssl)
VALUES('owned-bond-peer','127.0.0.1',$1,true,'ix-node','synthetic','synthetic',false,true) RETURNING id`,
[(backupRouter.address() as { port: number }).port])
const secondSegment = (await post("", { revision: 0, configuration: { name: "ix-web-bond-peer", sites: [
{ serverId: Number(secondIx.id), autonomousSystem: 64513, routerId: "192.0.2.8" },
] } }, 200)).segment
const secondPath = "/" + secondSegment.id
const secondInput = { ...clientInput, hubEndpoint: "198.51.100.20", serverId: Number(secondIx.id), revision: secondSegment.revision }
await post(secondPath + "/linux", { ...secondInput, vpsClientId: randomUUID() }, 409)
const existingPair = await post(secondPath + "/linux", { ...secondInput, additionalGre: true }, 200)
const initialPairPlan = await post(secondPath + "/plan", { revision: existingPair.segment.revision }, 200)
const appliedPair = (await post(secondPath + "/apply", { revision: existingPair.segment.revision, digest: initialPairPlan.digest }, 200)).segment
const [oldWg, oldGre] = appliedPair.configuration.sites[0].interfaces
assert.notEqual(oldWg.linux.clientId, bond.clientId)
const changeIdentity = { ...secondInput, interfaceName: oldWg.name, vpsClientId: bond.clientId, revision: appliedPair.revision }
const secondWg = await post(secondPath + "/linux", changeIdentity, 200)
const newTunnel = secondWg.segment.configuration.sites[0].interfaces[0]
assert.deepEqual(newTunnel, { ...oldWg, linux: { ...oldWg.linux, clientId: bond.clientId } })
assert.deepEqual(secondWg.segment.configuration.sites[0].interfaces[1], oldGre)
assert.notEqual(newTunnel.provisionWireguard.peerAddress, wireguard.provisionWireguard.peerAddress)
const secondaryPlan = await post(secondPath + "/plan", { revision: secondWg.segment.revision }, 200)
assert.deepEqual(secondaryPlan.changes, [])
const secondaryApplied = (await post(secondPath + "/apply", { revision: secondWg.segment.revision, digest: secondaryPlan.digest }, 200)).segment
const cross = await post(bondPath, { ...bondInput, members: [bondInput.members[0], {
segmentId: secondSegment.id, appliedRevision: secondaryApplied.revision, serverId: secondInput.serverId, interfaceName: secondWg.interfaceName, weight: 1,
}] }, 200)
await post(secondPath + "/removal-plan", { revision: secondaryApplied.revision }, 409)
const groupedChange = await post(secondPath + "/linux", { ...changeIdentity, vpsClientId: oldGre.linux.clientId, revision: secondaryApplied.revision }, 409)
assert.match(groupedChange.error, /исключите подключение/)
const crossBundle = await post(bondPath + "/" + cross.id + "/export", { revision: 1 }, 200)
assert.equal(crossBundle.members[1].address, newTunnel.provisionWireguard.peerAddress)
await post(bondPath + "/" + cross.id, { revision: 1 }, 204, writer, "DELETE")
const ownPublicKey = Buffer.alloc(32, 29).toString("base64")
const manualVrf = backupRows["/ip/vrf"]
const manualGrePolicy = { "src-address": "198.51.100.20/32", "dst-address": "192.0.2.22/32", protocol: "gre", action: "encrypt", level: "require", tunnel: "false" }
backupRows["/interface/wireguard"].push({ name: "pre-wg", "public-key": fixtureHubPublicKey })
backupRows["/interface/wireguard/peers"].push({ interface: "pre-wg", "public-key": ownPublicKey, "allowed-address": "10.7.0.2/32" })
backupRows["/interface/gre"].push({ name: "pre-gre", "local-address": "198.51.100.20", "remote-address": "192.0.2.22", "allow-fast-path": "false" })
backupRows["/ip/ipsec/policy"].push(manualGrePolicy)
backupRows["/ip/address"].push({ interface: "pre-wg", address: "10.7.0.1/30" }, { interface: "pre-gre", address: "10.8.0.1/30" })
const refs = ["pre-wg", "pre-gre"].map((interfaceName, i) => ({ interfaceName, segmentId: secondSegment.id, serverId: secondInput.serverId,
appliedRevision: secondaryApplied.revision, weight: 1, existing: { linuxInterface: i ? "gre-manual" : "wg0", address: "10." + (7 + i) + ".0.2",
probe: "10." + (7 + i) + ".0.1", endpoint: "198.51.100.20", destinations: ["10.250.0.0/24"],
...(i ? { kind: "gre-ipsec", remoteEndpoint: "192.0.2.22" } : { kind: "wireguard", clientPublicKey: ownPublicKey }) } }))
const manualPath = secondPath + "/linux-bonds"
const manualInput = { ...bondInput, name: "existing", members: refs }
const beforeManual = JSON.stringify(backupRows)
const writesBeforeManual = writes
await post(manualPath, manualInput, 403, reader)
await post(manualPath, { ...manualInput, members: [{ ...refs[0], existing: { ...refs[0].existing, clientPublicKey: fixtureHubPublicKey } }, refs[1]] }, 409)
manualVrf.unshift({ name: "another-vrf", interfaces: "pre-wg" })
await post(manualPath, manualInput, 409)
manualVrf.shift()
const manual = await post(manualPath, manualInput, 200)
const manualExport = manualPath + "/" + manual.id + "/export"
const result = await post(manualExport, { revision: 1 }, 200)
assert.deepEqual(result.members.map(p => p.interfaceName), ["wg0", "gre-manual"])
assert.equal(result.members[0].peerPublicKey, fixtureHubPublicKey)
manualGrePolicy.level = "use"
await post(manualExport, { revision: 1 }, 409)
manualGrePolicy.level = "require"
await post(manualPath + "/" + manual.id, { revision: 1 }, 204, writer, "DELETE")
assert.equal(writes, writesBeforeManual)
assert.equal(JSON.stringify(backupRows), beforeManual)
await post(secondPath + "/removal-plan", { revision: secondaryApplied.revision }, 200)
console.log(JSON.stringify({ appliedRevisions: [2, 4], writes, audit: audit.n, mcpConnections: connections.n, console.log(JSON.stringify({ appliedRevisions: [2, 4], writes, audit: audit.n, mcpConnections: connections.n,
unauthenticated: 401, readOnly: 403, ownerMismatch: 409, drift: 409, replay: 409, protected: 409, linuxClients: clients.items.length, unauthenticated: 401, readOnly: 403, ownerMismatch: 409, drift: 409, replay: 409, protected: 409, linuxClients: clients.items.length,
deletedDraft: true, removedNativeObjects: deletes, revisionsRetained: archive.revisions, mcpRemovalVerified: true })) deletedDraft: true, removedNativeObjects: deletes, revisionsRetained: archive.revisions,
mcpRemovalVerified: true, managedWireguardVerified: true, clientWithTransitStagedAtomically: true, bothProtocolsInOneVrf: true,
mixedBondExport: true, crossSegmentBond: true, concurrentBondEdits: true, existingRouterOsTunnels: true }))
} finally { } finally {
await mcp?.close() await mcp?.close()
await app?.close() await app?.close()
await new Promise<void>(resolve => router.close(() => resolve())) await new Promise<void>(resolve => router.close(() => resolve()))
if (backupRouter.listening) await new Promise<void>(resolve => backupRouter.close(() => resolve()))
await pool.end() await pool.end()
await pg.stop() await pg.stop()
} }
+2
View File
@@ -27,6 +27,7 @@ import internetPathRoutes from "./routes/internet-path.js"
import evobgpRoutes from "./routes/evobgp.js" import evobgpRoutes from "./routes/evobgp.js"
import { createStorageProbeRoutes } from "./routes/probe-storage-handler.js" import { createStorageProbeRoutes } from "./routes/probe-storage-handler.js"
import schedulerRoutes from "./routes/scheduler.js" import schedulerRoutes from "./routes/scheduler.js"
import { ConfigurationBusyError } from "./services/config-mutation-lock.js"
import sidebarCountsRoutes from "./routes/sidebar-counts.js" import sidebarCountsRoutes from "./routes/sidebar-counts.js"
import alertsRoutes from "./routes/alerts.js" import alertsRoutes from "./routes/alerts.js"
import backupsRoutes from "./routes/backups.js" import backupsRoutes from "./routes/backups.js"
@@ -105,6 +106,7 @@ export async function buildApp(opts?: {
return reply.status(status).send({ error: "Внутренняя ошибка сервера" }) return reply.status(status).send({ error: "Внутренняя ошибка сервера" })
} }
const message = error instanceof Error ? error.message : "Ошибка запроса" const message = error instanceof Error ? error.message : "Ошибка запроса"
if (error instanceof ConfigurationBusyError) return reply.code(409).send({ error: message, code: error.code })
return reply.status(status).send({ error: message }) return reply.status(status).send({ error: message })
}) })
+5
View File
@@ -9,6 +9,11 @@ assert.equal(new Set(coverage.routes.map(routeKey)).size, coverage.routes.length
assert.deepEqual(coverage.routes.map(routeKey).sort(), actual.map(routeKey).sort(), "REST routes changed: update mcp-coverage.json with a typed tool, human-only reason, or explicit pending adapter") assert.deepEqual(coverage.routes.map(routeKey).sort(), actual.map(routeKey).sort(), "REST routes changed: update mcp-coverage.json with a typed tool, human-only reason, or explicit pending adapter")
const implemented = new Set(listActions().map(action => action.operation.id)) const implemented = new Set(listActions().map(action => action.operation.id))
const ixInterfaceRoutes = new Set([ const ixInterfaceRoutes = new Set([
"POST /api/ix/import",
"GET /api/ix/linux-bonds",
"POST /api/ix/segments/:id/linux-bonds",
"DELETE /api/ix/segments/:id/linux-bonds/:bondId",
"POST /api/ix/segments/:id/linux-bonds/:bondId/export",
"GET /api/ix/nodes", "GET /api/ix/nodes",
"GET /api/ix/segments/:id/linux", "GET /api/ix/segments/:id/linux",
"GET /api/ix/topology", "GET /api/ix/topology",
@@ -10,6 +10,8 @@ const leases = createPool(limit, true)
leases.on("error", () => console.error("MCP database request lease lost on idle connection")) leases.on("error", () => console.error("MCP database request lease lost on idle connection"))
const apiLeases = createPool(limit, true) const apiLeases = createPool(limit, true)
apiLeases.on("error", () => console.error("REST database request lease lost on idle connection")) apiLeases.on("error", () => console.error("REST database request lease lost on idle connection"))
const writeReserve = createPool(2, true)
writeReserve.on("error", () => console.error("REST write database lease lost on idle connection"))
const detachedApiLeases = createPool(2, true) const detachedApiLeases = createPool(2, true)
detachedApiLeases.on("error", () => console.error("Detached REST database lease lost on idle connection")) detachedApiLeases.on("error", () => console.error("Detached REST database lease lost on idle connection"))
const context = new AsyncLocalStorage<{ accepting: boolean; children: Set<Promise<unknown>>; signal: AbortSignal }>() const context = new AsyncLocalStorage<{ accepting: boolean; children: Set<Promise<unknown>>; signal: AbortSignal }>()
@@ -28,19 +30,24 @@ export function withActiveDatabaseRequest<T>(run: (signal: AbortSignal) => Promi
return child return child
} }
export function withMcpDatabaseRequest<T>(run: () => Promise<T>): Promise<T> { return withDatabaseRequest(run, true) } export function withMcpDatabaseRequest<T>(run: () => Promise<T>): Promise<T> { return withDatabaseRequest(run, leases) }
export function withDatabaseApiRequest<T>(run: () => Promise<T>): Promise<T> { return withDatabaseRequest(run, false) } export function withDatabaseApiRequest<T>(run: () => Promise<T>, mutation = false): Promise<T> {
// A burst of slow GETs must leave room for a configuration change to reach its lock.
const saturated = apiLeases.totalCount >= limit && apiLeases.idleCount === 0
return withDatabaseRequest(run, mutation && saturated ? writeReserve : apiLeases)
}
export function checkDatabaseApiStartup(): Promise<void> { export function checkDatabaseApiStartup(): Promise<void> {
return withDatabaseRequest(async () => {}, false, false, true) return withDatabaseRequest(async () => {}, apiLeases, true)
} }
async function withDatabaseRequest<T>(run: () => Promise<T>, mcp: boolean, detached = false, starting = false): Promise<T> { async function withDatabaseRequest<T>(run: () => Promise<T>, pool: typeof apiLeases, starting = false): Promise<T> {
const nested = withActiveDatabaseRequest(run) const nested = withActiveDatabaseRequest(run)
if (nested) return nested if (nested) return nested
const mcp = pool === leases
if (mcp && active >= limit) throw new McpError("RATE_LIMITED", "Лимит одновременно выполняемых запросов MCP", 429) if (mcp && active >= limit) throw new McpError("RATE_LIMITED", "Лимит одновременно выполняемых запросов MCP", 429)
if (mcp) active++ if (mcp) active++
try { try {
const client = await (detached ? detachedApiLeases : mcp ? leases : apiLeases).connect() const client = await pool.connect()
let destroy = true, acquired = false let destroy = true, acquired = false
const lifetime = new AbortController() const lifetime = new AbortController()
const disconnected = () => lifetime.abort(new McpError("PROTOCOL_STORAGE_BUSY", "Соединение с допуском MCP потеряно", 503)) const disconnected = () => lifetime.abort(new McpError("PROTOCOL_STORAGE_BUSY", "Соединение с допуском MCP потеряно", 503))
@@ -90,5 +97,5 @@ export function withMcpRunnerDatabaseRequest<T>(run: () => Promise<T>): Promise<
/** Detached jobs keep their own lease through terminal persistence after the HTTP response. */ /** Detached jobs keep their own lease through terminal persistence after the HTTP response. */
export function withDetachedDatabaseApiRequest<T>(run: () => Promise<T>): Promise<T> { export function withDetachedDatabaseApiRequest<T>(run: () => Promise<T>): Promise<T> {
return context.exit(() => sharedDatabaseGate.request(() => withDatabaseRequest(run, false, true))) return context.exit(() => sharedDatabaseGate.request(() => withDatabaseRequest(run, detachedApiLeases)))
} }
+1 -1
View File
@@ -49,7 +49,7 @@ export function registerFlowMapActions(register: typeof add) {
await authorize() await authorize()
const output = { serverId: server.id, userId: input.userId ?? null, interface: input.interface ?? null, map: projected, pages, sourceWindow, 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, readStartedAt: startedAt, observedAt: new Date().toISOString(), live: false, listenerBound,
source: "retained flow_buckets plus pending; same REST map engine with scoped topology", 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",
topRowsPerBucketLimit: Math.max(20, limits.topN), rowLimit: 20000, incomplete: true, graphComplete: false, topRowsPerBucketLimit: Math.max(20, limits.topN), rowLimit: 20000, incomplete: true, graphComplete: false,
referencedNodesMayBeOutsidePage: true, inferredPathsVerified: false, forwardingVerified: false, coverageVerified: false, referencedNodesMayBeOutsidePage: true, inferredPathsVerified: false, forwardingVerified: false, coverageVerified: false,
rowSumIsNetworkTotal: false, historicalOwnershipVerified: false, rowSumIsNetworkTotal: false, historicalOwnershipVerified: false,
@@ -94,6 +94,7 @@ test("actual collector initial settings failures release resource/ping/group bus
const modules:Record<string,unknown>={"../db/index.js":{db,dbAll:async()=>[]},"../db/schema.js":tables,"drizzle-orm":Object.fromEntries(["and","asc","eq","gte","lte","inArray","max","sql"].map(name=>[name,()=>null])), const modules:Record<string,unknown>={"../db/index.js":{db,dbAll:async()=>[]},"../db/schema.js":tables,"drizzle-orm":Object.fromEntries(["and","asc","eq","gte","lte","inArray","max","sql"].map(name=>[name,()=>null])),
"./config-mutation-policy.js":{executeGuardedApplicationWrite:()=>assert.fail("no config mutation")},"./monitoring-server-catalog.js":{listEnabledMonitoringServers:async()=>[]},"./mikrotik.js":{MikrotikClient:class{}},"../types/scheduler-run-snapshot.js":{SCHEDULER_RUN_SNAPSHOT_VERSION:1},"../constants/ping-probe.js":{PING_PROBE_WARN_RTT_MS:100},"./ros-metric-parse.js":{},"./ping-probe-replacement.js":{},"./partition-write-transaction.js":{withPartitionWrite:()=>assert.fail("no targets"),isPartitionWriteOutcomeUnknown:()=>false,PartitionWriteError:class extends Error{}}} "./config-mutation-policy.js":{executeGuardedApplicationWrite:()=>assert.fail("no config mutation")},"./monitoring-server-catalog.js":{listEnabledMonitoringServers:async()=>[]},"./mikrotik.js":{MikrotikClient:class{}},"../types/scheduler-run-snapshot.js":{SCHEDULER_RUN_SNAPSHOT_VERSION:1},"../constants/ping-probe.js":{PING_PROBE_WARN_RTT_MS:100},"./ros-metric-parse.js":{},"./ping-probe-replacement.js":{},"./partition-write-transaction.js":{withPartitionWrite:()=>assert.fail("no targets"),isPartitionWriteOutcomeUnknown:()=>false,PartitionWriteError:class extends Error{}}}
const exports:Record<string,(...args:unknown[])=>Record<string,unknown>|Promise<Record<string,unknown>>>={} const exports:Record<string,(...args:unknown[])=>Record<string,unknown>|Promise<Record<string,unknown>>>={}
modules["./config-mutation-lock.js"] = { withApplicationCollectorLock: (collect: () => Promise<unknown>) => collect() }
const code=ts.transpileModule(await readFile(new URL("../../services/uptime-collector.ts",import.meta.url),"utf8"),{compilerOptions:{module:ts.ModuleKind.CommonJS,target:ts.ScriptTarget.ES2022}}).outputText const code=ts.transpileModule(await readFile(new URL("../../services/uptime-collector.ts",import.meta.url),"utf8"),{compilerOptions:{module:ts.ModuleKind.CommonJS,target:ts.ScriptTarget.ES2022}}).outputText
runInNewContext(code,{exports,require:(name:string)=>{assert(name in modules,name);return modules[name]},Date,performance,console,Set,Map,Promise,Number,String,Math,Object,JSON,Error}) runInNewContext(code,{exports,require:(name:string)=>{assert(name in modules,name);return modules[name]},Date,performance,console,Set,Map,Promise,Number,String,Math,Object,JSON,Error})
for(const method of ["collectResourceSamplesOnce","collectPingProbesOnce","collectPingForProbeIds"]){ for(const method of ["collectResourceSamplesOnce","collectPingProbesOnce","collectPingForProbeIds"]){
+13 -2
View File
@@ -85,6 +85,17 @@ const firewall = {
"src-address-list": text.optional(), "dst-address-list": text.optional(), "connection-state": text.optional(), "src-address-list": text.optional(), "dst-address-list": text.optional(), "connection-state": text.optional(),
comment: text.optional(), disabled: bool.optional(), log: bool.optional(), "log-prefix": text.optional(), comment: text.optional(), disabled: bool.optional(), log: bool.optional(), "log-prefix": text.optional(),
} }
const ipv4Mangle = {
...firewall,
"tcp-flags": z.string().regex(/^!?(?:ack|cwr|ece|fin|psh|rst|syn|urg)(?:,!?(?:ack|cwr|ece|fin|psh|rst|syn|urg)){0,7}$/)
.refine(value => new Set(value.replaceAll("!", "").split(",")).size === value.split(",").length, "Флаги TCP не должны повторяться").optional(),
"tcp-mss": z.string().regex(/^(?:0|[1-9]\d{0,4})(?:-(?:0|[1-9]\d{0,4}))?$/).refine(value => {
const [min, max = min] = value.split("-").map(Number)
return min <= max && max <= 65535
}, "Требуется значение или диапазон TCP MSS от 0 до 65535").optional(),
"new-mss": integer(1, 65535).optional(),
passthrough: bool.optional(),
}
const route = { const route = {
"dst-address": name.optional(), gateway: name.optional(), distance: integer(1, 255).optional(), scope: integer(0, 255).optional(), "dst-address": name.optional(), gateway: name.optional(), distance: integer(1, 255).optional(), scope: integer(0, 255).optional(),
"target-scope": integer(0, 255).optional(), "routing-table": name.optional(), "check-gateway": z.enum(["none", "ping", "arp", "bfd"]).optional(), "target-scope": integer(0, 255).optional(), "routing-table": name.optional(), "check-gateway": z.enum(["none", "ping", "arp", "bfd"]).optional(),
@@ -112,7 +123,7 @@ export const rosResources: RosResourceSpec[] = [
{ id: "vrf", path: "/ip/vrf", title: "VRF", permission: "mm:network", fields: z.object({ name: name.optional(), interfaces: text.optional(), disabled: bool.optional(), comment: text.optional() }).strict(), create: true, remove: true, requiredOnCreate: ["name", "interfaces"] }, { id: "vrf", path: "/ip/vrf", title: "VRF", permission: "mm:network", fields: z.object({ name: name.optional(), interfaces: text.optional(), disabled: bool.optional(), comment: text.optional() }).strict(), create: true, remove: true, requiredOnCreate: ["name", "interfaces"] },
{ id: "ip_settings", path: "/ip/settings", title: "RPF и IPv4 hash-policy", permission: "mm:network", fields: z.object({ "rp-filter": z.enum(["no", "loose", "strict"]).optional(), "ipv4-multipath-hash-policy": z.enum(["l3", "l4", "l3-inner"]).optional() }).strict(), create: false, remove: false }, { id: "ip_settings", path: "/ip/settings", title: "RPF и IPv4 hash-policy", permission: "mm:network", fields: z.object({ "rp-filter": z.enum(["no", "loose", "strict"]).optional(), "ipv4-multipath-hash-policy": z.enum(["l3", "l4", "l3-inner"]).optional() }).strict(), create: false, remove: false },
{ id: "ipv6_settings", path: "/ipv6/settings", title: "IPv6 hash-policy", permission: "mm:network", fields: z.object({ "multipath-hash-policy": z.enum(["l3", "l4", "l3-inner"]).optional() }).strict(), create: false, remove: false }, { id: "ipv6_settings", path: "/ipv6/settings", title: "IPv6 hash-policy", permission: "mm:network", fields: z.object({ "multipath-hash-policy": z.enum(["l3", "l4", "l3-inner"]).optional() }).strict(), create: false, remove: false },
...(["ip", "ipv6"] as const).flatMap(family => (["filter", "nat", "mangle", "raw"] as const).map(table => ({ id: `${family}_${table}`, path: `/${family}/firewall/${table}`, title: `${family} firewall ${table}`, permission: "mm:network", fields: z.object(firewall).strict(), create: true, remove: true, requiredOnCreate: ["chain", "action"] }))), ...(["ip", "ipv6"] as const).flatMap(family => (["filter", "nat", "mangle", "raw"] as const).map(table => ({ id: `${family}_${table}`, path: `/${family}/firewall/${table}`, title: `${family} firewall ${table}`, permission: "mm:network", fields: z.object(family === "ip" && table === "mangle" ? ipv4Mangle : firewall).strict(), create: true, remove: true, requiredOnCreate: ["chain", "action"] }))),
{ id: "gre", path: "/interface/gre", title: "GRE", permission: "mm:network", fields: greNativeFieldsSchema, create: true, remove: true, requiredOnCreate: ["name", "remote-address"] }, { id: "gre", path: "/interface/gre", title: "GRE", permission: "mm:network", fields: greNativeFieldsSchema, create: true, remove: true, requiredOnCreate: ["name", "remote-address"] },
{ id: "wireguard", path: "/interface/wireguard", title: "WireGuard", permission: "mm:network", fields: z.object({ ...common, "listen-port": integer(1, 65535).optional(), mtu: integer(68, 65535).optional() }).strict(), create: true, remove: true, requiredOnCreate: ["name"] }, { id: "wireguard", path: "/interface/wireguard", title: "WireGuard", permission: "mm:network", fields: z.object({ ...common, "listen-port": integer(1, 65535).optional(), mtu: integer(68, 65535).optional() }).strict(), create: true, remove: true, requiredOnCreate: ["name"] },
{ id: "wireguard_peer", path: "/interface/wireguard/peers", title: "WireGuard peers", permission: "mm:network", fields: z.object({ interface: name.optional(), "public-key": name.optional(), "allowed-address": text.optional(), "endpoint-address": text.optional(), "endpoint-port": integer(0, 65535).optional(), "persistent-keepalive": text.optional(), disabled: bool.optional(), comment: text.optional() }).strict(), create: true, remove: true, requiredOnCreate: ["interface", "public-key", "allowed-address"] }, { id: "wireguard_peer", path: "/interface/wireguard/peers", title: "WireGuard peers", permission: "mm:network", fields: z.object({ interface: name.optional(), "public-key": name.optional(), "allowed-address": text.optional(), "endpoint-address": text.optional(), "endpoint-port": integer(0, 65535).optional(), "persistent-keepalive": text.optional(), disabled: bool.optional(), comment: text.optional() }).strict(), create: true, remove: true, requiredOnCreate: ["interface", "public-key", "allowed-address"] },
@@ -154,7 +165,7 @@ export function supportsRosPlacement(step: Pick<RosStep, "resource" | "action" |
export const ROS_SNAPSHOT_VERSION = 3 export const ROS_SNAPSHOT_VERSION = 3
// OSPF cost plans and archived inverses issued before prefix-list evidence cannot be reused. // OSPF cost plans and archived inverses issued before prefix-list evidence cannot be reused.
export const isSingletonRosResource = (resource: string) => ["ip_settings", "ipv6_settings", "ipv6_nd_settings"].includes(resource) export const isSingletonRosResource = (resource: string) => ["ip_settings", "ipv6_settings", "ipv6_nd_settings"].includes(resource)
export const rosSnapshotVersion = (resource: string): number => resource === "ospf_template" ? 10 : resource === "bfd_configuration" ? 7 : ["bridge", "bridge_port", "bridge_vlan", "routing_table", "ip_settings", "ipv6_settings", "ospf_instance", "ipv6_nd"].includes(resource) ? 4 : ROS_SNAPSHOT_VERSION export const rosSnapshotVersion = (resource: string): number => resource === "ospf_template" ? 10 : resource === "bfd_configuration" ? 7 : ["bridge", "bridge_port", "bridge_vlan", "routing_table", "ip_settings", "ipv6_settings", "ospf_instance", "ipv6_nd", "ip_mangle"].includes(resource) ? 4 : ROS_SNAPSHOT_VERSION
export interface RosSnapshot { serverId: number; resource: string; rows: ConfigurationRow[]; fingerprint: string; projectionVersion?: number; sourceProof?: string } export interface RosSnapshot { serverId: number; resource: string; rows: ConfigurationRow[]; fingerprint: string; projectionVersion?: number; sourceProof?: string }
const firewallAddressListResources = ["ip_address_list", "ipv6_address_list"] const firewallAddressListResources = ["ip_address_list", "ipv6_address_list"]
const routingPolicyResources = new Set(["routing_rule", "routing_filter", "routing_filter_select", "bfd_configuration", ...firewallAddressListResources, "ip_filter", "ip_nat", "ip_mangle", "ip_raw", "ipv6_filter", "ipv6_nat", "ipv6_mangle", "ipv6_raw"]) const routingPolicyResources = new Set(["routing_rule", "routing_filter", "routing_filter_select", "bfd_configuration", ...firewallAddressListResources, "ip_filter", "ip_nat", "ip_mangle", "ip_raw", "ipv6_filter", "ipv6_nat", "ipv6_mangle", "ipv6_raw"])
@@ -1,5 +1,5 @@
import assert from "node:assert/strict" import assert from "node:assert/strict"
import { configurationRows, isOrderedRosResource, resourceById, rosSnapshotVersion, splitOspfUnsetUpdate, type ConfigurationRow, type RosSnapshot, type RosStep } from "./resources.js" import { configurationRows, isOrderedRosResource, resourceById, rosSnapshotVersion, splitOspfUnsetUpdate, validateRosStep, type ConfigurationRow, type RosSnapshot, type RosStep } from "./resources.js"
import { fingerprint } from "./security.js" import { fingerprint } from "./security.js"
import { proveRosDriftExpectation, verifyRosStepSnapshots } from "./ros-step-verification.js" import { proveRosDriftExpectation, verifyRosStepSnapshots } from "./ros-step-verification.js"
import { readOspfTemplateFlags } from "../../services/ospf-template-flags.js" import { readOspfTemplateFlags } from "../../services/ospf-template-flags.js"
@@ -24,6 +24,26 @@ assert.equal(check(create, ack, [a, b], [a, b, { ...c, action: "drop" }]), false
assert.equal(check(create, undefined, [a], [a, c]), false, "Observed object never substitutes a lost acknowledgement") assert.equal(check(create, undefined, [a], [a, c]), false, "Observed object never substitutes a lost acknowledgement")
assert.equal(check({ ...create, id: "*A" }, ack, [a], [a, c]), false) assert.equal(check({ ...create, id: "*A" }, ack, [a], [a, c]), false)
const mangle = resourceById("ip_mangle")
const mssFields = {
chain: "forward", "out-interface": "gre-ix", "dst-address": "192.0.2.2/32", protocol: "tcp",
"tcp-flags": "syn,ack", "tcp-mss": "1381-65535", action: "change-mss", "new-mss": 1380, passthrough: true,
}
const mss = { ...create, resource: mangle.id, fields: validateRosStep(mangle, "create", mssFields) }
const liveMss = { ...mss.fields, ".id": "*C", "dst-address": "192.0.2.2", "tcp-flags": "ack,syn", passthrough: "yes", packets: "3" }
const mangleRows = (rows: ConfigurationRow[]) => configurationRows(mangle, rows)
assert.equal(check(mss, ack, [], mangleRows([liveMss])), true)
assert.equal(check(mss, ack, [], mangleRows([{ ...liveMss, "new-mss": "1460" }])), false)
assert.equal(check(mss, ack, [], mangleRows([{ ...liveMss, "dst-address": "192.0.2.2/24" }])), false)
assert.equal(check(mss, ack, [], mangleRows([{ ...liveMss, "tcp-flags": "syn,!ack" }])), false)
const mssUpdate = { ...mss, action: "update" as const, id: "*C", fields: validateRosStep(mangle, "update", { "new-mss": 1360 }, "*C") }
assert.equal(check(mssUpdate, {}, mangleRows([liveMss]), mangleRows([{ ...liveMss, "new-mss": "1360" }])), true)
assert.equal(check(mssUpdate, {}, mangleRows([liveMss]), mangleRows([{ ...liveMss, "new-mss": "1360", "tcp-mss": "1361-65535" }])), false)
for (const bad of [{ "new-mss": 65536 }, { "tcp-mss": "1400-1300" }, { "tcp-mss": "1-65536" }, { "tcp-flags": "syn,!syn" }, { passthrough: "yes" }]) {
assert.throws(() => validateRosStep(mangle, "create", { ...mssFields, ...bad }))
}
assert.equal(resourceById("ip_filter").fields.safeParse(mssFields).success, false)
const update: RosStep = { ...create, action: "update", id: "*A", fields: { action: "accept" } } const update: RosStep = { ...create, action: "update", id: "*A", fields: { action: "accept" } }
const updated = { ...a, action: "accept" } const updated = { ...a, action: "accept" }
assert.equal(check(update, {}, [a, b], [updated, b]), true) assert.equal(check(update, {}, [a, b], [updated, b]), true)
@@ -29,6 +29,10 @@ function requested(resource: RosResourceSpec, fields: RosStep["fields"], row: Co
if (resource.id === "bridge_vlan" && ["vlan-ids", "tagged", "untagged"].includes(key)) { if (resource.id === "bridge_vlan" && ["vlan-ids", "tagged", "untagged"].includes(key)) {
try { return canonicalBridgeVlanValue(key, row[key]) === canonicalBridgeVlanValue(key, value) } catch { return false } try { return canonicalBridgeVlanValue(key, row[key]) === canonicalBridgeVlanValue(key, value) } catch { return false }
} }
if (resource.id === "ip_mangle") {
if (key === "dst-address" || key === "src-address") return String(row[key]).replace(/\/32$/, "") === value.replace(/\/32$/, "")
if (key === "tcp-flags" && schema.safeParse(row[key]).success) return String(row[key]).split(",").sort().join(",") === value.split(",").sort().join(",")
}
return String(row[key]) === value return String(row[key]) === value
}) })
} }
@@ -1,9 +1,8 @@
import { fingerprint, accessGeneration, McpError } from "./security.js" import { fingerprint, accessGeneration, McpError } from "./security.js"
import { pool } from "../../db/index.js" import { pool } from "../../db/index.js"
import { wireguardExportRequestSchema } from "../../services/wireguard-export.js"
import { effectiveMcpConnection } from "./store.js" import { effectiveMcpConnection } from "./store.js"
import { registerMcpService } from "./service-registry.js" import { registerMcpService } from "./service-registry.js"
import { wireguardExportAuthority, wireguardExportAuthoritySchema, createWireguardExportArtifact, readWireguardExportSource, verifyWireguardExportArtifact } from "./wireguard-export-artifact.js" import { wireguardExportAuthority, wireguardExportAuthoritySchema, createWireguardExportArtifact, mcpWireguardExportRequestSchema, readWireguardExportSource, verifyWireguardExportArtifact } from "./wireguard-export-artifact.js"
import type { add } from "./actions.js" import type { add } from "./actions.js"
export function registerWireguardExportActions(register: typeof add) { export function registerWireguardExportActions(register: typeof add) {
@@ -16,10 +15,10 @@ export function registerWireguardExportActions(register: typeof add) {
return receipt?.humanDownloadOnly===true && receipt.wireguardContentReturned===false && !!receipt.artifactId && await verifyWireguardExportArtifact(receipt.artifactId,authority(input),String(input.expectedProof)) return receipt?.humanDownloadOnly===true && receipt.wireguardContentReturned===false && !!receipt.artifactId && await verifyWireguardExportArtifact(receipt.artifactId,authority(input),String(input.expectedProof))
}, },
}) })
register("network.wireguard.export","mm_wireguard_export_plan","Подготовить WireGuard экспорт для скачивания владельцем после человеческого подтверждения","network","mm:network:write","write","servers",wireguardExportRequestSchema,{ register("network.wireguard.export","mm_wireguard_export_plan","Подготовить WireGuard экспорт или готовый .conf для Linux-клиента IX","network","mm:network:write","write","servers",mcpWireguardExportRequestSchema,{
target:input=>({scope:"servers",serverIds:[wireguardExportRequestSchema.parse(input).serverId]}), target:input=>({scope:"servers",serverIds:[mcpWireguardExportRequestSchema.parse(input).serverId]}),
prepare:async(input,context)=>{ prepare:async(input,context)=>{
const request=wireguardExportRequestSchema.parse(input) const request=mcpWireguardExportRequestSchema.parse(input)
const authorize=async()=>{ const authorize=async()=>{
if(context.signal?.aborted)throw new McpError("READ_CANCELLED","Экспорт WireGuard отменён",409) if(context.signal?.aborted)throw new McpError("READ_CANCELLED","Экспорт WireGuard отменён",409)
const fresh=await effectiveMcpConnection(context.principal) const fresh=await effectiveMcpConnection(context.principal)
@@ -33,7 +32,10 @@ export function registerWireguardExportActions(register: typeof add) {
await authorize() await authorize()
return {target:{scope:"servers",serverIds:[request.serverId]},objects:[{kind:"server",id:String(request.serverId),serverId:request.serverId},{kind:"wireguard-export",id:request.interfaceName,serverId:request.serverId},...protections.map(row=>row.object_ref)],snapshots:[],before:{proof:source.proof},requiresHuman:true,mutationCost:1, return {target:{scope:"servers",serverIds:[request.serverId]},objects:[{kind:"server",id:String(request.serverId),serverId:request.serverId},{kind:"wireguard-export",id:request.interfaceName,serverId:request.serverId},...protections.map(row=>row.object_ref)],snapshots:[],before:{proof:source.proof},requiresHuman:true,mutationCost:1,
steps:[{kind:"service",service:"network.wireguard.export",input:{authority:access,expectedProof:source.proof,beforeFingerprint:fingerprint({proof:source.proof})}}], steps:[{kind:"service",service:"network.wireguard.export",input:{authority:access,expectedProof:source.proof,beforeFingerprint:fingerprint({proof:source.proof})}}],
warnings:[request.includePrivateKey && request.format!=="peer-conf" ? "Этот пакет включает приватный ключ интерфейса WireGuard. Скачивание разрешено только вошедшему владельцу на 15 минут." : "Приватные ключи в этот пакет не включаются. Файл доступен только вошедшему владельцу на 15 минут.","Модель получает только квитанцию и ссылку; содержимое, native ключи и комментарии в MCP не возвращаются. Предел файла — 1 МиБ, чтения — 45 секунд.","Изменение источника, прав, подключений или защит блокирует выдачу. Формат conf не воспроизводит отключённые интерфейсы/пиры; peer-conf не раскрывает ключи клиента.",request.format==="conf"?"Формат conf переносит параметры туннеля; имя интерфейса, имена пиров и клиентские подсказки RouterOS в нём не восстанавливаются.":request.format==="peer-conf"?"peer-conf — шаблон клиента: приватный ключ и AllowedIPs заполняются человеком; готовность клиентского подключения не подтверждается.":"RSC сохраняет поддержанные native поля и отключённые состояния; фактический путь проверяется отдельно."]} warnings: request.ixSegmentId ? [
"Готовый конфиг IX содержит приватный ключ Linux-клиента. Скачивание доступно вошедшему владельцу на 15 минут.",
"MCP возвращает только квитанцию и ссылку. Изменение применённой ревизии, прав или защит блокирует выдачу.",
] : [request.includePrivateKey && request.format!=="peer-conf" ? "Этот пакет включает приватный ключ интерфейса WireGuard. Скачивание разрешено только вошедшему владельцу на 15 минут." : "Приватные ключи в этот пакет не включаются. Файл доступен только вошедшему владельцу на 15 минут.","Модель получает только квитанцию и ссылку; содержимое, native ключи и комментарии в MCP не возвращаются. Предел файла — 1 МиБ, чтения — 45 секунд.","Изменение источника, прав, подключений или защит блокирует выдачу. Формат conf не воспроизводит отключённые интерфейсы/пиры; peer-conf не раскрывает ключи клиента.",request.format==="conf"?"Формат conf переносит параметры туннеля; имя интерфейса, имена пиров и клиентские подсказки RouterOS в нём не восстанавливаются.":request.format==="peer-conf"?"peer-conf — шаблон клиента: приватный ключ и AllowedIPs заполняются человеком; готовность клиентского подключения не подтверждается.":"RSC сохраняет поддержанные native поля и отключённые состояния; фактический путь проверяется отдельно."]}
}, },
}) })
} }
@@ -4,6 +4,9 @@ import type { PoolClient } from "pg"
import { pool } from "../../db/index.js" import { pool } from "../../db/index.js"
import { hasPermission, type AuthUser } from "../../lib/permissions.js" import { hasPermission, type AuthUser } from "../../lib/permissions.js"
import { readWireguardExport, wireguardExportRequestSchema } from "../../services/wireguard-export.js" import { readWireguardExport, wireguardExportRequestSchema } from "../../services/wireguard-export.js"
import { readIxLinuxClient } from "../../services/internet-exchange-execution.js"
import { IxConflict } from "../../services/internet-exchange-plan.js"
import { readIxSegment } from "../../services/internet-exchange-store.js"
import { assertVerifiedConfigurationAccess, executeGuardedApplicationWrite } from "../../services/config-mutation-policy.js" import { assertVerifiedConfigurationAccess, executeGuardedApplicationWrite } from "../../services/config-mutation-policy.js"
import { assertLogArtifactBudget } from "./log-artifacts.js" import { assertLogArtifactBudget } from "./log-artifacts.js"
import { assertPortalClaimsCurrent } from "./portal-revocation.js" import { assertPortalClaimsCurrent } from "./portal-revocation.js"
@@ -13,7 +16,11 @@ import { accessGeneration, decryptSecret, encryptSecret, fingerprint, McpError,
const MAX_BYTES = 1048576, MAX_CIPHER = 2 * 1048576 const MAX_BYTES = 1048576, MAX_CIPHER = 2 * 1048576
const digest = z.string().regex(/^[a-f0-9]{64}$/) const digest = z.string().regex(/^[a-f0-9]{64}$/)
const principalSchema = z.object({ connectionId: z.string().uuid(), credentialId: z.string().uuid(), credentialExpiresAt: z.iso.datetime() }).strict() const principalSchema = z.object({ connectionId: z.string().uuid(), credentialId: z.string().uuid(), credentialExpiresAt: z.iso.datetime() }).strict()
export const wireguardExportAuthoritySchema = z.object({ principal: principalSchema, ownerId: z.string().min(1).max(200), policyProof: digest, generation: digest, request: wireguardExportRequestSchema }).strict() export const mcpWireguardExportRequestSchema = wireguardExportRequestSchema.extend({
ixSegmentId: z.string().uuid().optional().describe("Для готового конфига Linux из IX укажите ID сегмента и формат peer-conf"),
}).refine(request => !request.ixSegmentId || request.format === "peer-conf" && !request.peerId && !request.includePrivateKey,
"Для клиента IX укажите peer-conf и имя интерфейса клиента. Его управляемый ключ будет включён в файл.")
export const wireguardExportAuthoritySchema = z.object({ principal: principalSchema, ownerId: z.string().min(1).max(200), policyProof: digest, generation: digest, request: mcpWireguardExportRequestSchema }).strict()
export type WireguardExportAuthority = z.infer<typeof wireguardExportAuthoritySchema> export type WireguardExportAuthority = z.infer<typeof wireguardExportAuthoritySchema>
const scopeSchema = z.object({ version: z.literal(1), kind: z.literal("wireguard-export"), authority: wireguardExportAuthoritySchema, sourceProof: digest, const scopeSchema = z.object({ version: z.literal(1), kind: z.literal("wireguard-export"), authority: wireguardExportAuthoritySchema, sourceProof: digest,
bytes: z.number().int().min(0).max(MAX_BYTES), sha256: digest, encryptedSha256: digest, proof: digest }).strict() bytes: z.number().int().min(0).max(MAX_BYTES), sha256: digest, encryptedSha256: digest, proof: digest }).strict()
@@ -41,10 +48,25 @@ async function protectionProof(authority: WireguardExportAuthority, client: Pick
export async function readWireguardExportSource(authority: WireguardExportAuthority, authorize: () => Promise<unknown> = async()=>{}, signal?: AbortSignal) { export async function readWireguardExportSource(authority: WireguardExportAuthority, authorize: () => Promise<unknown> = async()=>{}, signal?: AbortSignal) {
await authorize(); await assertWireguardExportAccess(authority) await authorize(); await assertWireguardExportAccess(authority)
const protections=await protectionProof(authority) const protections=await protectionProof(authority)
const source=await readWireguardExport(authority.request, { signal, authorize: async()=>{ const check = async () => {
signal?.throwIfAborted()
await authorize(); await assertWireguardExportAccess(authority) await authorize(); await assertWireguardExportAccess(authority)
if (await protectionProof(authority)!==protections) throw fail("Защиты экспорта изменились", "STATE_CONFLICT") if (await protectionProof(authority)!==protections) throw fail("Защиты экспорта изменились", "STATE_CONFLICT")
} }) }
const { ixSegmentId, ...request } = authority.request
if (ixSegmentId) {
await check()
const segment = await readIxSegment(ixSegmentId)
if (!segment) throw new McpError("NOT_FOUND", "Сегмент IX не найден", 404)
const access = await readIxLinuxClient(segment, request.serverId, request.interfaceName, "wireguard").catch(error => {
if (error instanceof IxConflict) throw new McpError(error.statusCode === 404 ? "NOT_FOUND" : "STATE_CONFLICT", error.message, error.statusCode)
throw error
})
await check()
const proof = await sign({ protections, ixSegmentId, request, access })
return { filename: access.filename, content: Buffer.from(access.template), protectionProof: protections, proof }
}
const source=await readWireguardExport(request, { signal, authorize: check })
return {...source,protectionProof:protections,proof:await sign({nativeSource:source.proof,protections})} return {...source,protectionProof:protections,proof:await sign({nativeSource:source.proof,protections})}
} }
+2 -1
View File
@@ -276,7 +276,8 @@ export async function requireAuth(
/** Gate the matched route, including encoded static segments in the raw URL. */ /** Gate the matched route, including encoded static segments in the raw URL. */
export async function requireApiAuth(request: FastifyRequest, reply: FastifyReply): Promise<void> { export async function requireApiAuth(request: FastifyRequest, reply: FastifyReply): Promise<void> {
const pathname = request.routeOptions.url ?? request.url.split("?")[0] ?? request.url const pathname = request.routeOptions.url ?? request.url.split("?")[0] ?? request.url
if (!pathname.startsWith("/api/") || pathname === "/api/auth/config") return if (!pathname.startsWith("/api/") || pathname === "/api/auth/config" ||
request.method === "POST" && pathname === "/api/ix/import") return
await requireAuth(request, reply) await requireAuth(request, reply)
} }
+1 -1
View File
@@ -23,7 +23,7 @@ export function installDatabaseRequestGate(app: FastifyInstance, admit = withDat
const run = async () => withConfigurationActor(request.authUser?.id ?? "system", async () => await original.call(this, request, reply)) const run = async () => withConfigurationActor(request.authUser?.id ?? "system", async () => await original.call(this, request, reply))
// The service owns exclusivity, including calls that do not originate in HTTP. // The service owns exclusivity, including calls that do not originate in HTTP.
if (operation) return run() if (operation) return run()
if (!stream) return gate.request(() => admit(run)) if (!stream) return gate.request(() => admit(run, !["GET", "HEAD", "OPTIONS"].includes(request.method)))
const state = { cancelled: false, abort: undefined as (() => void) | undefined } const state = { cancelled: false, abort: undefined as (() => void) | undefined }
streams.set(request, state) streams.set(request, state)
try { try {
+22 -12
View File
@@ -1,3 +1,4 @@
import { coalesceCatalogReads, observationIsCurrent, readCatalogWithObservedCache, withCatalogWriteLock } from "../services/routing-catalog-observation.js"
import { and, asc, eq, inArray } from "drizzle-orm" import { and, asc, eq, inArray } from "drizzle-orm"
import { z } from "zod" import { z } from "zod"
import type { FastifyPluginAsyncZod } from "@fastify/type-provider-zod" import type { FastifyPluginAsyncZod } from "@fastify/type-provider-zod"
@@ -8,7 +9,6 @@ import { pollGreCatalog } from "../services/gre-catalog-poll.js"
import { parseKeepalive } from "../services/gre-live.js" import { parseKeepalive } from "../services/gre-live.js"
import { parseDbServerId } from "../utils/server-id.js" import { parseDbServerId } from "../utils/server-id.js"
import { observeBgpFilterRules } from "../services/filter-rules-observed.js" import { observeBgpFilterRules } from "../services/filter-rules-observed.js"
import { withApplicationMutationLock, withConfigMutationLock } from "../services/config-mutation-lock.js"
import { appendEvent } from "../modules/events/service/events-service.js" import { appendEvent } from "../modules/events/service/events-service.js"
import { managedComment, hasManagedCommentPrefix } from "../managed-markers.js" import { managedComment, hasManagedCommentPrefix } from "../managed-markers.js"
import { compileManagedFilterRules, filterRuleBranches, filterRuleDescriptions, filterRuleToken, validatedFilterRules } from "../services/filter-rules-write-model.js" import { compileManagedFilterRules, filterRuleBranches, filterRuleDescriptions, filterRuleToken, validatedFilterRules } from "../services/filter-rules-write-model.js"
@@ -282,6 +282,8 @@ export async function fetchServerFilters(server: ServerRow) {
} }
} }
const readWebFilters = coalesceCatalogReads(fetchServerFilters)
async function toApiRulesets(serverRows: ServerRow[]) { async function toApiRulesets(serverRows: ServerRow[]) {
const dbRules = serverRows.length ? await db.select().from(filterRules).where(inArray(filterRules.serverId, serverRows.map(server => server.id))).orderBy(asc(filterRules.serverId), asc(filterRules.sortOrder), asc(filterRules.id)) : [] const dbRules = serverRows.length ? await db.select().from(filterRules).where(inArray(filterRules.serverId, serverRows.map(server => server.id))).orderBy(asc(filterRules.serverId), asc(filterRules.sortOrder), asc(filterRules.id)) : []
return serverRows.map(s => ({ return serverRows.map(s => ({
@@ -381,20 +383,26 @@ export async function readFilterRulesCatalog(selected: ServerRow[], options: { s
const rulesets = await toApiRulesets(selected) const rulesets = await toApiRulesets(selected)
return rulesets.map(ruleset => ({ ...ruleset, greTunnels: [] as LiveGreTunnel[], nativeRules: null as ReturnType<typeof observeBgpFilterRules> | null, live: false, stale: false, source: "cache" as const, error: null as string | null })) return rulesets.map(ruleset => ({ ...ruleset, greTunnels: [] as LiveGreTunnel[], nativeRules: null as ReturnType<typeof observeBgpFilterRules> | null, live: false, stale: false, source: "cache" as const, error: null as string | null }))
} }
const readSelected = () => Promise.all(selected.map(async server => { return Promise.all(selected.map(async server => {
try { try {
const remote = await fetchServerFilters(server) const read = async (fresh: boolean) => {
if (options.persistObserved) { const remote = await (fresh || !options.persistObserved ? fetchServerFilters : readWebFilters)(server)
if (!options.persistObserved) return { remote, rules: remote.rules, current: true }
const rules = await cacheRulesetsForServer(server.id)
const current = await observationIsCurrent(server.id, "filters", canonicalFilterRules(remote.rules), canonicalFilterRules(rules))
return { remote, rules, current }
}
const { remote, rules } = await readCatalogWithObservedCache(server, read, async ({ remote }) => {
await replaceDbRules(server.id, remote.rules) await replaceDbRules(server.id, remote.rules)
await appendRevisionIfChanged({ serverId: server.id, section: "filters", source: "observed", payload: canonicalFilterRules(remote.rules) }) await appendRevisionIfChanged({ serverId: server.id, section: "filters", source: "observed", payload: canonicalFilterRules(remote.rules) })
} return { remote, rules: await cacheRulesetsForServer(server.id), current: true }
return { serverId: String(server.id), rules: options.persistObserved ? await cacheRulesetsForServer(server.id) : remote.rules, greTunnels: remote.tunnels, nativeRules: remote.nativeRules, live: true, stale: false, source: "device" as const, error: null as string | null } })
} catch { return { serverId: String(server.id), rules, greTunnels: remote.tunnels, nativeRules: remote.nativeRules, live: true, stale: false, source: "device" as const, error: null as string | null }
} catch (error) {
if (error instanceof McpError && error.statusCode === 409) throw error
return { serverId: String(server.id), rules: await cacheRulesetsForServer(server.id), greTunnels: [] as LiveGreTunnel[], nativeRules: null, live: false, stale: true, source: "cache" as const, error: server.enabled ? "Не подтверждено чтение фильтров выбранного сервера" : "Сервер выключен. Опрос фильтров недоступен." } return { serverId: String(server.id), rules: await cacheRulesetsForServer(server.id), greTunnels: [] as LiveGreTunnel[], nativeRules: null, live: false, stale: true, source: "cache" as const, error: server.enabled ? "Не подтверждено чтение фильтров выбранного сервера" : "Сервер выключен. Опрос фильтров недоступен." }
} }
})) }))
return options.persistObserved
? withApplicationMutationLock(() => withConfigMutationLock(selected.map(server => server.id), readSelected)) : readSelected()
} }
export async function applyFiltersToServer( export async function applyFiltersToServer(
@@ -406,7 +414,7 @@ export async function applyFiltersToServer(
if (!server.enabled) throw new McpError("DEVICE_UNAVAILABLE", "Сервер выключен; изменение фильтров запрещено", 409) if (!server.enabled) throw new McpError("DEVICE_UNAVAILABLE", "Сервер выключен; изменение фильтров запрещено", 409)
if (options.managedRuleComment !== undefined && !hasManagedCommentPrefix(options.managedRuleComment)) throw new McpError("PROTECTED_OBJECT", "Сохранённый comment фильтра не принадлежит приложению", 409) if (options.managedRuleComment !== undefined && !hasManagedCommentPrefix(options.managedRuleComment)) throw new McpError("PROTECTED_OBJECT", "Сохранённый comment фильтра не принадлежит приложению", 409)
rules = validatedFilterRules(rules) rules = validatedFilterRules(rules)
return executeGuardedApplicationWrite({ kind: "filters", id: "managed-bgp-in" }, [server.id], () => withConfigMutationLock([server.id], async () => { return withCatalogWriteLock(server, "filters", () => executeGuardedApplicationWrite({ kind: "filters", id: "managed-bgp-in" }, [server.id], async () => {
const client = MikrotikClient.fromServer(server) const client = MikrotikClient.fromServer(server)
const interfaces = rules.some(rule => rule.action !== "blackhole" && rule.gatewayTunnelId && !rule.gatewayTunnelId.startsWith("rec:")) ? nativeBgpRows(await client.get("/interface/gre")) : [] const interfaces = rules.some(rule => rule.action !== "blackhole" && rule.gatewayTunnelId && !rule.gatewayTunnelId.startsWith("rec:")) ? nativeBgpRows(await client.get("/interface/gre")) : []
const ruleBody = await toRouterRuleBody(server.id, rules, interfaces) const ruleBody = await toRouterRuleBody(server.id, rules, interfaces)
@@ -442,7 +450,7 @@ const filtersRoutes: FastifyPluginAsyncZod = async (app) => {
const server = enabledServers.find(s => s.id === sid) const server = enabledServers.find(s => s.id === sid)
if (!server) return reply.status(404).send({ error: "Server not found" }) if (!server) return reply.status(404).send({ error: "Server not found" })
try { try {
const remote = await fetchServerFilters(server) const remote = await readWebFilters(server)
return reply.send({ tunnels: remote.tunnels }) return reply.send({ tunnels: remote.tunnels })
} catch (error) { } catch (error) {
app.log.warn({ serverId: sid, err: String(error) }, "filters GRE catalog unavailable") app.log.warn({ serverId: sid, err: String(error) }, "filters GRE catalog unavailable")
@@ -450,7 +458,7 @@ const filtersRoutes: FastifyPluginAsyncZod = async (app) => {
} }
} }
return reply.send(await pollGreCatalog(enabledServers, fetchServerFilters)) return reply.send(await pollGreCatalog(enabledServers, readWebFilters))
}) })
/** Без serverId — cache для дашборда. С serverId — live с CHR, cache fallback. */ /** Без serverId — cache для дашборда. С serverId — live с CHR, cache fallback. */
@@ -523,6 +531,7 @@ const filtersRoutes: FastifyPluginAsyncZod = async (app) => {
rules: cached, rules: cached,
}) })
} catch (err) { } catch (err) {
if (err instanceof McpError && err.statusCode === 409) throw err
app.log.error({ serverId, err: String(err) }, "filters apply failed") app.log.error({ serverId, err: String(err) }, "filters apply failed")
await appendEvent({ await appendEvent({
level: "critical", level: "critical",
@@ -588,6 +597,7 @@ const filtersRoutes: FastifyPluginAsyncZod = async (app) => {
}) })
return reply.send({ ok: true, rules: cached, pushedRules: result.pushed }) return reply.send({ ok: true, rules: cached, pushedRules: result.pushed })
} catch (err) { } catch (err) {
if (err instanceof McpError) throw err
app.log.error({ serverId: server.id, err: String(err) }, "filters restore failed") app.log.error({ serverId: server.id, err: String(err) }, "filters restore failed")
return reply.status(500).send({ error: String(err) }) return reply.status(500).send({ error: String(err) })
} }
+101 -11
View File
@@ -1,16 +1,19 @@
import { randomUUID } from "node:crypto" import { randomUUID } from "node:crypto"
import type { FastifyPluginAsync } from "fastify" import type { FastifyPluginAsync } from "fastify"
import { z } from "zod" import { z } from "zod"
import { ixChangeSchema, ixLinuxClientRequest, ixTransitRequest, type IxWebPlan } from "@mmapp/contracts/internet-exchange" import { ixBondEditSchema, ixChangeSchema, ixLinuxClientRequest, ixTransitRequest, type IxWebPlan } from "@mmapp/contracts/internet-exchange"
import { fingerprint, McpError } from "../modules/mcp/security.js" import { fingerprint, McpError } from "../modules/mcp/security.js"
import { audit } from "../modules/mcp/store.js" import { audit } from "../modules/mcp/store.js"
import { pool } from "../db/index.js" import { pool } from "../db/index.js"
import { captureVerifiedRestRequest, inspectVerifiedRestRequest, RestRequestProvenanceError } from "../plugins/auth.js" import { captureVerifiedRestRequest, inspectVerifiedRestRequest, RestRequestProvenanceError, type VerifiedRestRequestAuthority } from "../plugins/auth.js"
import { withApplicationMutationLock } from "../services/config-mutation-lock.js" import { assertPortalClaimsCurrent } from "../modules/mcp/portal-revocation.js"
import { createIxImportLinks } from "../services/ix-import-links.js"
import { withApplicationCollectorLock, withApplicationMutationLock } from "../services/config-mutation-lock.js"
import { withConfigurationActor } from "../services/config-mutation-policy.js" import { withConfigurationActor } from "../services/config-mutation-policy.js"
import { applyIxChange, assignIxRouterIds, configureIxLinuxClient, configureIxTransit, listIxLinuxClients, observeIxLinuxPath, observeIxSegment, prepareIxChange, prepareIxRemoval, readIxLinuxClient, readIxNodeInventory, removeIxSegment } from "../services/internet-exchange-execution.js" import { applyIxChange, assignIxRouterIds, configureIxLinuxClient, configureIxTransit, listIxLinuxClients, observeIxLinuxPath, observeIxSegment, prepareIxChange, prepareIxRemoval, readIxLinuxClient, readIxNodeInventory, removeIxSegment } from "../services/internet-exchange-execution.js"
import { compileIxConfiguration, IxConflict } from "../services/internet-exchange-plan.js" import { compileIxConfiguration, IxConflict } from "../services/internet-exchange-plan.js"
import { assertIxRevision, listIxSegments, readIxSegment, writeIxRevision } from "../services/internet-exchange-store.js" import { assertIxRevision, listIxSegments, readIxSegment, writeIxRevision } from "../services/internet-exchange-store.js"
import { changeIxBond, exportIxBond, inspectIxBondImports, ixBondCatalog } from "../services/internet-exchange-bonds.js"
const paging = z.object({ const paging = z.object({
limit: z.coerce.number().int().min(1).max(100).default(25), limit: z.coerce.number().int().min(1).max(100).default(25),
@@ -48,11 +51,27 @@ function summarizeTasks(tasks: Awaited<ReturnType<typeof prepareIxChange>>["nati
})) }))
} }
const importLinkLifetime = 5 * 60_000
function importLinkOwner(authority: VerifiedRestRequestAuthority) {
const { ownerId, issuedAt, authentication, expiresAt } = authority
return async () => {
if (Date.now() >= expiresAt) throw new IxConflict("Ссылка истекла", 410)
if (authentication === "jwt") await assertPortalClaimsCurrent({ id: ownerId, issuedAt })
}
}
const ixRoutes: FastifyPluginAsync = async app => { const ixRoutes: FastifyPluginAsync = async app => {
const links = createIxImportLinks()
app.post("/ix/import", { bodyLimit: 256 }, async (request, reply) => {
reply.header("Cache-Control", "private, no-store")
const { code } = z.object({ code: z.string().regex(/^[A-Za-z0-9_-]{32}$/) }).strict().parse(request.body)
return links.redeem(code)
})
app.setErrorHandler((error, request, reply) => { app.setErrorHandler((error, request, reply) => {
if (error instanceof z.ZodError) return reply.code(400).send({ error: "Некорректные параметры IX", details: error.issues }) if (error instanceof z.ZodError) return reply.code(400).send({ error: "Некорректные параметры IX", details: error.issues })
if (error instanceof IxConflict) return reply.code(error.statusCode).send({ error: error.message }) if (error instanceof IxConflict) return reply.code(error.statusCode).send({ error: error.message })
if (error instanceof McpError) return reply.code(error.statusCode).send({ error: error.message }) if (error instanceof McpError) return reply.code(error.statusCode).send({ error: error.message, code: error.code })
if (error instanceof RestRequestProvenanceError) return reply.code(403).send({ error: "Нет действующего права изменения IX" }) if (error instanceof RestRequestProvenanceError) return reply.code(403).send({ error: "Нет действующего права изменения IX" })
request.log.error({ error: error instanceof Error ? error.name : "unknown" }, "IX request failed") request.log.error({ error: error instanceof Error ? error.name : "unknown" }, "IX request failed")
const errorMessage = request.method === "DELETE" ? "Удаление сегмента IX не подтверждено. Обновите данные и проверьте план." const errorMessage = request.method === "DELETE" ? "Удаление сегмента IX не подтверждено. Обновите данные и проверьте план."
@@ -65,6 +84,48 @@ const ixRoutes: FastifyPluginAsync = async app => {
const input = paging.parse(request.query) const input = paging.parse(request.query)
return { items: await listIxSegments(input.limit, input.offset) } return { items: await listIxSegments(input.limit, input.offset) }
}) })
app.get("/ix/linux-bonds", async () => ixBondCatalog())
app.post("/ix/segments/:id/linux-bonds", async request => {
const { id } = segmentParams.parse(request.params)
const edit = ixBondEditSchema.parse(request.body)
await inspectIxBondImports(id, edit)
return withApplicationMutationLock(() => changeIxBond(id, edit, request.authUser?.id ?? "local-operator"), { waitMs: 5000 })
})
app.delete("/ix/segments/:id/linux-bonds/:bondId", async (request, reply) => {
const { id, bondId } = segmentParams.extend({ bondId: z.uuid() }).parse(request.params)
const { revision } = planRequest.parse(request.body)
await withApplicationMutationLock(() => changeIxBond(id, { id: bondId, revision }, request.authUser?.id ?? "local-operator"), { waitMs: 5000 })
return reply.code(204).send()
})
app.post("/ix/segments/:id/linux-bonds/:bondId/export", async (request, reply) => {
const { id, bondId } = segmentParams.extend({ bondId: z.uuid() }).parse(request.params)
const { revision, importLink } = planRequest.extend({ importLink: z.boolean().optional() }).parse(request.body)
const scope = { deadlineAt: Date.now() + (importLink ? importLinkLifetime : 90_000) }
const token = await captureVerifiedRestRequest(request, scope)
const authorize = () => inspectVerifiedRestRequest(token, scope, "mm:network:write")
const authority = await authorize()
const { ownerId } = authority
if (importLink) {
const authorizeOwner = importLinkOwner(authority)
await audit(pool, ownerId, "ix.bond.import_link_issued", null, { segmentId: id, bondId, revision })
await authorize()
reply.header("Cache-Control", "private, no-store")
return { code: links.issue(authority.monotonicDeadline, () => withApplicationCollectorLock(async () => {
await authorizeOwner()
const bond = await exportIxBond(id, bondId, revision, authorizeOwner)
await audit(pool, ownerId, "ix.bond.exported", null, { segmentId: id, bondId, revision })
await authorizeOwner()
return { version: 1, kind: "bond", bond }
})) }
}
return withApplicationCollectorLock(async () => {
const bundle = await exportIxBond(id, bondId, revision, authorize)
await audit(pool, ownerId, "ix.bond.exported", null, { segmentId: id, bondId, revision })
await authorize()
reply.header("Cache-Control", "no-store")
return bundle
})
})
app.get("/ix/nodes", async () => { app.get("/ix/nodes", async () => {
const [nodes, peers] = await Promise.all([ const [nodes, peers] = await Promise.all([
pool.query("SELECT id,name,site,country,enabled FROM servers WHERE type='ix-node' ORDER BY name,id LIMIT 500"), pool.query("SELECT id,name,site,country,enabled FROM servers WHERE type='ix-node' ORDER BY name,id LIMIT 500"),
@@ -96,12 +157,12 @@ const ixRoutes: FastifyPluginAsync = async app => {
app.get("/ix/segments/:id/linux", async request => { app.get("/ix/segments/:id/linux", async request => {
const { id } = z.object({ id: z.string().uuid() }).parse(request.params) const { id } = z.object({ id: z.string().uuid() }).parse(request.params)
const query = z.union([ const query = z.union([
z.object({ serverId: z.coerce.number().positive().int().safe(), interfaceName: z.string().regex(/^[A-Za-z0-9_.-]{1,48}$/) }).strict(), z.object({ serverId: z.coerce.number().positive().int().safe(), interfaceName: z.string().regex(/^[A-Za-z0-9_.-]{1,48}$/), transportOnly: z.literal("true").optional() }).strict(),
z.object({}).strict(), z.object({}).strict(),
]).parse(request.query) ]).parse(request.query)
const segment = await readIxSegment(id) const segment = await readIxSegment(id)
if (!segment) throw new IxConflict("Сегмент IX не найден", 404) if (!segment) throw new IxConflict("Сегмент IX не найден", 404)
return "serverId" in query ? readIxLinuxClient(segment, query.serverId, query.interfaceName) : listIxLinuxClients(segment) return "serverId" in query ? readIxLinuxClient(segment, query.serverId, query.interfaceName, false, query.transportOnly === "true") : listIxLinuxClients(segment)
}) })
app.post("/ix/segments/:id/linux", async request => { app.post("/ix/segments/:id/linux", async request => {
const { id } = segmentParams.parse(request.params) const { id } = segmentParams.parse(request.params)
@@ -110,7 +171,12 @@ const ixRoutes: FastifyPluginAsync = async app => {
const current = await readIxSegment(id) const current = await readIxSegment(id)
if (!current) throw new IxConflict("Сегмент IX не найден", 404) if (!current) throw new IxConflict("Сегмент IX не найден", 404)
assertIxRevision(current, input.revision) assertIxRevision(current, input.revision)
const { configuration, interfaceName } = await configureIxLinuxClient(current, input) const base = input.transit ? { ...current, configuration: await configureIxTransit(current, {
...input.transit, revision: input.revision, serverId: input.serverId,
}) } : current
const { configuration, interfaceName } = await configureIxLinuxClient(base, {
...input, exit: input.transit?.name ?? input.exit,
})
const segment = await writeIxRevision(id, current.revision, configuration, request.authUser?.id ?? "system", false) const segment = await writeIxRevision(id, current.revision, configuration, request.authUser?.id ?? "system", false)
return { segment, interfaceName } return { segment, interfaceName }
}, { waitMs: 5000 }) }, { waitMs: 5000 })
@@ -124,13 +190,37 @@ const ixRoutes: FastifyPluginAsync = async app => {
}) })
app.post("/ix/segments/:id/linux/credential", async (request, reply) => { app.post("/ix/segments/:id/linux/credential", async (request, reply) => {
const { id } = segmentParams.parse(request.params) const { id } = segmentParams.parse(request.params)
const { serverId, interfaceName } = clientKey.parse(request.body) const { serverId, interfaceName, transportOnly, importLink } = clientKey.extend({
const scope = { deadlineAt: Date.now() + 60_000 } transportOnly: z.boolean().optional(), importLink: z.boolean().optional(),
}).parse(request.body)
const scope = { deadlineAt: Date.now() + (importLink ? importLinkLifetime : 60_000) }
const token = await captureVerifiedRestRequest(request, scope) const token = await captureVerifiedRestRequest(request, scope)
const { ownerId } = await inspectVerifiedRestRequest(token, scope, "mm:network:write") const authority = await inspectVerifiedRestRequest(token, scope, "mm:network:write")
const { ownerId } = authority
const segment = await readIxSegment(id) const segment = await readIxSegment(id)
if (!segment) throw new IxConflict("Сегмент IX не найден", 404) if (!segment) throw new IxConflict("Сегмент IX не найден", 404)
const access = await readIxLinuxClient(segment, serverId, interfaceName, true) if (importLink) {
const revision = segment.appliedRevision
if (revision === null) throw new IxConflict("Сначала примените конфигурацию площадки")
const authorizeOwner = importLinkOwner(authority)
await audit(pool, ownerId, "ix.linux.import_link_issued", null, { segmentId: id, serverId, interfaceName, revision })
await inspectVerifiedRestRequest(token, scope, "mm:network:write")
reply.header("Cache-Control", "private, no-store")
return { code: links.issue(authority.monotonicDeadline, async () => {
await authorizeOwner()
const current = await readIxSegment(id)
if (!current || current.appliedRevision !== revision) throw new IxConflict("Ревизия IX изменилась; получите новую ссылку", 410)
const access = await readIxLinuxClient(current, serverId, interfaceName, true, true, true)
if ((await readIxSegment(id))?.appliedRevision !== revision) throw new IxConflict("Ревизия IX изменилась; получите новую ссылку", 410)
await audit(pool, ownerId, "ix.linux.credential_exported", null, { segmentId: id, serverId, interfaceName, revision })
await authorizeOwner()
const name = access.filename.replace(/\.conf$/, "")
if (access.kind === "wireguard") return { version: 1, kind: "wireguard", name, config: access.template }
if (!access.greImport) throw new IxConflict("Нет параметров управляемого GRE/IPsec")
return { version: 1, kind: "gre-ipsec", name, gre: access.greImport }
}) }
}
const access = await readIxLinuxClient(segment, serverId, interfaceName, true, transportOnly)
await inspectVerifiedRestRequest(token, scope, "mm:network:write") await inspectVerifiedRestRequest(token, scope, "mm:network:write")
await audit(pool, ownerId, "ix.linux.credential_exported", null, { segmentId: id, serverId, interfaceName, revision: access.revision }) await audit(pool, ownerId, "ix.linux.credential_exported", null, { segmentId: id, serverId, interfaceName, revision: access.revision })
reply.header("Cache-Control", "no-store") reply.header("Cache-Control", "no-store")
+41 -25
View File
@@ -1,9 +1,10 @@
import { coalesceCatalogReads, observationIsCurrent, readCatalogWithObservedCache, withCatalogWriteLock } from "../services/routing-catalog-observation.js"
import { recursiveApplyBodySchema, recursiveTargetSchema, recursiveInputRowsSchema } from '../services/recursive-route-validation.js' import { recursiveApplyBodySchema, recursiveTargetSchema, recursiveInputRowsSchema } from '../services/recursive-route-validation.js'
import { parseRecursiveCatalog, parseRecursiveGatewayCatalog, readRecursiveEffectiveProperties, type RecursiveObservedProperty } from "../services/recursive-route-catalog.js" import { parseRecursiveCatalog, parseRecursiveGatewayCatalog, readRecursiveEffectiveProperties, type RecursiveObservedProperty } from "../services/recursive-route-catalog.js"
import { executeRecursiveApply, RecursiveApplyError } from "../services/recursive-apply.js" import { executeRecursiveApply, RecursiveApplyError } from "../services/recursive-apply.js"
import { storeRecursiveRoutes } from "../services/recursive-route-store.js" import { storeRecursiveRoutes } from "../services/recursive-route-store.js"
import { planRecursiveIdentities } from "../services/recursive-route-identity.js" import { planRecursiveIdentities } from "../services/recursive-route-identity.js"
import { withApplicationMutationLock, withConfigMutationLock } from "../services/config-mutation-lock.js" import { McpError } from "../modules/mcp/security.js"
import { asc, eq } from "drizzle-orm" import { asc, eq } from "drizzle-orm"
import { z } from "zod" import { z } from "zod"
import type { FastifyPluginAsyncZod } from "@fastify/type-provider-zod" import type { FastifyPluginAsyncZod } from "@fastify/type-provider-zod"
@@ -100,7 +101,7 @@ export async function applyRecursiveToServer(
source: ConfigRevisionSource, source: ConfigRevisionSource,
validateExisting?: (rows: ReturnType<typeof parseRecursiveCatalog>) => void | Promise<void>, validateExisting?: (rows: ReturnType<typeof parseRecursiveCatalog>) => void | Promise<void>,
): Promise<{ pushed: number; deleted: number }> { ): Promise<{ pushed: number; deleted: number }> {
return withApplicationMutationLock(() => withConfigMutationLock([server.id], async () => { return withCatalogWriteLock(server, "recursive-routes", async () => {
await storeRecursiveRoutes(server.id, routes, source, true) await storeRecursiveRoutes(server.id, routes, source, true)
const client = MikrotikClient.fromServer(server) const client = MikrotikClient.fromServer(server)
return executeRecursiveApply(client, routes.map(toRouterPayload), async () => { return executeRecursiveApply(client, routes.map(toRouterPayload), async () => {
@@ -116,7 +117,7 @@ export async function applyRecursiveToServer(
await validateExisting?.(parseRecursiveCatalog(observed)) await validateExisting?.(parseRecursiveCatalog(observed))
return observed return observed
}, () => readRecursiveNativeRowsForServer(server)) }, () => readRecursiveNativeRowsForServer(server))
})) })
} }
const RevisionIdParamSchema = z.object({ id: z.string().min(1) }) const RevisionIdParamSchema = z.object({ id: z.string().min(1) })
@@ -158,16 +159,32 @@ const recursiveDefaults: RecursiveRouteDependencies = {
/** Strict observation shared by both transports. REST can persist metadata; /** Strict observation shared by both transports. REST can persist metadata;
* observers opt out. An unavailable source always fails this catalog read. */ * observers opt out. An unavailable source always fails this catalog read. */
export async function readRecursiveCatalogForServer(server: ServerRow, deps: Pick<RecursiveRouteDependencies, "readRaw" | "readProperty" | "getRoutes" | "saveObserved"> = recursiveDefaults, options: { persistObserved?: boolean } = {}) { type RecursiveReadDependencies = Pick<RecursiveRouteDependencies, "readRaw" | "readProperty" | "getRoutes" | "saveObserved">
const read = async () => {
const readWebRecursiveRows = coalesceCatalogReads(readRecursiveNativeRowsForServer)
async function observeRecursiveRoutes(server: ServerRow, deps: RecursiveReadDependencies, persist: boolean) {
const read = async (fresh: boolean) => {
if (!server.enabled) throw new Error("Устройство отключено: каталог маршрутов недоступен") if (!server.enabled) throw new Error("Устройство отключено: каталог маршрутов недоступен")
const observed = await readRecursiveEffectiveProperties(await deps.readRaw(server), (id, property) => deps.readProperty(server, id, property)) const observed = !fresh && persist && deps === recursiveDefaults ? await readWebRecursiveRows(server)
const routes = mergeCachedCountry(parseRecursiveCatalog(observed), await deps.getRoutes(server.id)) : await readRecursiveEffectiveProperties(await deps.readRaw(server), (id, property) => deps.readProperty(server, id, property))
if (options.persistObserved !== false) await deps.saveObserved(server.id, routes) const cached = await deps.getRoutes(server.id)
return { serverId: server.id, routes, live: true, stale: false } const routes = mergeCachedCountry(parseRecursiveCatalog(observed), cached)
const current = !persist || deps === recursiveDefaults && await observationIsCurrent(server.id, "recursive-routes", canonicalRecursiveRoutes(routes), canonicalRecursiveRoutes(cached))
return { routes, cached, current }
} }
return deps === recursiveDefaults && options.persistObserved !== false const save = async (snapshot: Awaited<ReturnType<typeof read>>) => {
? withApplicationMutationLock(() => withConfigMutationLock([server.id], read)) : read() await deps.saveObserved(server.id, snapshot.routes)
return { ...snapshot, cached: await deps.getRoutes(server.id), current: true }
}
if (deps === recursiveDefaults) return readCatalogWithObservedCache(server, read, save)
const snapshot = await read(true)
return snapshot.current ? snapshot : save(snapshot)
}
export async function readRecursiveCatalogForServer(server: ServerRow, deps: RecursiveReadDependencies = recursiveDefaults, options: { persistObserved?: boolean } = {}) {
const { routes } = await observeRecursiveRoutes(server, deps, options.persistObserved !== false)
return { serverId: server.id, routes, live: true, stale: false }
} }
export async function readRecursiveNativeRowsForServer(server: ServerRow) { export async function readRecursiveNativeRowsForServer(server: ServerRow) {
@@ -187,22 +204,18 @@ export async function readRecursiveGatewaysForServer(server: ServerRow, deps: Pi
/** Legacy application read, including its explicit stale fallback. MCP observers /** Legacy application read, including its explicit stale fallback. MCP observers
* share the source/parser while leaving cache and revision history untouched. */ * share the source/parser while leaving cache and revision history untouched. */
export async function readRecursiveRoutesForServer(server: ServerRow, deps: Pick<RecursiveRouteDependencies, "readRaw" | "readProperty" | "getRoutes" | "saveObserved"> = recursiveDefaults, options: { persistObserved?: boolean } = {}) { export async function readRecursiveRoutesForServer(server: ServerRow, deps: RecursiveReadDependencies = recursiveDefaults, options: { persistObserved?: boolean } = {}) {
if (!server.enabled) throw new Error("Устройство отключено: опрос маршрутов недоступен") if (!server.enabled) throw new Error("Устройство отключено: опрос маршрутов недоступен")
const read = async () => { try {
const cached = await deps.getRoutes(server.id) const observed = await observeRecursiveRoutes(server, deps, options.persistObserved !== false)
try { const routes = options.persistObserved === false
const result = await readRecursiveCatalogForServer(server, deps, options) ? planRecursiveIdentities(observed.cached, observed.routes, new Set(), "observed").rows.map((row, index) => ({ ...row, id: row.id || observed.routes[index].id }))
const routes = options.persistObserved === false : observed.cached
? planRecursiveIdentities(cached, result.routes, new Set(), "observed").rows.map((row, index) => ({ ...row, id: row.id || result.routes[index].id })) return { serverId: server.id, routes, live: true, stale: false }
: await deps.getRoutes(server.id) } catch (error) {
return { ...result, routes } if (error instanceof McpError && (error.code === "CONFIGURATION_BUSY" || error.code === "STATE_CONFLICT")) throw error
} catch { return { serverId: server.id, routes: await deps.getRoutes(server.id), live: false, stale: true, error: "Не удалось подтвердить живой каталог; возвращена сохранённая конфигурация" }
return { serverId: server.id, routes: cached, live: false, stale: true, error: "Не удалось подтвердить живой каталог; возвращена сохранённая конфигурация" }
}
} }
return deps === recursiveDefaults && options.persistObserved !== false
? withApplicationMutationLock(() => withConfigMutationLock([server.id], read)) : read()
} }
export function createRecursiveRoutes(overrides: Partial<RecursiveRouteDependencies> = {}): FastifyPluginAsyncZod { export function createRecursiveRoutes(overrides: Partial<RecursiveRouteDependencies> = {}): FastifyPluginAsyncZod {
@@ -218,6 +231,7 @@ export function createRecursiveRoutes(overrides: Partial<RecursiveRouteDependenc
try { try {
return reply.send(await readRecursiveCatalogForServer(server, deps)) return reply.send(await readRecursiveCatalogForServer(server, deps))
} catch (error) { } catch (error) {
if (error instanceof McpError) throw error
return reply.status(503).send({ error: error instanceof Error ? error.message : "Не удалось прочитать каталог маршрутов" }) return reply.status(503).send({ error: error instanceof Error ? error.message : "Не удалось прочитать каталог маршрутов" })
} }
}) })
@@ -276,6 +290,7 @@ export function createRecursiveRoutes(overrides: Partial<RecursiveRouteDependenc
return reply.send({ ok: true, serverId, routes: stored, pushedRoutes: result.pushed }) return reply.send({ ok: true, serverId, routes: stored, pushedRoutes: result.pushed })
} catch (err) { } catch (err) {
const receipt = recursiveFailureReceipt(err, result) const receipt = recursiveFailureReceipt(err, result)
if (!receipt && err instanceof McpError) throw err
return reply.status(receipt ? 502 : 500).send({ error: String(err), serverId, ...receipt }) return reply.status(receipt ? 502 : 500).send({ error: String(err), serverId, ...receipt })
} }
}) })
@@ -313,6 +328,7 @@ export function createRecursiveRoutes(overrides: Partial<RecursiveRouteDependenc
return reply.send({ ok: true, serverId: server.id, routes: stored, pushedRoutes: result.pushed }) return reply.send({ ok: true, serverId: server.id, routes: stored, pushedRoutes: result.pushed })
} catch (err) { } catch (err) {
const receipt = recursiveFailureReceipt(err, result) const receipt = recursiveFailureReceipt(err, result)
if (!receipt && err instanceof McpError) throw err
return reply.status(receipt ? 502 : 500).send({ error: String(err), serverId: server.id, ...receipt }) return reply.status(receipt ? 502 : 500).send({ error: String(err), serverId: server.id, ...receipt })
} }
}) })
+11
View File
@@ -5,6 +5,7 @@ import { createSchedulerRoutes } from "./scheduler.js"
import type { SchedulerRunReceipt } from "../services/scheduler-recorded-run.js" import type { SchedulerRunReceipt } from "../services/scheduler-recorded-run.js"
import { pauseSchedulerJobsAndWait, resumeSchedulerJobs } from "../services/scheduler-running.js" import { pauseSchedulerJobsAndWait, resumeSchedulerJobs } from "../services/scheduler-running.js"
import { runSchedulerJobNow } from "../services/scheduler.js" import { runSchedulerJobNow } from "../services/scheduler.js"
import { ConfigurationBusyError } from "../services/config-mutation-lock.js"
const receipt: SchedulerRunReceipt = { status: "ok", error: null, result: { v: 1, job: "backups", sampledAt: "2026-10-01T00:00:00Z", due: true, created: 1, failures: 0, pruned: 0 } } const receipt: SchedulerRunReceipt = { status: "ok", error: null, result: { v: 1, job: "backups", sampledAt: "2026-10-01T00:00:00Z", due: true, created: 1, failures: 0, pruned: 0 } }
async function setup(patch: Partial<Parameters<typeof createSchedulerRoutes>[0]> = {}) { async function setup(patch: Partial<Parameters<typeof createSchedulerRoutes>[0]> = {}) {
const app = Fastify(); let calls = 0 const app = Fastify(); let calls = 0
@@ -39,3 +40,13 @@ test("collector or journal rejection remains explicit without a fabricated recei
const { app } = await setup({ run: async () => { throw Error("journal not confirmed; retry may repeat operations") } }) const { app } = await setup({ run: async () => { throw Error("journal not confirmed; retry may repeat operations") } })
try { const response = await app.inject({ method: "POST", url: "/scheduler/jobs/backups/run-now" }); assert.equal(response.statusCode, 500); assert.match(response.json().error, /retry may repeat/); assert.equal(response.json().result, undefined) } finally { await app.close() } try { const response = await app.inject({ method: "POST", url: "/scheduler/jobs/backups/run-now" }); assert.equal(response.statusCode, 500); assert.match(response.json().error, /retry may repeat/); assert.equal(response.json().result, undefined) } finally { await app.close() }
}) })
test("configuration contention is distinguishable from an already running job", async () => {
const busy = new ConfigurationBusyError("server")
const { app } = await setup({ run: async () => { throw busy } })
try {
const response = await app.inject({ method: "POST", url: "/scheduler/jobs/uptime_ping/run-now" })
assert.equal(response.statusCode, 409)
assert.deepEqual(response.json(), { code: "CONFIGURATION_BUSY", error: busy.message })
} finally { await app.close() }
})
+4 -4
View File
@@ -51,11 +51,11 @@ return async (app) => {
return reply.send({ ok: result.status === "ok", result, status, ...(statusError ? { statusError } : {}) }) return reply.send({ ok: result.status === "ok", result, status, ...(statusError ? { statusError } : {}) })
} catch (e) { } catch (e) {
const statusCode = (e as Error & { statusCode?: number }).statusCode const statusCode = (e as Error & { statusCode?: number }).statusCode
if (statusCode === 409) {
const paused = (e as Error & { code?: string }).code === "SCHEDULER_PAUSED"
return reply.status(409).send({ error: paused ? "Планировщик приостановлен для операции с базой" : "Задача уже выполняется" })
}
const msg = e instanceof Error ? e.message : String(e) const msg = e instanceof Error ? e.message : String(e)
if (statusCode === 409) {
const code = (e as Error & { code?: string }).code
return reply.status(409).send({ error: msg, ...(code ? { code } : {}) })
}
return reply.status(500).send({ error: msg }) return reply.status(500).send({ error: msg })
} }
}) })
+3 -1
View File
@@ -210,7 +210,9 @@ const trafficFlowRoutes: FastifyPluginAsyncZod = async (app) => {
app.get("/traffic/flow/map-hops", async (req, reply) => { app.get("/traffic/flow/map-hops", async (req, reply) => {
const query = analyticsQuery(req) 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) => { app.get("/traffic/flow/monthly", async (req, reply) => {
+35 -10
View File
@@ -13,7 +13,7 @@ import {
} from "../services/traffic-collector.js" } from "../services/traffic-collector.js"
import { refreshScheduler } from "../services/scheduler.js" import { refreshScheduler } from "../services/scheduler.js"
import { collectTrafficManually } from "../services/manual-traffic-collection.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 { MikrotikClient, MikrotikError } from "../services/mikrotik.js"
import { getEnabledServerById } from "../services/wireguard-live.js" import { getEnabledServerById } from "../services/wireguard-live.js"
import { readTrafficCollectionContext } from "../services/traffic-collection-state.js" import { readTrafficCollectionContext } from "../services/traffic-collection-state.js"
@@ -106,7 +106,17 @@ const trafficRoutes: FastifyPluginAsyncZod = async (app) => {
}) })
app.get("/traffic/servers/:id/live", async (req, reply) => { app.get("/traffic/servers/:id/live", async (req, reply) => {
const p = req.params as { id?: string | number } const p = req.params as { id?: string | number }
const q = req.query as { iface?: string } 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 () => { const readServer = (id: string | number, signal?: AbortSignal) => withDatabaseApiRequest(async () => {
signal?.throwIfAborted() signal?.throwIfAborted()
const row = await getEnabledServerById(id) const row = await getEnabledServerById(id)
@@ -117,11 +127,33 @@ const trafficRoutes: FastifyPluginAsyncZod = async (app) => {
if (!server || !server.enabled) return reply.status(404).send({ error: "Server not found" }) if (!server || !server.enabled) return reply.status(404).send({ error: "Server not found" })
const onlyInterface = q.iface && q.iface !== "__all__" ? q.iface : undefined 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 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 abort = new AbortController()
const onClose = () => abort.abort() const onClose = () => abort.abort()
registerDatabaseStreamAbort(req, onClose) registerDatabaseStreamAbort(req, onClose)
if (abort.signal.aborted) return reply.code(503).send({ error: "Выполняется операция с базой приложения" }) if (abort.signal.aborted) return reply.code(503).send({ error: "Выполняется операция с базой приложения" })
if (reply.raw.destroyed) return if (reply.raw.destroyed) return
if (q.once === "1") {
reply.raw.once("close", onClose)
try {
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-измерение интерфейса недоступно" })
return
} finally {
reply.raw.off("close", onClose)
}
}
reply.raw.on("close", onClose) reply.raw.on("close", onClose)
reply.hijack() reply.hijack()
@@ -144,17 +176,10 @@ const trafficRoutes: FastifyPluginAsyncZod = async (app) => {
reply.raw.writeHead(200, sseHeaders) reply.raw.writeHead(200, sseHeaders)
reply.raw.write(":\n\n") reply.raw.write(":\n\n")
const client = MikrotikClient.fromServer(server)
const cache = { names: onlyInterface ? [onlyInterface] : [] as string[], joinedFailed: false }
try { try {
while (!abort.signal.aborted) { while (!abort.signal.aborted) {
try { try {
const sample = await readTrafficLiveSample(client, onlyInterface, cache, abort.signal, async () => { const sample = await readSample(abort.signal)
const current = await readServer(server.id, abort.signal)
if (!current) throw new TrafficLiveSourceChanged("Устройство выключено или удалено. Live-поток остановлен")
if (Date.parse(current.updatedAt) !== Date.parse(server.updatedAt)) throw new TrafficLiveSourceChanged("Конфигурация устройства изменилась. Переподключите live-поток")
})
if (abort.signal.aborted) break if (abort.signal.aborted) break
writeSse(reply.raw, "sample", sample) writeSse(reply.raw, "sample", sample)
} catch (error) { } catch (error) {
+25 -6
View File
@@ -14,10 +14,10 @@ const held = new AsyncLocalStorage<ServerLockCompletion>()
const applicationLease = new AsyncLocalStorage<LockCompletion>() const applicationLease = new AsyncLocalStorage<LockCompletion>()
const collectorLease = new AsyncLocalStorage<LockCompletion>() const collectorLease = new AsyncLocalStorage<LockCompletion>()
const applicationLockKey = "hashtextextended('mm-config:application',0)" const applicationLockKey = "hashtextextended('mm-config:application',0)"
/** Another mutation holds the global configuration lock, or collectors hold it shared while they read routers.
* Same message and 409 as before; the code lets MCP report it instead of a generic device failure. */
export class ConfigurationBusyError extends McpError { export class ConfigurationBusyError extends McpError {
constructor() { super("CONFIGURATION_BUSY", "Глобальная конфигурация изменяется другой операцией", 409) } constructor(scope: "application" | "server" = "application") {
super("CONFIGURATION_BUSY", scope === "server" ? "Конфигурация сервера временно занята другой операцией" : "Глобальная конфигурация временно занята другой операцией", 409)
}
} }
export async function acquireApplicationMutationTransactionLock(client: Pick<PoolClient, "query">): Promise<void> { export async function acquireApplicationMutationTransactionLock(client: Pick<PoolClient, "query">): Promise<void> {
@@ -80,17 +80,36 @@ export async function withApplicationMutationLock<T>(work: () => Promise<T>, opt
/** Collectors coexist with each other but exclude configuration mutation for /** Collectors coexist with each other but exclude configuration mutation for
* the complete native/sample/status operation. This lock grants no authority. * the complete native/sample/status operation. This lock grants no authority.
* Verified operations retain their original exact exclusive client protocol. */ * Verified operations retain their original exact exclusive client protocol. */
export async function withApplicationCollectorLock<T>(work: () => Promise<T>): Promise<T> { export async function withApplicationCollectorLock<T>(work: () => Promise<T>, { waitMs = 5000 }: { waitMs?: number } = {}): Promise<T> {
assertOperationConfigurationLockScope() assertOperationConfigurationLockScope()
if (applicationLease.getStore()?.active || captureOperationConfigurationLockHandoff()) return withApplicationMutationLock(work) if (applicationLease.getStore()?.active || captureOperationConfigurationLockHandoff()) return withApplicationMutationLock(work)
if (collectorLease.getStore()?.active) return work() if (collectorLease.getStore()?.active) return work()
const deadline = performance.now() + waitMs
for (;;) {
let admitted = false
try {
return await tryApplicationCollectorLock(() => {
admitted = true
return work()
})
} catch (error) {
const remaining = deadline - performance.now()
if (admitted || !(error instanceof ConfigurationBusyError) || remaining <= 0) throw error
// Release the failed attempt's connection before waiting for the writer.
await delay(Math.min(250, remaining))
if (performance.now() >= deadline) throw error
}
}
}
async function tryApplicationCollectorLock<T>(work: () => Promise<T>): Promise<T> {
let complete!: () => void let complete!: () => void
const completed = new Promise<void>(resolve => { complete = resolve }) const completed = new Promise<void>(resolve => { complete = resolve })
const client = await pool.connect(), context = { active: true, completed } const client = await pool.connect(), context = { active: true, completed }
let acquired = false, unsafe = false let acquired = false, unsafe = false
try { try {
acquired = (await client.query(`SELECT pg_try_advisory_lock_shared(${applicationLockKey}) AS acquired`)).rows[0].acquired acquired = (await client.query(`SELECT pg_try_advisory_lock_shared(${applicationLockKey}) AS acquired`)).rows[0].acquired
if (!acquired) throw Object.assign(new Error("Глобальная конфигурация изменяется другой операцией"), { statusCode: 409 }) if (!acquired) throw new ConfigurationBusyError()
return await collectorLease.run(context, work) return await collectorLease.run(context, work)
} finally { } finally {
context.active = false context.active = false
@@ -159,7 +178,7 @@ async function runConfigMutationLock<T>(serverIds: number[], work: () => Promise
} }
for (const id of requested) { for (const id of requested) {
const { rows: [row] } = await client.query<{ acquired: boolean }>("SELECT pg_try_advisory_lock(hashtextextended($1,0)) AS acquired", ["mm-config:" + id]) const { rows: [row] } = await client.query<{ acquired: boolean }>("SELECT pg_try_advisory_lock(hashtextextended($1,0)) AS acquired", ["mm-config:" + id])
if (!row.acquired) throw Object.assign(new Error("Конфигурация сервера изменяется другой операцией"), { statusCode: 409 }) if (!row.acquired) throw new ConfigurationBusyError("server")
acquired.push(id) acquired.push(id)
signal.throwIfAborted() signal.throwIfAborted()
} }
@@ -0,0 +1,55 @@
import assert from "node:assert/strict"
import { test } from "node:test"
import type { IxBondCandidate, IxBondEdit, IxSavedBond } from "@mmapp/contracts/internet-exchange"
import { ixSegmentConfigurationSchema } from "@mmapp/contracts/internet-exchange"
import { bondCandidates, resolveBondMembers } from "./internet-exchange-bonds.js"
const owner = "a213a2c7-53cd-4325-8e43-e2d953cd761b"
const other = "5c1364bd-6147-46ea-b726-273a7e933302"
const client = "5a7fa65a-f94f-475a-96cd-a2ece0ed77ce"
const primary: IxBondCandidate = { segmentId: owner, appliedRevision: 3, serverId: 5, segmentName: "eu",
interfaceName: "wg-vps", name: "alpha", kind: "wireguard", probe: "10.255.0.1", address: "10.255.0.2", endpoint: "192.0.2.1", destinations: ["0.0.0.0/0"] }
const backup: IxBondCandidate = { ...primary, segmentId: other, segmentName: "asia", clientId: client,
serverId: 6, kind: "gre-ipsec", interfaceName: "gre-vps", probe: "10.255.0.5", address: "10.255.0.6" }
const edit: IxBondEdit = { name: "vps", mode: "weighted", directCidrs: [], revision: 0,
members: [primary, backup].map(({ segmentId, appliedRevision, serverId, interfaceName }, i) =>
({ segmentId, appliedRevision, serverId, interfaceName, weight: i ? 1 : 3 })) }
test("cross-segment members retain order, declared VPS identity and revision", () => {
const { members, clientId } = resolveBondMembers(edit, [backup, primary], [], owner)
assert.deepEqual(members, [primary, backup])
assert.equal(clientId, client)
const saved: IxSavedBond = { ...edit, id: other, ownerSegmentId: owner, revision: 1, clientId }
assert.throws(() => resolveBondMembers(edit, [primary, backup], [saved], owner), /уже входит/)
assert.equal(resolveBondMembers(saved, [primary, backup], [saved], owner, saved).clientId, client)
})
test("reject stale, revoked, foreign-client and conflicting routing paths", () => {
const invalid: Array<[IxBondCandidate, RegExp]> = [
[{ ...backup, appliedRevision: 4 }, /изменилось/],
[{ ...backup, destinations: ["198.51.100.0/24"] }, /назначения/],
[{ ...backup, address: primary.probe }, /внутренние адреса/],
]
for (const [candidate, reason] of invalid) {
assert.throws(() => resolveBondMembers(edit, [primary, candidate], [], owner), reason)
}
assert.throws(() => resolveBondMembers(edit, [primary], [], owner), /недоступно/)
assert.throws(() => resolveBondMembers(edit, [{ ...primary, clientId: owner }, backup], [], owner), /разными VPS/)
assert.throws(() => resolveBondMembers(edit, [primary, backup], [], client), /текущего сегмента/)
})
test("existing static WireGuard exports keep their applied prefixes; external GRE and BGP remain independent", () => {
const config = ixSegmentConfigurationSchema.parse({ name: "legacy", sites: [{ serverId: 5, autonomousSystem: 64512,
routerId: "192.0.2.1", interfaces: [
{ kind: "wireguard", name: "wg-static", provisionWireguard: { listenPort: 31820, hubEndpoint: primary.endpoint,
localAddress: primary.probe + "/30", peerAddress: primary.address, peerPublicKey: Buffer.alloc(32, 3).toString("base64") } },
{ kind: "gre-ipsec", name: "gre-manual", localEndpoint: primary.endpoint, endpoint: "198.51.100.8", prefixes: ["10.7.0.0/24"] },
] }] })
const [candidate] = bondCandidates(owner, 7, config)
assert.deepEqual(bondCandidates(owner, 7, config).map(c => c.interfaceName), ["wg-static"])
assert.deepEqual(candidate.destinations, ["10.7.0.0/24"])
assert.equal(candidate.clientId, undefined)
config.sites[0].neighbors.push({ id: "bgp", binding: "wg-static", type: "member", remoteAs: 64513,
address: primary.address, localAddress: primary.probe, prefixes: [], exportPrefixes: [], rules: [], limit: 10 })
assert.deepEqual(bondCandidates(owner, 7, config), [])
})
@@ -0,0 +1,176 @@
import { randomUUID } from "node:crypto"
import { isIP } from "node:net"
import type { PoolClient } from "pg"
import {
ixBondBundleSchema, ixSavedBondSchema, ixSegmentConfigurationSchema, type IxBondCandidate,
type IxBondEdit, type IxSavedBond, type IxConfiguration, type IxBondBundle,
} from "@mmapp/contracts/internet-exchange"
import { pool } from "../db/index.js"
import { audit } from "../modules/mcp/store.js"
import { canonicalBgpPolicyPrefix } from "./bgp-community-policy-model.js"
import { ixLegacyWireguardRoutes, ixLinuxBindingKind, ixLinuxInterfaceName } from "./internet-exchange-client.js"
import { readIxLinuxClient, verifyIxExistingTransport } from "./internet-exchange-execution.js"
import { IxConflict } from "./internet-exchange-plan.js"
import { ixReservedTunnelBindings, readIxSegment } from "./internet-exchange-store.js"
import { admitPartitionWriter } from "./partition-write-transaction.js"
type Query = Pick<PoolClient, "query">
type MemberRef = IxBondEdit["members"][number]
const visible = "(s.configuration->>'deleted') IS DISTINCT FROM 'true'"
const key = (m: Pick<MemberRef, "segmentId" | "serverId" | "interfaceName">) => [m.segmentId, m.serverId, m.interfaceName].join("/")
export function bondCandidates(segmentId: string, appliedRevision: number, config: IxConfiguration): IxBondCandidate[] {
return config.sites.flatMap(site => site.interfaces.flatMap(binding => {
const kind = ixLinuxBindingKind(binding)
const linux = binding.linux
const tunnel = binding.provisionWireguard ?? binding.provisionGre
if (!kind || linux?.enabled === false || !tunnel || binding.peerServerId) return []
if (!linux && (kind !== "wireguard" || site.neighbors.some(peer => peer.binding === binding.name))) return []
const family = isIP(tunnel.peerAddress)
const routes = linux ? linux.destinations : ixLegacyWireguardRoutes(config, binding)
const destinations = linux?.exit ? [family === 6 ? "::/0" : "0.0.0.0/0"]
: [...new Set(routes.map(canonicalBgpPolicyPrefix))].sort()
if (!linux && (!destinations.length || destinations.length > 64 || destinations.some(cidr => isIP(cidr.split("/")[0]) !== family))) return []
return [{
segmentId, appliedRevision, segmentName: config.name, serverId: site.serverId, interfaceName: binding.name,
name: linux?.name ?? binding.name, clientId: linux?.clientId, kind, address: tunnel.peerAddress, probe: tunnel.localAddress.split("/")[0],
endpoint: (binding.provisionWireguard?.hubEndpoint ?? binding.localEndpoint)!,
destinations,
}]
}))
}
async function candidates(sql: Query, ids?: string[], refs: MemberRef[] = []) {
const { rows } = await sql.query(`SELECT s.id,s.applied_revision,r.configuration FROM ix_segments s
JOIN ix_segment_revisions r ON r.segment_id=s.id AND r.revision=s.applied_revision
WHERE ${visible} AND ($1::uuid[] IS NULL OR s.id=ANY($1)) ORDER BY s.name,s.id`, [ids ?? null])
return rows.flatMap(row => {
const config = ixSegmentConfigurationSchema.parse(row.configuration)
const result = bondCandidates(row.id, row.applied_revision, config)
for (const ref of refs) {
const path = ref.existing
if (!path || ref.segmentId !== row.id) continue
const site = config.sites.find(s => s.serverId === ref.serverId)
const binding = site?.interfaces.find(b => b.name === ref.interfaceName)
if (!site || binding && (binding.peerServerId || binding.provisionTransit || binding.provisionWireguard || binding.provisionGre || binding.linux ||
binding.kind !== path.kind) || result.some(c => key(c) === key(ref)) || site.neighbors.some(p => p.binding === ref.interfaceName)) {
throw new IxConflict("Интерфейс занят клиентом, BGP либо принадлежит другому узлу: " + ref.interfaceName)
}
result.push({ ...ref, ...path, segmentName: config.name, appliedRevision: row.applied_revision, name: path.linuxInterface,
destinations: [...new Set(path.destinations.map(canonicalBgpPolicyPrefix))].sort() })
}
return result
})
}
export async function inspectIxBondImports(ownerId: string, edit: IxBondEdit) {
if (!edit.members.some(m => m.existing)) return
const [available, groups] = await Promise.all([candidates(pool, [...new Set(edit.members.map(m => m.segmentId))], edit.members), savedGroups(pool)])
resolveBondMembers(edit, available, groups, ownerId, groups.find(g => g.id === edit.id && g.ownerSegmentId === ownerId))
for (const m of edit.members) if (m.existing) await verifyIxExistingTransport(m.segmentId, m.serverId, m.interfaceName, m.existing)
}
async function savedGroups(sql: Query, ownerId?: string): Promise<IxSavedBond[]> {
const { rows } = await sql.query(`SELECT item FROM ix_segments s
CROSS JOIN LATERAL jsonb_array_elements(s.configuration->'linuxBonds') item
WHERE ${visible} AND ($1::uuid IS NULL OR s.id=$1) ORDER BY s.id`, [ownerId ?? null])
return rows.map(row => ixSavedBondSchema.parse(row.item))
}
export async function ixBondCatalog() {
const [groups, available] = await Promise.all([savedGroups(pool), candidates(pool)])
return { groups, candidates: available }
}
export function resolveBondMembers(edit: IxBondEdit, available: IxBondCandidate[], groups: IxSavedBond[], ownerId: string, previous?: IxSavedBond) {
const routerInterface = (m: MemberRef) => m.serverId + "/" + m.interfaceName
const occupied = new Set(groups.filter(g => g.id !== previous?.id).flatMap(g => g.members.map(routerInterface)))
const owned = new Map(available.map(m => [key(m), m]))
const addresses = new Set<string>()
const linuxNames = new Set<string>()
const members = edit.members.map(member => {
const label = member.interfaceName
const found = owned.get(key(member))
if (!found || found.appliedRevision !== member.appliedRevision) throw new IxConflict("Подключение изменилось или недоступно: " + label)
if (occupied.has(routerInterface(member))) throw new IxConflict("Интерфейс уже входит в группу: " + label)
occupied.add(routerInterface(member))
const linuxName = found.existing?.linuxInterface ?? ixLinuxInterfaceName(found.kind === "wireguard" ? "ixw" : "ixg", found.serverId, { name: found.interfaceName })
if (linuxNames.has(linuxName)) throw new IxConflict("Имя интерфейса на VPS повторяется: " + linuxName)
linuxNames.add(linuxName)
for (const address of [found.address, found.probe]) {
const host = canonicalBgpPolicyPrefix(address + (isIP(address) === 6 ? "/128" : "/32"))
if (addresses.has(host)) throw new IxConflict("Назначьте разные внутренние адреса участникам группы: " + address)
addresses.add(host)
}
return found
})
const first = members[0]
if (!members.some(m => m.segmentId === ownerId)) throw new IxConflict("Выберите подключение из текущего сегмента")
if (!first?.destinations.length || members.some(m => isIP(m.address) !== isIP(first.address) ||
JSON.stringify(m.destinations) !== JSON.stringify(first.destinations))) {
throw new IxConflict("Участникам нужны одинаковые непустые назначения и одно семейство адресов")
}
const identities = new Set(members.flatMap(m => m.clientId ? [m.clientId] : []))
if (previous) identities.add(previous.clientId)
if (identities.size > 1) throw new IxConflict("Выбранные подключения зарегистрированы за разными VPS")
return { members, clientId: [...identities][0] ?? randomUUID() }
}
export async function changeIxBond(ownerId: string, edit: IxBondEdit | { id: string; revision: number }, actor: string) {
const sql = await pool.connect()
try {
await sql.query("BEGIN")
await admitPartitionWriter(sql)
// A member can belong to only one group, including groups owned by another segment.
await sql.query("SELECT pg_advisory_xact_lock(hashtextextended('ix-linux-bonds',0))")
if (!await readIxSegment(ownerId, sql)) throw new IxConflict("Сегмент IX не найден", 404)
const groups = await savedGroups(sql)
const previous = groups.find(group => group.ownerSegmentId === ownerId && group.id === edit.id)
if (edit.id && !previous) throw new IxConflict("Группа не найдена", 404)
if ((previous?.revision ?? 0) !== edit.revision) throw new IxConflict("Группа изменилась. Обновите данные")
let next: IxSavedBond | null = null
if ("members" in edit) {
const available = await candidates(sql, [...new Set(edit.members.map(m => m.segmentId))], edit.members)
const { clientId } = resolveBondMembers(edit, available, groups, ownerId, previous)
for (const m of edit.members) if (m.existing && (await ixReservedTunnelBindings(m.serverId, m.segmentId, sql)).some(b => b.name === m.interfaceName)) {
throw new IxConflict("Интерфейс уже закреплён за другим сегментом: " + m.interfaceName)
}
next = ixSavedBondSchema.parse({ ...edit, id: previous?.id ?? randomUUID(), ownerSegmentId: ownerId, clientId,
revision: edit.revision + 1, directCidrs: [...new Set(edit.directCidrs.map(canonicalBgpPolicyPrefix))] })
}
const owned = groups.filter(group => group.ownerSegmentId === ownerId && group.id !== edit.id)
if (next) owned.push(next)
const result = await sql.query(`UPDATE ix_segments s SET configuration=jsonb_set(configuration,'{linuxBonds}',$2::jsonb)
WHERE s.id=$1 AND ${visible}`, [ownerId, JSON.stringify(owned)])
if (result.rowCount !== 1) throw new IxConflict("Сегмент IX недоступен")
await audit(sql, actor, next ? "ix.bond.saved" : "ix.bond.removed", null, { ownerId, id: next?.id ?? edit.id, revision: next?.revision ?? edit.revision })
await sql.query("COMMIT")
return next
} catch (error) {
await sql.query("ROLLBACK").catch(() => {})
throw error
} finally { sql.release() }
}
export async function exportIxBond(ownerId: string, id: string, revision: number, authorize: () => Promise<unknown>): Promise<IxBondBundle> {
const group = (await savedGroups(pool, ownerId)).find(g => g.id === id)
if (!group || group.revision !== revision) throw new IxConflict("Группа отсутствует или её ревизия изменилась")
const segments = [...new Set(group.members.map(m => m.segmentId))]
const { members } = resolveBondMembers(group, await candidates(pool, segments, group.members), [], ownerId, group)
const result = []
for (const [index, m] of members.entries()) {
await authorize()
const segment = await readIxSegment(m.segmentId)
if (!segment || segment.appliedRevision !== m.appliedRevision) throw new IxConflict("Изменилась площадка " + m.segmentName)
const access = m.existing ? { filename: m.existing.linuxInterface,
hubPublicKey: await verifyIxExistingTransport(m.segmentId, m.serverId, m.interfaceName, m.existing) }
: await readIxLinuxClient(segment, m.serverId, m.interfaceName)
result.push({ kind: m.kind, interfaceName: m.existing ? m.existing.linuxInterface : access.filename.replace(/\.conf$/, ""), address: m.address, probe: m.probe,
endpoint: m.endpoint, weight: group.mode === "weighted" ? group.members[index].weight : 1,
...(m.kind === "wireguard" && { peerPublicKey: access.hubPublicKey }) })
}
const bundle = ixBondBundleSchema.parse({ version: 1, id, revision, name: group.name, clientId: group.clientId, mode: group.mode,
destinations: members[0].destinations, directCidrs: group.directCidrs, members: result })
await authorize()
return bundle
}
@@ -1,6 +1,6 @@
import { createHash } from "node:crypto" import { createHash } from "node:crypto"
import { isIP } from "node:net" import { isIP } from "node:net"
import type { IxSite } from "@mmapp/contracts/internet-exchange" import type { IxConfiguration, IxSite } from "@mmapp/contracts/internet-exchange"
import { canonicalBgpPolicyPrefix } from "./bgp-community-policy-model.js" import { canonicalBgpPolicyPrefix } from "./bgp-community-policy-model.js"
import { IxConflict } from "./internet-exchange-plan.js" import { IxConflict } from "./internet-exchange-plan.js"
@@ -12,11 +12,16 @@ export function ixLinuxBindingKind(binding: Binding) {
return null return null
} }
export function ixLinuxInterfaceName(prefix: "ixw" | "ixg", serverId: number, binding: Binding) { export function ixLegacyWireguardRoutes(configuration: IxConfiguration, binding: Binding) {
return configuration.sites.flatMap(site => site.interfaces
.filter(connection => connection !== binding && connection.kind !== "uplink").flatMap(connection => connection.prefixes))
}
export function ixLinuxInterfaceName(prefix: "ixw" | "ixg", serverId: number, binding: Pick<Binding, "name">) {
return prefix + createHash("sha256").update(JSON.stringify([serverId, binding.name])).digest("hex").slice(0, 12) return prefix + createHash("sha256").update(JSON.stringify([serverId, binding.name])).digest("hex").slice(0, 12)
} }
export function ixWireguardClientTemplate(binding: Binding, hubPublicKey: string, routes: string[]) { export function ixWireguardClientTemplate(binding: Binding, hubPublicKey: string, routes: string[], privateKey = "<локальный_приватный_ключ>", transportOnly = false) {
const config = binding.provisionWireguard const config = binding.provisionWireguard
if (binding.kind !== "wireguard" || !config?.hubEndpoint || !/^[A-Za-z0-9+/]{43}=$/.test(hubPublicKey)) { if (binding.kind !== "wireguard" || !config?.hubEndpoint || !/^[A-Za-z0-9+/]{43}=$/.test(hubPublicKey)) {
throw new IxConflict("Для Linux нужны публичный ключ узла и заданный внешний адрес IX") throw new IxConflict("Для Linux нужны публичный ключ узла и заданный внешний адрес IX")
@@ -28,9 +33,9 @@ export function ixWireguardClientTemplate(binding: Binding, hubPublicKey: string
return [ return [
"[Interface]", "[Interface]",
"Address = " + address(config.peerAddress), "Address = " + address(config.peerAddress),
"PrivateKey = <локальный_приватный_ключ>", "PrivateKey = " + privateKey,
binding.linux ? "Table = auto" : "Table = off", binding.linux && !transportOnly ? "Table = auto" : "Table = off",
...(binding.linux?.exit && binding.linux.peerEndpoint && isIP(binding.linux.peerEndpoint) === family ? [ ...(!transportOnly && binding.linux?.exit && binding.linux.peerEndpoint && isIP(binding.linux.peerEndpoint) === family ? [
"PostUp = ip -" + family + " rule add pref 10450 from " + address(binding.linux.peerEndpoint) + " lookup main", "PostUp = ip -" + family + " rule add pref 10450 from " + address(binding.linux.peerEndpoint) + " lookup main",
"PreDown = ip -" + family + " rule del pref 10450 from " + address(binding.linux.peerEndpoint) + " lookup main", "PreDown = ip -" + family + " rule del pref 10450 from " + address(binding.linux.peerEndpoint) + " lookup main",
] : []), ] : []),
@@ -44,7 +49,7 @@ export function ixWireguardClientTemplate(binding: Binding, hubPublicKey: string
].join("\n") ].join("\n")
} }
export function ixGreClientTemplate(binding: Binding, serverId: number, bgp?: { address: string; localAddress: string }, credential?: string) { export function ixGreClientTemplate(binding: Binding, serverId: number, bgp?: { address: string; localAddress: string }, credential?: string, transportOnly = false) {
const hub = binding.localEndpoint const hub = binding.localEndpoint
const client = binding.endpoint const client = binding.endpoint
if (binding.kind !== "gre-ipsec" || !hub || !client || isIP(hub) !== 4 || isIP(client) !== 4 || hub === client) { if (binding.kind !== "gre-ipsec" || !hub || !client || isIP(hub) !== 4 || isIP(client) !== 4 || hub === client) {
@@ -55,13 +60,47 @@ export function ixGreClientTemplate(binding: Binding, serverId: number, bgp?: {
const tunnel = binding.provisionGre const tunnel = binding.provisionGre
const family = tunnel ? isIP(tunnel.peerAddress) : 4 const family = tunnel ? isIP(tunnel.peerAddress) : 4
const protocol = "ip -" + family const protocol = "ip -" + family
const local = tunnel?.localAddress.split("/")[0]
const table = 30000 + parseInt(id.slice(-4), 16) const table = 30000 + parseInt(id.slice(-4), 16)
const management = 10000 + parseInt(id.slice(-3), 16) const management = 12000 + 2 * parseInt(id.slice(-3), 16)
const managementRules = [
["ip -4", "to " + hub + "/32 lookup main"],
["ip -4", "from " + client + "/32 lookup main"],
...(family === 6 && binding.linux?.exit ? [["ip -6", "ipproto tcp sport 22 lookup main"]] : []),
]
const greParameters = id + " mode gre local " + client + " remote " + hub
const common = [
"swanctl --load-all",
"swanctl --initiate --child " + id + " --timeout 20",
"ip tunnel add " + greParameters,
]
const addressCommand = tunnel && "ip address add " + tunnel.peerAddress + (family === 4 ? "/32" : "/128") + " dev " + id
const transportSetup = transportOnly && tunnel && [
'conf="$(dirname -- "$0")/' + id + '.conf"',
'unit=/etc/systemd/system/ix-gre-' + id + '.service',
'profile=/etc/swanctl/conf.d/' + id + '.conf',
'if [ ! -r "$conf" ]; then echo "Положите ' + id + '.conf рядом со скриптом."; exit 1; fi',
'candidate=$(mktemp)',
'trap \'rm -f "$candidate"\' EXIT',
'cat >"$candidate" <<\'IX_GRE_UNIT\'',
"[Unit]", "Description=IX Client GRE/IPsec " + id, "Wants=network-online.target", "After=network-online.target strongswan.service",
"Requires=strongswan.service", "[Service]", "Type=oneshot", "RemainAfterExit=yes",
"ExecStartPre=/usr/sbin/swanctl --load-all",
"ExecStart=/bin/sh -ec '/usr/sbin/ip tunnel add " + greParameters + '; trap "/usr/sbin/ip link del dev ' + id +
'" EXIT; /usr/sbin/' + addressCommand + "; /usr/sbin/ip link set " + id + " up; trap - EXIT'",
"ExecStop=/usr/sbin/ip link del dev " + id,
"[Install]", "WantedBy=multi-user.target", "IX_GRE_UNIT",
'if [ -e "$unit" ] && ! cmp -s "$candidate" "$unit"; then echo "Служба уже принадлежит другой конфигурации."; exit 1; fi',
'if [ -e "$profile" ] && ! cmp -s "$conf" "$profile"; then echo "Профиль strongSwan отличается от существующего."; exit 1; fi',
'if [ ! -e "$unit" ] && ip link show dev ' + id + ' >/dev/null 2>&1; then echo "Интерфейс уже существует."; exit 1; fi',
'install -d -m 0700 /etc/swanctl/conf.d',
'if [ ! -e "$profile" ]; then install -m 0600 "$conf" "$profile"; fi',
'install -m 0644 "$candidate" "$unit"',
"systemctl daemon-reload", "systemctl enable --now ix-gre-" + id + ".service",
].join("\n")
return { return {
filename: id + ".conf", filename: id + ".conf",
template: [ template: [
"# Сверьте предложения и идентификаторы IKE с профилем узла IX.", ...(tunnel ? [] : ["# Сверьте предложения и идентификаторы IKE с профилем узла IX."]),
"connections {", "connections {",
" " + id + " {", " " + id + " {",
" version = 2", " version = 2",
@@ -97,28 +136,36 @@ export function ixGreClientTemplate(binding: Binding, serverId: number, bgp?: {
"}", "}",
"", "",
].join("\n"), ].join("\n"),
setup: [ setup: transportSetup || (tunnel ? [
"swanctl --load-all", 'conf="$(dirname -- "$0")/' + id + '.conf"',
"swanctl --initiate --child " + id, 'if [ ! -r "$conf" ]; then echo "Положите файл ' + id + '.conf рядом со скриптом" >&2; exit 1; fi',
"# Создайте GRE после успешного установления IPsec.", 'if ip link show dev ' + id + ' >/dev/null 2>&1; then echo "GRE уже поднят" >&2; exit 1; fi',
"ip tunnel add " + id + " mode gre local " + client + " remote " + hub, 'install -d -m 0700 /etc/swanctl/conf.d',
tunnel ? "ip address add " + tunnel.peerAddress + (family === 4 ? "/32" : "/128") + " dev " + id : 'install -m 0600 "$conf" /etc/swanctl/conf.d/' + id + '.conf',
bgp ? "ip address add " + bgp.address + hostMask + " dev " + id : "# Назначьте согласованный адрес Linux внутри туннеля.", "cleanup() {",
" " + protocol + " rule del pref " + (management + 1) + " lookup " + table + " 2>/dev/null || :",
" ip link del dev " + id + " 2>/dev/null || :",
...managementRules.map(([ip, selector]) => " " + ip + " rule del pref " + management + " " + selector + " 2>/dev/null || :"),
" swanctl --terminate --ike " + id + " --timeout 5 >/dev/null 2>&1 || :",
"}",
"trap cleanup 0",
...managementRules.map(([ip, selector]) => ip + " rule add pref " + management + " " + selector),
...common,
addressCommand!,
"ip link set " + id + " up",
...[...new Set([
tunnel.localAddress.split("/")[0] + (family === 4 ? "/32" : "/128"),
...(binding.linux?.destinations ?? []).map(canonicalBgpPolicyPrefix),
...(bgp && isIP(bgp.localAddress) === family ? [bgp.localAddress + hostMask] : []),
...(binding.linux?.exit ? ["default"] : []),
])].map(prefix => protocol + " route replace " + prefix + " dev " + id + " src " + tunnel.peerAddress + " table " + table),
protocol + " rule add pref " + (management + 1) + " lookup " + table,
"trap - 0",
] : [
...common,
bgp ? "ip address add " + bgp.address + hostMask + " dev " + id : "# Назначьте согласованный адрес Linux внутри туннеля.",
"ip link set " + id + " up", "ip link set " + id + " up",
...(tunnel ? [
protocol + " route replace " + local + (family === 4 ? "/32" : "/128") + " dev " + id + " src " + tunnel.peerAddress,
...(binding.linux?.destinations ?? []).map(prefix => protocol + " route replace " + prefix + " dev " + id + " src " + tunnel.peerAddress),
...(binding.linux?.exit ? [
protocol + " route replace default dev " + id + " src " + tunnel.peerAddress + " table " + table,
...(family === 4 ? [
"ip -4 rule add pref " + management + " to " + hub + "/32 lookup main",
"ip -4 rule add pref " + management + " from " + client + "/32 lookup main",
] : []),
protocol + " rule add pref " + (management + 1) + " lookup " + table,
"# Удаление политик: " + protocol + " rule del pref " + (management + 1) + " lookup " + table,
] : []),
] : []),
...(bgp ? ["ip route add " + bgp.localAddress + hostMask + " dev " + id + " src " + bgp.address] : []), ...(bgp ? ["ip route add " + bgp.localAddress + hostMask + " dev " + id + " src " + bgp.address] : []),
].join("\n"), ]).join("\n"),
} }
} }
@@ -14,6 +14,26 @@ const route: IxRouterObject = {
} }
const device = (rows: Record<string, Array<Record<string, string>>>) => [{ serverId: 17, source: "", rows }] const device = (rows: Record<string, Array<Record<string, string>>>) => [{ serverId: 17, source: "", rows }]
test("managed MSS rules are backfilled and removed without adopting a hand-written rule", () => {
const path = "/ip/firewall/mangle"
const from = { serverId: 17, path, fields: { comment: name + ":linux-mss-from-il-wg", action: "change-mss",
chain: "prerouting", "in-interface": "il-wg", "new-mss": "1380", "tcp-mss": "1381-65535" } }
const to = { serverId: 17, path, fields: { comment: name + ":linux-mss-to-il-wg", action: "change-mss",
chain: "postrouting", "out-interface": "il-wg", "new-mss": "1380", "tcp-mss": "1381-65535" } }
const manual = { ...to.fields, comment: "manual MSS", ".id": "*A" }
const fromRow = { ...from.fields, ".id": "*B" }
const toRow = { ...to.fields, ".id": "*C" }
const desired = [from, to]
const live = (rows: Array<Record<string, string>>) => device({ [path]: rows })
assert.deepEqual(planIxNative(id, desired, desired, live([manual])).map(task => [task.fields, task.placeBefore]),
[[from.fields, "*A"], [to.fields, "*A"]])
assert.deepEqual(planIxNative(id, desired, desired, live([fromRow, manual])).map(task => task.fields), [to.fields])
assert.deepEqual(planIxNative(id, desired, desired, live([fromRow, toRow, manual])), [])
assert.deepEqual(planIxNative(id, [], desired, live([fromRow, toRow, manual])).map(task => task.rosId), ["*C", "*B"])
assert.throws(() => planIxNative(id, desired, [], live([fromRow, manual])), /незавершённой операции/)
assert.throws(() => planIxNative(id, desired, desired, live([{ ...fromRow, "new-mss": "1460" }, toRow])), /изменён вне операции/)
})
test("a new VRF is inserted before main and no foreign route is altered", () => { test("a new VRF is inserted before main and no foreign route is altered", () => {
const changes = planIxNative(id, [vrf, route], [], device({ const changes = planIxNative(id, [vrf, route], [], device({
"/ip/vrf": [{ ".id": "*A", name: "main", interfaces: "all", builtin: "true" }], "/ip/vrf": [{ ".id": "*A", name: "main", interfaces: "all", builtin: "true" }],
@@ -9,9 +9,10 @@ import { getServerRowById, type ServerRow } from "../modules/servers/repository/
import { withApplicationMutationLock, withConfigMutationLock } from "./config-mutation-lock.js" import { withApplicationMutationLock, withConfigMutationLock } from "./config-mutation-lock.js"
import { assertVerifiedConfigurationAccess } from "./config-mutation-policy.js" import { assertVerifiedConfigurationAccess } from "./config-mutation-policy.js"
import { compileIxConfiguration, inIxNetwork, IxConflict, ixClientRoutingTable, ixDeviceIds, ixDiscardInterface, ixEgressList, ixNamespace } from "./internet-exchange-plan.js" import { compileIxConfiguration, inIxNetwork, IxConflict, ixClientRoutingTable, ixDeviceIds, ixDiscardInterface, ixEgressList, ixNamespace } from "./internet-exchange-plan.js"
import { archiveIxSegment, assertIxName, assertIxRevision, assertIxRouterIds, assertIxSites, ixReservedRouterIds, ixReservedTunnelBindings, nextIxRouterId, readIxRevision, readIxSegment, writeIxRevision } from "./internet-exchange-store.js" import { archiveIxSegment, assertIxBondClientAssignments, assertIxName, assertIxRevision, assertIxRouterIds, assertIxSites, assertIxSegmentWithoutBonds, ixBondClientId, ixKnownVpsClient, ixReservedLinuxPoolBlocks, ixReservedRouterIds, ixReservedTunnelBindings, nextIxRouterId, readIxRevision, readIxSegment, writeIxRevision } from "./internet-exchange-store.js"
import { MikrotikClient } from "./mikrotik.js" import { MikrotikClient } from "./mikrotik.js"
import { ixGreClientTemplate, ixLinuxBindingKind, ixLinuxInterfaceName, ixWireguardClientTemplate } from "./internet-exchange-client.js" import { ixGreClientTemplate, ixLegacyWireguardRoutes, ixLinuxBindingKind, ixLinuxInterfaceName, ixWireguardClientTemplate } from "./internet-exchange-client.js"
import { ixWireguardPublicKey, type IxExistingTransport } from "@mmapp/contracts/internet-exchange"
type NativeRow = Record<string, string> type NativeRow = Record<string, string>
type IpCore = Pick<MikrotikClient, "get" | "put" | "patch" | "delete"> type IpCore = Pick<MikrotikClient, "get" | "put" | "patch" | "delete">
@@ -27,6 +28,23 @@ interface IxNativeChange {
tasks: Task[] tasks: Task[]
} }
function wireguardKeys(seed: string) {
const scalar = Buffer.from(seed, "hex")
scalar[0] &= 248
scalar[31] = (scalar[31] & 127) | 64
const der = Buffer.concat([Buffer.from("302e020100300506032b656e04220420", "hex"), scalar])
const key = createPrivateKey({ key: der, format: "der", type: "pkcs8" })
return {
privateKey: scalar.toString("base64"),
publicKey: createPublicKey(key).export({ format: "der", type: "spki" }).subarray(-32).toString("base64"),
}
}
async function ixLinuxWireguardKeys(segmentId: string, serverId: number, name: string, credentialId: string, create = false) {
const derive = await (create ? privateFingerprinter : privateFingerprinterExisting)("ix-linux-wireguard-credential-v1")
return wireguardKeys(derive([segmentId, serverId, name, credentialId].join(":")))
}
const nativePlanDigest = ({ before, tasks }: IxNativeChange) => fingerprint({ before, tasks }) const nativePlanDigest = ({ before, tasks }: IxNativeChange) => fingerprint({ before, tasks })
const routerId = /^\*[a-z\d]+$/i const routerId = /^\*[a-z\d]+$/i
@@ -80,6 +98,9 @@ export function planIxNative(id: string, desired: IxRouterObject[], previous: Ix
rows.some(row => egressObject(row.comment)))).map(device => device.serverId)) rows.some(row => egressObject(row.comment)))).map(device => device.serverId))
// An older applied revision had no egress list. A partial set still needs reconciliation. // An older applied revision had no egress list. A partial set still needs reconciliation.
previous = previous.filter(object => !egressObject(object.fields.comment) || withEgressList.has(object.serverId)) previous = previous.filter(object => !egressObject(object.fields.comment) || withEgressList.has(object.serverId))
// Older revisions were compiled without MSS rules. Backfill only absent managed MSS rules.
previous = previous.filter(object => !object.fields.comment?.startsWith(namespace + ":linux-mss-") ||
devices.some(device => device.serverId === object.serverId && managedRow(device, object)))
const desiredKeys = new Set(desired.map(deviceMarker)) const desiredKeys = new Set(desired.map(deviceMarker))
const previousByKey = new Map(previous.map(object => [deviceMarker(object), object])) const previousByKey = new Map(previous.map(object => [deviceMarker(object), object]))
const result: Task[] = [] const result: Task[] = []
@@ -149,6 +170,10 @@ function verifyEgressMembers(device: NativeDevice, id: string, objects: IxRouter
async function readRows(client: IpCore, path: string, props: readonly string[]) { async function readRows(client: IpCore, path: string, props: readonly string[]) {
const raw = await client.get<unknown>(path + "?" + new URLSearchParams({ ".proplist": [...new Set(props)].join(",") })) const raw = await client.get<unknown>(path + "?" + new URLSearchParams({ ".proplist": [...new Set(props)].join(",") }))
return nativeRows(raw, props)
}
function nativeRows(raw: unknown, props: readonly string[]) {
if (!Array.isArray(raw) || raw.length > 10000 || raw.some(value => !value || typeof value !== "object" || Array.isArray(value))) { if (!Array.isArray(raw) || raw.length > 10000 || raw.some(value => !value || typeof value !== "object" || Array.isArray(value))) {
throw new IxConflict("Не удалось прочитать полный каталог RouterOS") throw new IxConflict("Не удалось прочитать полный каталог RouterOS")
} }
@@ -243,6 +268,39 @@ export async function assignIxRouterIds(id: string, configuration: IxConfigurati
} }
export async function configureIxLinuxClient(segment: IxSegment, input: IxLinuxClientRequest) { export async function configureIxLinuxClient(segment: IxSegment, input: IxLinuxClientRequest) {
if (input.vpsClientId && !await ixKnownVpsClient(input.vpsClientId)) throw new IxConflict("VPS больше не зарегистрирован в применённой конфигурации IX")
if (input.additionalGre && (isIP(input.peerEndpoint ?? "") !== 4 || isIP(input.hubEndpoint) !== 4)) {
throw new IxConflict("Для подключения по обоим протоколам укажите два внешних IPv4-адреса", 400)
}
const site = segment.configuration.sites.find(candidate => candidate.serverId === input.serverId)
const companion = input.companionOf && site?.interfaces.find(binding => binding.name === input.companionOf && binding.linux)
if (input.companionOf && !companion) throw new IxConflict("Исходное подключение Linux не найдено", 404)
if (input.interfaceName && input.vpsClientId) {
const groupVps = await ixBondClientId(segment.id, input.serverId, input.interfaceName)
if (groupVps && groupVps !== input.vpsClientId) throw new IxConflict("Сначала исключите подключение из действующей группы VPS")
}
const existingId = companion ? companion.linux?.clientId ?? await ixBondClientId(segment.id, input.serverId, companion.name) : undefined
const name = companion ? companion.linux!.name : input.name
const first = await configureIxLinuxTunnel(segment, { ...input, name })
const second = input.additionalGre ? await configureIxLinuxTunnel({ ...segment, configuration: first.configuration }, {
...input, kind: "gre-ipsec", localAddress: undefined, peerAddress: undefined, peerPublicKey: undefined, prefixes: [],
}) : undefined
const result = second ?? first
const currentId = site?.interfaces.find(binding => binding.name === input.interfaceName)?.linux?.clientId
const clientId = existingId ?? input.vpsClientId ?? currentId ??
(input.interfaceName ? await ixBondClientId(segment.id, input.serverId, input.interfaceName) : undefined) ?? randomUUID()
const siblings = new Set([first.interfaceName, second?.interfaceName, companion ? companion.name : undefined])
return { interfaceName: first.interfaceName, configuration: {
...result.configuration,
sites: result.configuration.sites.map(site => site.serverId !== input.serverId ? site : {
...site, interfaces: site.interfaces.map(binding =>
binding.linux && (siblings.has(binding.name) || !input.vpsClientId && binding.linux.clientId === clientId)
? { ...binding, linux: { ...binding.linux, name, clientId } } : binding),
}),
} }
}
async function configureIxLinuxTunnel(segment: IxSegment, input: IxLinuxClientRequest) {
const site = segment.configuration.sites.find(candidate => candidate.serverId === input.serverId) const site = segment.configuration.sites.find(candidate => candidate.serverId === input.serverId)
if (!site) throw new IxConflict("Узел не входит в сегмент IX", 404) if (!site) throw new IxConflict("Узел не входит в сегмент IX", 404)
const previous = site.interfaces.find(binding => binding.name === input.interfaceName && binding.linux) const previous = site.interfaces.find(binding => binding.name === input.interfaceName && binding.linux)
@@ -255,11 +313,13 @@ export async function configureIxLinuxClient(segment: IxSegment, input: IxLinuxC
let localAddress = input.localAddress ?? currentTunnel?.localAddress let localAddress = input.localAddress ?? currentTunnel?.localAddress
let peerAddress = input.peerAddress ?? currentTunnel?.peerAddress let peerAddress = input.peerAddress ?? currentTunnel?.peerAddress
if (!localAddress && !peerAddress) { if (!localAddress && !peerAddress) {
const occupiedBlocks = await ixReservedLinuxPoolBlocks()
const used = inventory.interfaces.flatMap(item => item.addresses).concat(reserved const used = inventory.interfaces.flatMap(item => item.addresses).concat(reserved
.concat(segment.configuration.sites.filter(candidate => candidate !== site).flatMap(candidate => candidate.interfaces)) .concat(segment.configuration.sites.flatMap(candidate => candidate.interfaces))
.flatMap(binding => [binding.provisionWireguard?.localAddress, binding.provisionGre?.localAddress, .flatMap(binding => [binding.provisionWireguard?.localAddress, binding.provisionGre?.localAddress,
binding.provisionTransit?.localAddress, ...binding.prefixes].filter(value => value !== undefined))) binding.provisionTransit?.localAddress, ...binding.prefixes].filter(value => value !== undefined)))
for (let index = 0; index < 65536; index += 4) { for (let index = 0; index < 65536; index += 4) {
if (occupiedBlocks.has(index)) continue
const base = "10.254." + (index >> 8) + "." const base = "10.254." + (index >> 8) + "."
const next = base + ((index & 255) + 1) + "/30" const next = base + ((index & 255) + 1) + "/30"
if (used.some(network => inIxNetwork(network, next) || inIxNetwork(next, network))) continue if (used.some(network => inIxNetwork(network, next) || inIxNetwork(next, network))) continue
@@ -269,10 +329,19 @@ export async function configureIxLinuxClient(segment: IxSegment, input: IxLinuxC
} }
} }
if (!localAddress || !peerAddress) throw new IxConflict("Укажите оба адреса туннеля или оставьте их для автоматического подбора", 400) if (!localAddress || !peerAddress) throw new IxConflict("Укажите оба адреса туннеля или оставьте их для автоматического подбора", 400)
const ports = new Set([...inventory.wireguardPorts, ...reserved.map(binding => binding.provisionWireguard?.listenPort)]) const ports = new Set(inventory.wireguardPorts)
for (const binding of [...reserved, ...site.interfaces]) {
if (binding.provisionWireguard) ports.add(binding.provisionWireguard.listenPort)
if (binding.provisionTransit) {
ports.add(binding.provisionTransit.localPort)
ports.add(binding.provisionTransit.remotePort)
}
}
let listenPort = 51820 let listenPort = 51820
while (ports.has(listenPort) && listenPort <= 65535) listenPort++ while (ports.has(listenPort) && listenPort <= 65535) listenPort++
const name = previous?.name ?? "il-" + randomUUID().replace(/-/g, "").slice(0, 12) const slug = input.name.normalize("NFKD").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "").slice(0, 24).replace(/-$/, "")
const transport = input.kind === "wireguard" ? "wg" : "gre"
const name = previous?.name ?? ["il", transport, slug || "vps", randomUUID().replace(/-/g, "").slice(0, 12)].join("-")
const family = isIP(peerAddress) const family = isIP(peerAddress)
const localExit = "ix-wan" + family const localExit = "ix-wan" + family
const groups = [...site.groups] const groups = [...site.groups]
@@ -289,16 +358,26 @@ export async function configureIxLinuxClient(segment: IxSegment, input: IxLinuxC
} }
const binding: IxSite["interfaces"][number] = { const binding: IxSite["interfaces"][number] = {
name, kind: input.kind, prefixes: input.prefixes, name, kind: input.kind, prefixes: input.prefixes,
linux: { name: input.name, enabled: input.enabled, destinations: input.destinations, peerEndpoint: input.peerEndpoint, linux: { name: input.name, clientId: previous?.linux?.clientId, enabled: input.enabled, destinations: input.destinations, peerEndpoint: input.peerEndpoint,
exit: input.exit === "local-wan" ? localExit : input.exit }, tunnelMtu: input.tunnelMtu ?? previous?.linux?.tunnelMtu, exit: input.exit === "local-wan" ? localExit : input.exit },
} }
if (input.kind === "wireguard") { if (input.kind === "wireguard") {
const publicKey = input.peerPublicKey ?? previous?.provisionWireguard?.peerPublicKey const existing = previous?.provisionWireguard
if (!publicKey || !previous?.provisionWireguard && listenPort > 65535) throw new IxConflict("Нужен публичный ключ и свободный порт WireGuard", 400) if (!existing && listenPort > 65535) throw new IxConflict("Нет свободного порта WireGuard", 400)
binding.provisionWireguard = { peerPublicKey: publicKey, listenPort: previous?.provisionWireguard?.listenPort ?? listenPort, let peerPublicKey = input.peerPublicKey ?? existing?.peerPublicKey
let credentialId = peerPublicKey === existing?.peerPublicKey ? existing?.credentialId : undefined
if (!peerPublicKey) {
credentialId = randomUUID()
peerPublicKey = (await ixLinuxWireguardKeys(segment.id, site.serverId, name, credentialId, true)).publicKey
}
binding.provisionWireguard = { peerPublicKey, credentialId, listenPort: existing?.listenPort ?? listenPort,
localAddress, peerAddress, hubEndpoint: input.hubEndpoint } localAddress, peerAddress, hubEndpoint: input.hubEndpoint }
} else { } else {
if (isIP(input.peerEndpoint ?? "") !== 4 || isIP(input.hubEndpoint) !== 4) throw new IxConflict("Укажите два внешних IPv4 для GRE/IPsec", 400) if (isIP(input.peerEndpoint ?? "") !== 4 || isIP(input.hubEndpoint) !== 4) throw new IxConflict("Укажите два внешних IPv4 для GRE/IPsec", 400)
if (site.interfaces.some(item => item !== previous && item.kind === "gre-ipsec" &&
item.localEndpoint === input.hubEndpoint && item.endpoint === input.peerEndpoint)) {
throw new IxConflict("Эта пара внешних адресов уже используется для GRE/IPsec")
}
binding.endpoint = input.peerEndpoint binding.endpoint = input.peerEndpoint
binding.localEndpoint = input.hubEndpoint binding.localEndpoint = input.hubEndpoint
binding.provisionGre = { localAddress, peerAddress, binding.provisionGre = { localAddress, peerAddress,
@@ -410,12 +489,78 @@ function verifyGreBinding(binding: IxSite["interfaces"][number], interfaces: Nat
return gre return gre
} }
function validateBindings(configuration: IxConfiguration, id: string, devices: NativeDevice[]) { /** Inspect operator-owned transports without running the provisioning or VRF planner. */
export async function verifyIxExistingTransport(segmentId: string, serverId: number, name: string, path: IxExistingTransport) {
const client = await requiredIxNode(serverId)
const addrPath = (address: string) => isIP(address) === 4 ? "/ip/address" : "/ipv6/address"
const readAddresses = (ip: string) => readRows(client, addrPath(ip), ["address", "network", "interface", "vrf", "disabled", "invalid"])
const [addresses, vrfs, reserved] = await Promise.all([readAddresses(path.probe), readRows(client, "/ip/vrf", ["name", "interfaces", "disabled"]), ixReservedTunnelBindings(serverId, segmentId)])
if (reserved.some(b => b.name === name)) throw new IxConflict("Интерфейс уже закреплён за другим сегментом: " + name)
const sameIP = (a: string | undefined, b: string) => !!a && isIP(a) === isIP(b) &&
inIxNetwork(b + (isIP(b) === 4 ? "/32" : "/128"), a)
const local = addresses.find(row => !isTrue(row.disabled) && !isTrue(row.invalid) && row.interface === name && sameIP(row.address?.split("/")[0], path.probe))
if (!local) throw new IxConflict("Адрес IX для проверки не назначен интерфейсу " + name)
const allowedVrf = (value: string) => value === "main" || value === ixNamespace(segmentId)
if (local.vrf) {
if (!allowedVrf(local.vrf)) throw new IxConflict("Адрес принадлежит другой VRF: " + name)
} else {
const names = new Set((await readRows(client, "/interface", ["name"])).map(row => row.name))
let owner: string | undefined
for (const row of vrfs.filter(v => !isTrue(v.disabled))) {
const selectors = row.interfaces?.split(",") ?? []
if (selectors.some(s => s === name || s === "all")) { owner = row.name; break }
// Older RouterOS may omit address.vrf. An unexpanded list could match before main.
if (selectors.some(s => s !== "none" && !names.has(s))) break
}
if (!owner || !allowedVrf(owner)) throw new IxConflict("Не подтверждена принадлежность интерфейса VRF узла: " + name)
}
if (path.kind === "gre-ipsec") {
const [interfaces, policies] = await Promise.all([readRows(client, "/interface/gre", [...greColumns, "disabled"]),
readRows(client, "/ip/ipsec/policy", ipsecPolicyColumns)])
const gre = verifyGreBinding({ name, kind: path.kind, localEndpoint: path.endpoint, endpoint: path.remoteEndpoint, prefixes: [] }, interfaces, policies)
if (isTrue(gre.disabled)) throw new IxConflict("Интерфейс отключён: " + name)
if (!sameIP(local.network, path.address) && !inIxNetwork(local.address, path.address)) {
const routes = await readRows(client, isIP(path.address) === 4 ? "/ip/route" : "/ipv6/route", ["dst-address", "gateway", "immediate-gw", "disabled"])
const host = path.address + (isIP(path.address) === 4 ? "/32" : "/128")
if (!routes.some(r => !isTrue(r.disabled) && r["dst-address"] === host &&
[r.gateway, r["immediate-gw"]].some(gw => gw?.split("@")[0] === name || gw?.split("%")[1]?.split("@")[0] === name))) {
throw new IxConflict("Адрес VPS не подтверждён подсетью или хост-маршрутом GRE: " + name)
}
}
return undefined
}
const [wireguard, peers, outer] = await Promise.all([readRows(client, "/interface/wireguard", ["name", "public-key", "disabled"]),
readRows(client, "/interface/wireguard/peers", ["interface", "public-key", "allowed-address", "disabled"]),
addrPath(path.endpoint) === addrPath(path.probe) ? addresses : readAddresses(path.endpoint)])
if (!outer.some(r => !isTrue(r.disabled) && !isTrue(r.invalid) && r.interface !== name && sameIP(r.address?.split("/")[0], path.endpoint))) {
throw new IxConflict("Внешний адрес WireGuard не найден на узле IX")
}
const hub = wireguard.find(r => r.name === name && !isTrue(r.disabled))
const peer = peers.find(r => r.interface === name && !isTrue(r.disabled) && r["public-key"] === path.clientPublicKey &&
r["allowed-address"]?.split(",").some(cidr => cidr.includes("/") && inIxNetwork(cidr.trim(), path.address)))
if (!peer || !ixWireguardPublicKey.safeParse(hub?.["public-key"]).success) throw new IxConflict("Не подтверждены WireGuard, публичный ключ VPS или allowed-address на " + name)
return hub!["public-key"]
}
function validateBindings(configuration: IxConfiguration, id: string, devices: NativeDevice[], knownObjects: IxRouterObject[]) {
for (const site of configuration.sites) { for (const site of configuration.sites) {
const device = devices.find(entry => entry.serverId === site.serverId)! const device = devices.find(entry => entry.serverId === site.serverId)!
if (rowsFor(device, "/interface/bridge/port").some(row => row.bridge === ixDiscardInterface(id))) { if (rowsFor(device, "/interface/bridge/port").some(row => row.bridge === ixDiscardInterface(id))) {
throw new IxConflict("Изолированный bridge отбрасывания IX содержит порты") throw new IxConflict("Изолированный bridge отбрасывания IX содержит порты")
} }
// Активация WAN-выхода создаёт в main обратный маршрут через клиентский туннель.
const ownedMainRoutes = new Map<string, IxRouterObject[]>()
for (const object of knownObjects) {
if (object.serverId !== site.serverId || !["/ip/route", "/ipv6/route"].includes(object.path) || object.fields["routing-table"] !== "main") continue
const key = objectMarker(object)
const known = ownedMainRoutes.get(key) ?? []
known.push(object)
ownedMainRoutes.set(key, known)
}
const foreignMainRoutes = ["/ip/route", "/ipv6/route"].flatMap(path => rowsFor(device, path).filter(row => {
if (row["routing-table"] !== "main" || isTrue(row.dynamic)) return false
return !ownedMainRoutes.get(marker(path, row.comment ?? ""))?.some(known => matches(row, known.fields))
}))
for (const binding of site.interfaces) { for (const binding of site.interfaces) {
const iface = rowsFor(device, "/interface").find(row => row.name === binding.name) const iface = rowsFor(device, "/interface").find(row => row.name === binding.name)
if (!iface && (binding.provisionWireguard || binding.provisionGre || binding.provisionTransit)) continue if (!iface && (binding.provisionWireguard || binding.provisionGre || binding.provisionTransit)) continue
@@ -433,8 +578,8 @@ function validateBindings(configuration: IxConfiguration, id: string, devices: N
throw new IxConflict("Интерфейс " + binding.name + " не выделен для данного сегмента IX") throw new IxConflict("Интерфейс " + binding.name + " не выделен для данного сегмента IX")
} }
const foreignVrf = rowsFor(device, "/ip/vrf").find(row => row.name !== "main" && row.name !== ixNamespace(id) && row.interfaces?.split(",").includes(binding.name)) const foreignVrf = rowsFor(device, "/ip/vrf").find(row => row.name !== "main" && row.name !== ixNamespace(id) && row.interfaces?.split(",").includes(binding.name))
const mainRoutes = [...rowsFor(device, "/ip/route"), ...rowsFor(device, "/ipv6/route")].filter(row => row["routing-table"] === "main" && !isTrue(row.dynamic)) if (foreignVrf || foreignMainRoutes.some(row => row.gateway?.split(",").some(gateway =>
if (foreignVrf || mainRoutes.some(row => row.gateway === binding.name || row.gateway?.includes("%" + binding.name))) { gateway.trim().split("@")[0].split("%").at(-1) === binding.name))) {
throw new IxConflict("Интерфейс " + binding.name + " уже используется другой маршрутизацией") throw new IxConflict("Интерфейс " + binding.name + " уже используется другой маршрутизацией")
} }
if (binding.kind === "gre-ipsec") { if (binding.kind === "gre-ipsec") {
@@ -473,20 +618,23 @@ async function resolveIxCredentials(id: string, objects: IxRouterObject[], exist
if (name === "secret" && psk && value.startsWith("ix-credential:")) return [name, psk(id + ":" + object.serverId + ":" + value)] if (name === "secret" && psk && value.startsWith("ix-credential:")) return [name, psk(id + ":" + object.serverId + ":" + value)]
if (wg && ["public-key", "private-key"].includes(name) && value.startsWith("ix-transit:")) { if (wg && ["public-key", "private-key"].includes(name) && value.startsWith("ix-transit:")) {
const [, variant, version, side] = value.split(":") const [, variant, version, side] = value.split(":")
const raw = Buffer.from(wg([id, version, side].join(":")), "hex") const keys = wireguardKeys(wg([id, version, side].join(":")))
const scalar = Buffer.from(raw) return [name, variant === "private" ? keys.privateKey : keys.publicKey]
scalar[0] &= 248
scalar[31] = (scalar[31] & 127) | 64
if (variant === "private") return [name, scalar.toString("base64")]
const der = Buffer.concat([Buffer.from("302e020100300506032b656e04220420", "hex"), scalar])
const privateKey = createPrivateKey({ key: der, format: "der", type: "pkcs8" })
return [name, createPublicKey(privateKey).export({ format: "der", type: "spki" }).subarray(-32).toString("base64")]
} }
return [name, value] return [name, value]
})) })) })) }))
} }
async function prepareNative(id: string, configuration: IxConfiguration | null, previousConfiguration: IxConfiguration | null, resume = false): Promise<IxNativeChange> { async function prepareNative(id: string, configuration: IxConfiguration | null, previousConfiguration: IxConfiguration | null, resume = false): Promise<IxNativeChange> {
if (configuration) await assertIxBondClientAssignments(id, configuration)
for (const site of configuration?.sites ?? []) for (const binding of site.interfaces) {
const wg = binding.provisionWireguard
if (!wg?.credentialId) continue
const keys = await ixLinuxWireguardKeys(id, site.serverId, binding.name, wg.credentialId)
if (!binding.linux || !constantEqual(keys.publicKey, wg.peerPublicKey)) {
throw new IxConflict("Ключ WireGuard не соответствует управляемому клиенту IX")
}
}
const previous = previousConfiguration ? await resolveIxCredentials(id, compileIxConfiguration(id, previousConfiguration), true) : [] const previous = previousConfiguration ? await resolveIxCredentials(id, compileIxConfiguration(id, previousConfiguration), true) : []
const objects = configuration ? await resolveIxCredentials(id, compileIxConfiguration(id, configuration), false) : [] const objects = configuration ? await resolveIxCredentials(id, compileIxConfiguration(id, configuration), false) : []
const before: NativeDevice[] = [] const before: NativeDevice[] = []
@@ -503,7 +651,7 @@ async function prepareNative(id: string, configuration: IxConfiguration | null,
before.push(await readDevice(server, [...objects, ...previous].filter(object => object.serverId === serverId), !configuration)) before.push(await readDevice(server, [...objects, ...previous].filter(object => object.serverId === serverId), !configuration))
verifyIxMainGateways(before.at(-1)!, objects.filter(object => object.serverId === serverId)) verifyIxMainGateways(before.at(-1)!, objects.filter(object => object.serverId === serverId))
} }
if (configuration) validateBindings(configuration, id, before) if (configuration) validateBindings(configuration, id, before, resume ? objects.concat(previous) : previous)
for (const device of before) verifyEgressMembers(device, id, resume ? previous.concat(objects) : previous) for (const device of before) verifyEgressMembers(device, id, resume ? previous.concat(objects) : previous)
for (const old of previousConfiguration?.sites ?? []) { for (const old of previousConfiguration?.sites ?? []) {
const next = configuration?.sites.find(site => site.serverId === old.serverId) const next = configuration?.sites.find(site => site.serverId === old.serverId)
@@ -538,12 +686,13 @@ async function assertIxResume(id: string, revision: number, native: IxNativeChan
function verifyRemovalScope(id: string, device: NativeDevice, previous: IxRouterObject[]) { function verifyRemovalScope(id: string, device: NativeDevice, previous: IxRouterObject[]) {
const namespace = ixNamespace(id) const namespace = ixNamespace(id)
const managed = previous.filter(object => object.serverId === device.serverId) const managed = previous.filter(object => object.serverId === device.serverId)
const known = new Set(managed.map(objectMarker)) const known = new Set(managed.filter(object => object.fields.comment).map(objectMarker))
const named = new Set(managed.filter(object => !object.fields.comment && object.fields.name).map(objectMarker))
const interfaces = new Set(managed.filter(object => ["/interface/wireguard", "/interface/bridge", "/ip/vrf"].includes(object.path)) const interfaces = new Set(managed.filter(object => ["/interface/wireguard", "/interface/bridge", "/ip/vrf"].includes(object.path))
.map(object => object.fields.name)) .map(object => object.fields.name))
for (const [path, rows] of Object.entries(device.rows)) { for (const [path, rows] of Object.entries(device.rows)) {
if (path === "/interface") continue // RouterOS mirrors WireGuard and bridge objects here. if (path === "/interface") continue // RouterOS mirrors WireGuard and bridge objects here.
if (rows.some(row => !isTrue(row.dynamic) && !known.has(marker(path, row.comment ?? "")) && if (rows.some(row => !isTrue(row.dynamic) && !known.has(marker(path, row.comment ?? "")) && !named.has(marker(path, row.name ?? "")) &&
(row.comment?.startsWith(namespace + ":") || row["routing-table"] === namespace || (row.comment?.startsWith(namespace + ":") || row["routing-table"] === namespace ||
[row.interface, row.bridge, row["in-interface"], row["out-interface"], ...(row.gateway?.split(/[@%]/) ?? [])].some(value => interfaces.has(value)) || [row.interface, row.bridge, row["in-interface"], row["out-interface"], ...(row.gateway?.split(/[@%]/) ?? [])].some(value => interfaces.has(value)) ||
[row["in-interface-list"], row["out-interface-list"]].includes(ixEgressList(id)) || [row["in-interface-list"], row["out-interface-list"]].includes(ixEgressList(id)) ||
@@ -554,6 +703,7 @@ function verifyRemovalScope(id: string, device: NativeDevice, previous: IxRouter
} }
export async function prepareIxRemoval(id: string, revision: number) { export async function prepareIxRemoval(id: string, revision: number) {
await assertIxSegmentWithoutBonds(id)
const segment = await readIxSegment(id) const segment = await readIxSegment(id)
if (!segment) throw new IxConflict("Сегмент IX не найден", 404) if (!segment) throw new IxConflict("Сегмент IX не найден", 404)
assertIxRevision(segment, revision) assertIxRevision(segment, revision)
@@ -660,29 +810,37 @@ export async function listIxLinuxClients(segment: IxSegment) {
const bindings = site.interfaces.filter(binding => ixLinuxBindingKind(binding) && !binding.peerServerId) const bindings = site.interfaces.filter(binding => ixLinuxBindingKind(binding) && !binding.peerServerId)
const items: IxLinuxBinding[] = bindings.map(binding => ({ const items: IxLinuxBinding[] = bindings.map(binding => ({
serverId: site.serverId, interfaceName: binding.name, kind: ixLinuxBindingKind(binding)!, serverId: site.serverId, interfaceName: binding.name, kind: ixLinuxBindingKind(binding)!,
...(binding.provisionWireguard?.credentialId && { managedWireguard: true }),
...(binding.linux && { name: binding.linux.name, enabled: binding.linux.enabled, policy: binding.linux }), ...(binding.linux && { name: binding.linux.name, enabled: binding.linux.enabled, policy: binding.linux }),
})) }))
if (!bindings.some(binding => binding.linux?.enabled)) return items if (!bindings.some(binding => binding.linux?.enabled)) return items
const observedAt = new Date().toISOString() const observedAt = new Date().toISOString()
try { try {
const client = await requiredIxNode(site.serverId) const client = await requiredIxNode(site.serverId)
const [peers, ipsec] = await Promise.all([ const hasGre = bindings.some(binding => binding.linux?.enabled && binding.provisionGre)
const counterFields = ["name", "rx-byte", "tx-byte"]
const [peers, ipsec, stats] = await Promise.all([
bindings.some(binding => binding.linux && binding.provisionWireguard) ? readRows(client, "/interface/wireguard/peers", bindings.some(binding => binding.linux && binding.provisionWireguard) ? readRows(client, "/interface/wireguard/peers",
["interface", "public-key", "last-handshake", "rx", "tx"]) : [], ["interface", "public-key", "last-handshake", "rx", "tx"]).catch(() => null) : [],
bindings.some(binding => binding.linux && binding.provisionGre) ? readRows(client, "/ip/ipsec/active-peers", ["remote-address", "state"]) : [], hasGre ? readRows(client, "/ip/ipsec/active-peers", ["remote-address", "state"]).catch(() => null) : [],
hasGre ? client.post<unknown>("/interface/print", { stats: "", ".proplist": counterFields })
.then(raw => nativeRows(raw, counterFields)).catch(() => []) : [],
]) ])
for (const [index, binding] of bindings.entries()) { for (const [index, binding] of bindings.entries()) {
if (!binding.linux?.enabled) continue if (!binding.linux?.enabled) continue
const peer = peers.find(row => row.interface === binding.name && row["public-key"] === binding.provisionWireguard?.peerPublicKey) const peer = peers?.find(row => row.interface === binding.name && row["public-key"] === binding.provisionWireguard?.peerPublicKey)
const handshake = peer?.["last-handshake"]?.trim() const handshake = peer?.["last-handshake"]?.trim()
const age = handshake && /^\d+:\d{2}:\d{2}$/.test(handshake) const age = handshake && /^\d+:\d{2}:\d{2}$/.test(handshake)
? handshake.split(":").reduce((total, part) => total * 60 + Number(part), 0) ? handshake.split(":").reduce((total, part) => total * 60 + Number(part), 0)
: handshake && /^(?:(\d+)m)?(?:(\d+)s)?$/.exec(handshake) : handshake && /^(?:(\d+)m)?(?:(\d+)s)?$/.exec(handshake)
const fresh = typeof age === "number" ? age < 180 : const fresh = typeof age === "number" ? age < 180 :
Array.isArray(age) && Number(age[1] ?? 0) * 60 + Number(age[2] ?? 0) < 180 Array.isArray(age) && Number(age[1] ?? 0) * 60 + Number(age[2] ?? 0) < 180
const established = binding.provisionGre && ipsec.some(row => row.state === "established" && const established = binding.provisionGre && ipsec?.some(row => row.state === "established" &&
(row["remote-address"] === binding.endpoint || row["remote-address"]?.startsWith(binding.endpoint + ":"))) (row["remote-address"] === binding.endpoint || row["remote-address"]?.startsWith(binding.endpoint + ":")))
items[index].connection = { observedAt, state: fresh || established ? "connected" : "waiting", ...(peer && { rx: peer.rx, tx: peer.tx }) } const iface = binding.provisionGre && stats.find(row => row.name === binding.name)
const state = fresh || established ? "connected" : (binding.provisionGre ? ipsec : peers) === null ? "unknown" : "waiting"
items[index].connection = { observedAt, state,
rx: peer?.rx ?? (iface ? iface["rx-byte"] : undefined), tx: peer?.tx ?? (iface ? iface["tx-byte"] : undefined) }
} }
} catch { } catch {
for (const item of items) if (item.enabled) item.connection = { observedAt, state: "unknown" } for (const item of items) if (item.enabled) item.connection = { observedAt, state: "unknown" }
@@ -715,7 +873,7 @@ export async function observeIxLinuxPath(segment: IxSegment, serverId: number, n
})) } })) }
} }
export async function readIxLinuxClient(segment: IxSegment, serverId: number, name: string, includeCredential = false): Promise<IxLinuxAccess> { export async function readIxLinuxClient(segment: IxSegment, serverId: number, name: string, includeCredential: boolean | "wireguard" = false, transportOnly = false, forImportLink = false): Promise<IxLinuxAccess & { greImport?: import("./ix-import-links.js").IxImportGre }> {
if (segment.appliedRevision === null) throw new IxConflict("Сначала примените конфигурацию площадки") if (segment.appliedRevision === null) throw new IxConflict("Сначала примените конфигурацию площадки")
const configuration = await readIxRevision(segment.id, segment.appliedRevision) const configuration = await readIxRevision(segment.id, segment.appliedRevision)
const site = configuration.sites.find(site => site.serverId === serverId) const site = configuration.sites.find(site => site.serverId === serverId)
@@ -723,6 +881,7 @@ export async function readIxLinuxClient(segment: IxSegment, serverId: number, na
const server = await getServerRowById(serverId) const server = await getServerRowById(serverId)
if (!site || !binding || !server?.enabled || server.type !== "ix-node") throw new IxConflict("Подключение IX не найдено", 404) if (!site || !binding || !server?.enabled || server.type !== "ix-node") throw new IxConflict("Подключение IX не найдено", 404)
if (binding.peerServerId || binding.linux?.enabled === false) throw new IxConflict("Клиентское подключение отключено или недоступно") if (binding.peerServerId || binding.linux?.enabled === false) throw new IxConflict("Клиентское подключение отключено или недоступно")
if (includeCredential === "wireguard" && binding.kind !== "wireguard") throw new IxConflict("Для скачивания выберите клиента WireGuard", 404)
const peer = site.neighbors.find(entry => entry.binding === name && entry.type !== "public-feed") const peer = site.neighbors.find(entry => entry.binding === name && entry.type !== "public-feed")
const clientInfo = { const clientInfo = {
revision: segment.appliedRevision, revision: segment.appliedRevision,
@@ -746,10 +905,18 @@ export async function readIxLinuxClient(segment: IxSegment, serverId: number, na
throw new IxConflict("Действующий PSK не совпал с применённой ревизией. Выполните сверку") throw new IxConflict("Действующий PSK не совпал с применённой ревизией. Выполните сверку")
} }
} }
return { ...clientInfo, kind: "gre-ipsec", ...ixGreClientTemplate(binding, serverId, peer, credential) } const access = ixGreClientTemplate(binding, serverId, peer, credential, transportOnly)
if (forImportLink && (!credential || !binding.provisionGre || !binding.endpoint || !binding.localEndpoint)) {
throw new IxConflict("Для импорта по ссылке нужен управляемый GRE/IPsec")
}
return { ...clientInfo, kind: "gre-ipsec", ...access,
...(forImportLink && credential && binding.provisionGre && binding.endpoint && binding.localEndpoint && {
greImport: { local: binding.endpoint, remote: binding.localEndpoint, address: binding.provisionGre.peerAddress, psk: credential },
}),
}
} }
if (ixLinuxBindingKind(binding) !== "wireguard") throw new IxConflict("Нет параметров WireGuard для Linux") if (ixLinuxBindingKind(binding) !== "wireguard") throw new IxConflict("Нет параметров WireGuard для Linux")
const wireguard = await readRows(client, "/interface/wireguard", ["name", "public-key", "comment", "disabled"]) const wireguard = await readRows(client, "/interface/wireguard", ["name", "public-key", "listen-port", "comment", "disabled"])
const iface = wireguard.find(row => row.name === binding.name && row.comment?.startsWith(ixNamespace(segment.id) + ":wg-") && !isTrue(row.disabled)) const iface = wireguard.find(row => row.name === binding.name && row.comment?.startsWith(ixNamespace(segment.id) + ":wg-") && !isTrue(row.disabled))
const peers = await readRows(client, "/interface/wireguard/peers", ["interface", "public-key", "comment", "disabled"]) const peers = await readRows(client, "/interface/wireguard/peers", ["interface", "public-key", "comment", "disabled"])
if (!peers.some(row => row.interface === name && row["public-key"] === binding.provisionWireguard?.peerPublicKey && if (!peers.some(row => row.interface === name && row["public-key"] === binding.provisionWireguard?.peerPublicKey &&
@@ -758,13 +925,24 @@ export async function readIxLinuxClient(segment: IxSegment, serverId: number, na
} }
const routes = binding.linux ? [...binding.linux.destinations, const routes = binding.linux ? [...binding.linux.destinations,
...(binding.linux.exit ? [isIP(binding.provisionWireguard!.peerAddress) === 4 ? "0.0.0.0/0" : "::/0"] : [])] ...(binding.linux.exit ? [isIP(binding.provisionWireguard!.peerAddress) === 4 ? "0.0.0.0/0" : "::/0"] : [])]
: configuration.sites.flatMap(entry => entry.interfaces : ixLegacyWireguardRoutes(configuration, binding)
.filter(connection => connection !== binding && connection.kind !== "uplink").flatMap(connection => connection.prefixes)) let privateKey: string | undefined
if (includeCredential) {
const wg = binding.provisionWireguard
if (!binding.linux || !wg?.credentialId) throw new IxConflict("Этот клиент использует собственный ключ WireGuard", 404)
const keys = await ixLinuxWireguardKeys(segment.id, serverId, name, wg.credentialId)
if (Number(iface?.["listen-port"]) !== wg.listenPort || !constantEqual(keys.publicKey, wg.peerPublicKey) ||
(await readIxSegment(segment.id))?.appliedRevision !== segment.appliedRevision) {
throw new IxConflict("Действующие параметры WireGuard не совпали с применённой ревизией. Выполните сверку")
}
privateKey = keys.privateKey
}
return { return {
...clientInfo, ...clientInfo,
kind: "wireguard", kind: "wireguard",
filename: ixLinuxInterfaceName("ixw", serverId, binding) + ".conf", filename: ixLinuxInterfaceName("ixw", serverId, binding) + ".conf",
template: ixWireguardClientTemplate(binding, iface?.["public-key"] ?? "", routes), hubPublicKey: iface?.["public-key"],
template: ixWireguardClientTemplate(binding, iface?.["public-key"] ?? "", routes, privateKey, transportOnly),
} }
} }
@@ -814,6 +992,7 @@ export async function removeIxSegment(id: string, revision: number, expectedDige
authorize = assertVerifiedConfigurationAccess) { authorize = assertVerifiedConfigurationAccess) {
return withApplicationMutationLock(async () => { return withApplicationMutationLock(async () => {
await authorize() await authorize()
await assertIxSegmentWithoutBonds(id)
const segment = await readIxSegment(id) const segment = await readIxSegment(id)
assertIxRevision(segment, revision) assertIxRevision(segment, revision)
const applied = segment?.appliedRevision ? await readIxRevision(id, segment.appliedRevision) : null const applied = segment?.appliedRevision ? await readIxRevision(id, segment.appliedRevision) : null
@@ -32,6 +32,8 @@ test("managed clients get their own return path and fail closed if both exit pro
provisionWireguard: { peerPublicKey: "A".repeat(43) + "=", listenPort: 51900, provisionWireguard: { peerPublicKey: "A".repeat(43) + "=", listenPort: 51900,
localAddress: "10.254.1.1/30", peerAddress: "10.254.1.2", hubEndpoint: "192.0.2.10" } }) localAddress: "10.254.1.1/30", peerAddress: "10.254.1.2", hubEndpoint: "192.0.2.10" } })
const objects = compileIxConfiguration(id, value) const objects = compileIxConfiguration(id, value)
const clamp = objects.findIndex(object => object.fields.comment === table + ":linux-mss-from-linux-wg")
assert.ok(clamp >= 0 && clamp < objects.findIndex(object => object.fields.comment === table + ":linux-linux-wg-route"))
const clientTable = ixClientRoutingTable(table, "linux-wg") const clientTable = ixClientRoutingTable(table, "linux-wg")
const defaults = objects.filter(object => object.fields["routing-table"] === clientTable) const defaults = objects.filter(object => object.fields["routing-table"] === clientTable)
assert.deepEqual(defaults.map(object => object.fields.distance), ["10", "11", "254"]) assert.deepEqual(defaults.map(object => object.fields.distance), ["10", "11", "254"])
@@ -45,6 +47,35 @@ test("managed clients get their own return path and fail closed if both exit pro
assert.ok(objects.every(object => object.path !== "/ip/vrf" || !object.fields.interfaces.includes("ether1"))) assert.ok(objects.every(object => object.path !== "/ip/vrf" || !object.fields.interfaces.includes("ether1")))
}) })
test("managed Linux tunnels clamp TCP SYN in both directions before routing marks can end prerouting", () => {
const value = fixture(), site = value.sites[0]
site.interfaces.push(
{ name: "linux-wg", kind: "wireguard", prefixes: [], linux: { name: "vps", enabled: true, destinations: [] },
provisionWireguard: { localAddress: "10.254.0.1/30", peerAddress: "10.254.0.2", listenPort: 51820, peerPublicKey: "A".repeat(43) + "=" } },
{ name: "linux-gre", kind: "gre-ipsec", prefixes: [], endpoint: "192.0.2.90", localEndpoint: "192.0.2.17",
linux: { name: "vps", enabled: false, destinations: [] },
provisionGre: { localAddress: "10.254.0.5/30", peerAddress: "10.254.0.6", credentialId: id } },
{ name: "linux-wg6", kind: "wireguard", prefixes: [],
linux: { name: "vps6", enabled: true, destinations: [], tunnelMtu: 1360 },
provisionWireguard: { localAddress: "fd00:254::1/126", peerAddress: "fd00:254::2", listenPort: 51821, peerPublicKey: "B".repeat(43) + "=" } },
)
const rules = compileIxConfiguration(id, ixSegmentConfigurationSchema.parse(value)).filter(object => object.fields.action === "change-mss")
assert.equal(rules.length, 6)
for (const [binding, family, mss, disabled] of [
["linux-wg", "ip", 1380, "false"], ["linux-gre", "ip", 1380, "true"], ["linux-wg6", "ipv6", 1300, "false"],
] as const) {
const list = ixClientRoutingTable(table, binding) + "-src"
const shared = { protocol: "tcp", "tcp-flags": "syn", "tcp-mss": (mss + 1) + "-65535",
action: "change-mss", "new-mss": String(mss), passthrough: "true", disabled }
assert.deepEqual(rules.filter(object => object.fields.comment.endsWith("-" + binding)), [
{ serverId: site.serverId, path: "/" + family + "/firewall/mangle",
fields: { ...shared, chain: "prerouting", "in-interface": binding, "src-address-list": list, comment: table + ":linux-mss-from-" + binding } },
{ serverId: site.serverId, path: "/" + family + "/firewall/mangle",
fields: { ...shared, chain: "postrouting", "out-interface": binding, "dst-address-list": list, comment: table + ":linux-mss-to-" + binding } },
])
}
})
test("a managed remote exit prepares both CHRs and returns only prefixes of users assigned to it", () => { test("a managed remote exit prepares both CHRs and returns only prefixes of users assigned to it", () => {
const value = fixture(), site = value.sites[0] const value = fixture(), site = value.sites[0]
site.interfaces.push({ name: "it-abc", kind: "wireguard", prefixes: [], peerServerId: 99, site.interfaces.push({ name: "it-abc", kind: "wireguard", prefixes: [], peerServerId: 99,
+13 -1
View File
@@ -84,6 +84,11 @@ function compileLinuxPolicy(namespace: string, site: IxSite, binding: IxSite["in
const permitted = privateTable + "-dst" const permitted = privateTable + "-dst"
const sourcesCidr = [...new Set([host(tunnel.peerAddress), ...binding.prefixes.map(canonicalBgpPolicyPrefix)])] const sourcesCidr = [...new Set([host(tunnel.peerAddress), ...binding.prefixes.map(canonicalBgpPolicyPrefix)])]
const destinations = [...new Set([host(tunnel.localAddress.split("/")[0]), ...policy.destinations.map(canonicalBgpPolicyPrefix)])] const destinations = [...new Set([host(tunnel.localAddress.split("/")[0]), ...policy.destinations.map(canonicalBgpPolicyPrefix)])]
// Use the WireGuard default as a conservative ceiling for both managed tunnel types.
const mss = (policy.tunnelMtu ?? 1420) - (family === 4 ? 40 : 60)
const clamp = { protocol: "tcp", "tcp-flags": "syn", "tcp-mss": (mss + 1) + "-65535",
action: "change-mss", "new-mss": String(mss), passthrough: "true", disabled: String(!policy.enabled) }
const mangle = ip + "/firewall/mangle"
const ingress = { chain: "prerouting", "in-interface": binding.name } const ingress = { chain: "prerouting", "in-interface": binding.name }
const exit = site.groups.find(group => group.id === policy.exit) const exit = site.groups.find(group => group.id === policy.exit)
const paths = exit ? groupPaths(exit) : [] const paths = exit ? groupPaths(exit) : []
@@ -114,6 +119,13 @@ function compileLinuxPolicy(namespace: string, site: IxSite, binding: IxSite["in
add(filter, key + "-allow-inbound", { ...inbound, "src-address-list": permitted, "in-interface": namespace, add(filter, key + "-allow-inbound", { ...inbound, "src-address-list": permitted, "in-interface": namespace,
action: "accept", disabled: String(!policy.enabled) }) action: "accept", disabled: String(!policy.enabled) })
add(filter, key + "-deny-inbound", { ...inbound, action: "drop" }) add(filter, key + "-deny-inbound", { ...inbound, action: "drop" })
// The real VRF member is visible before routing and after routing, respectively.
add(mangle, "linux-mss-from-" + binding.name, {
...clamp, ...ingress, "src-address-list": sources,
})
add(mangle, "linux-mss-to-" + binding.name, {
...clamp, chain: "postrouting", "out-interface": binding.name, "dst-address-list": sources,
})
if (!exit) return if (!exit) return
add("/routing/table", key + "-table", { name: privateTable, fib: "true" }) add("/routing/table", key + "-table", { name: privateTable, fib: "true" })
for (const [index, path] of paths.entries()) { for (const [index, path] of paths.entries()) {
@@ -122,7 +134,7 @@ function compileLinuxPolicy(namespace: string, site: IxSite, binding: IxSite["in
}) })
} }
add(routePath(family), key + "-default-drop", { "routing-table": privateTable, "dst-address": defaultRoute[family], blackhole: "yes", distance: "254" }) add(routePath(family), key + "-default-drop", { "routing-table": privateTable, "dst-address": defaultRoute[family], blackhole: "yes", distance: "254" })
add(ip + "/firewall/mangle", key + "-route", { ...ingress, "src-address-list": sources, "dst-address-list": "!" + permitted, add(mangle, key + "-route", { ...ingress, "src-address-list": sources, "dst-address-list": "!" + permitted,
action: "mark-routing", "new-routing-mark": privateTable, passthrough: "false", disabled: String(!policy.enabled) }) action: "mark-routing", "new-routing-mark": privateTable, passthrough: "false", disabled: String(!policy.enabled) })
const mainPaths = paths.filter(path => path.viaMain) const mainPaths = paths.filter(path => path.viaMain)
for (const [index, path] of mainPaths.entries()) { for (const [index, path] of mainPaths.entries()) {
@@ -14,7 +14,8 @@ interface SegmentRow {
updated_at: Date updated_at: Date
} }
const columns = "id,revision,applied_revision,configuration,updated_at" // VPS bond metadata has its own revision and never enters a RouterOS plan or segment export.
const columns = "id,revision,applied_revision,(configuration - 'linuxBonds') AS configuration,updated_at"
const visible = "(configuration->>'deleted') IS DISTINCT FROM 'true'" const visible = "(configuration->>'deleted') IS DISTINCT FROM 'true'"
function segment(row: SegmentRow): IxSegment { function segment(row: SegmentRow): IxSegment {
return { id: row.id, revision: row.revision, appliedRevision: row.applied_revision, return { id: row.id, revision: row.revision, appliedRevision: row.applied_revision,
@@ -41,6 +42,46 @@ export async function isIxSegmentArchived(id: string, revision: number) {
return rowCount === 1 return rowCount === 1
} }
export async function assertIxSegmentWithoutBonds(id: string) {
const { rowCount } = await pool.query(`SELECT 1 FROM ix_segments s
CROSS JOIN LATERAL jsonb_array_elements(s.configuration->'linuxBonds') g
WHERE (s.configuration->>'deleted') IS DISTINCT FROM 'true'
AND (s.id=$1::uuid OR EXISTS (SELECT FROM jsonb_array_elements(g->'members') m WHERE m->>'segmentId'=$1::text))
LIMIT 1`, [id])
if (rowCount) throw new IxConflict("Сначала исключите сегмент из групп туннелей Linux")
}
export async function ixBondClientId(segmentId: string, serverId: number, interfaceName: string) {
const { rows } = await pool.query<{ id: string }>(`SELECT g->>'clientId' AS id FROM ix_segments s
CROSS JOIN LATERAL jsonb_array_elements(s.configuration->'linuxBonds') g
WHERE (s.configuration->>'deleted') IS DISTINCT FROM 'true' AND g->'members' @> $1::jsonb LIMIT 1`,
[JSON.stringify([{ segmentId, serverId, interfaceName }])])
return rows[0]?.id
}
export async function ixKnownVpsClient(id: string) {
const { rowCount } = await pool.query(`SELECT 1 FROM ix_segments s
JOIN ix_segment_revisions r ON r.segment_id=s.id AND r.revision=s.applied_revision
WHERE (s.configuration->>'deleted') IS DISTINCT FROM 'true' AND
(s.configuration->'linuxBonds' @> $1::jsonb OR r.configuration->'sites' @> $2::jsonb) LIMIT 1`,
[JSON.stringify([{ clientId: id }]), JSON.stringify([{ interfaces: [{ linux: { clientId: id, enabled: true } }] }])])
return !!rowCount
}
export async function assertIxBondClientAssignments(segmentId: string, configuration: IxConfiguration) {
const assignments = configuration.sites.flatMap(site => site.interfaces.flatMap(binding => binding.linux?.clientId
? [{ server_id: site.serverId, iface: binding.name, client_id: binding.linux.clientId }] : []))
if (!assignments.length) return
const { rowCount } = await pool.query(`SELECT 1 FROM ix_segments s
CROSS JOIN LATERAL jsonb_array_elements(s.configuration->'linuxBonds') g
CROSS JOIN LATERAL jsonb_array_elements(g->'members') m
JOIN jsonb_to_recordset($2::jsonb) AS a(server_id bigint, iface text, client_id uuid)
ON m->>'serverId' = a.server_id::text AND m->>'interfaceName' = a.iface
WHERE (s.configuration->>'deleted') IS DISTINCT FROM 'true' AND m->>'segmentId'=$1 AND g->>'clientId'<>a.client_id::text LIMIT 1`,
[segmentId, JSON.stringify(assignments)])
if (rowCount) throw new IxConflict("Сначала исключите подключение из действующей группы VPS")
}
export async function readIxRevision(id: string, revision: number) { export async function readIxRevision(id: string, revision: number) {
const { rows: [row] } = await pool.query("SELECT configuration FROM ix_segment_revisions WHERE segment_id=$1 AND revision=$2", [id, revision]) const { rows: [row] } = await pool.query("SELECT configuration FROM ix_segment_revisions WHERE segment_id=$1 AND revision=$2", [id, revision])
if (!row) throw new IxConflict("Ревизия IX не найдена", 404) if (!row) throw new IxConflict("Ревизия IX не найдена", 404)
@@ -78,17 +119,34 @@ export async function ixReservedRouterIds(id?: string, sql: Pick<PoolClient, "qu
return new Set(rows.map(row => row.router_id)) return new Set(rows.map(row => row.router_id))
} }
export async function ixReservedTunnelBindings(serverId: number) { export async function ixReservedTunnelBindings(serverId: number, excludeSegmentId?: string, sql: Pick<PoolClient, "query"> = pool) {
const { rows } = await pool.query<{ configuration: unknown }>(` const { rows } = await sql.query<{ configuration: unknown }>(`
SELECT s.configuration FROM ix_segments s JOIN ix_segment_devices d ON d.segment_id=s.id SELECT s.configuration - 'linuxBonds' AS configuration FROM ix_segments s JOIN ix_segment_devices d ON d.segment_id=s.id
WHERE d.server_id=$1 AND (s.configuration->>'deleted') IS DISTINCT FROM 'true' WHERE d.server_id=$1 AND ($2::uuid IS NULL OR s.id<>$2) AND (s.configuration->>'deleted') IS DISTINCT FROM 'true'
UNION ALL UNION ALL
SELECT r.configuration FROM ix_segments s JOIN ix_segment_devices d ON d.segment_id=s.id SELECT r.configuration FROM ix_segments s JOIN ix_segment_devices d ON d.segment_id=s.id
JOIN ix_segment_revisions r ON r.segment_id=s.id AND r.revision=s.applied_revision JOIN ix_segment_revisions r ON r.segment_id=s.id AND r.revision=s.applied_revision
WHERE d.server_id=$1 AND (s.configuration->>'deleted') IS DISTINCT FROM 'true' WHERE d.server_id=$1 AND ($2::uuid IS NULL OR s.id<>$2) AND (s.configuration->>'deleted') IS DISTINCT FROM 'true'
`, [serverId]) `, [serverId, excludeSegmentId ?? null])
return rows.flatMap(({ configuration }) => ixSegmentConfigurationSchema.parse(configuration).sites return rows.flatMap(({ configuration }) => ixSegmentConfigurationSchema.parse(configuration).sites
.filter(site => site.serverId === serverId).flatMap(site => site.interfaces)) .flatMap(site => site.interfaces.filter(binding => site.serverId === serverId || binding.peerServerId === serverId)))
}
export async function ixReservedLinuxPoolBlocks() {
const { rows } = await pool.query<{ address: string }>(`
SELECT DISTINCT address
FROM ix_segments s LEFT JOIN ix_segment_revisions r ON r.segment_id=s.id AND r.revision=s.applied_revision
CROSS JOIN LATERAL jsonb_array_elements(COALESCE(s.configuration->'sites','[]'::jsonb) ||
COALESCE(r.configuration->'sites','[]'::jsonb)) site
CROSS JOIN LATERAL jsonb_array_elements(site->'interfaces') binding
CROSS JOIN LATERAL (VALUES
(split_part(COALESCE(binding->'provisionWireguard'->>'localAddress',binding->'provisionGre'->>'localAddress'),'/',1)),
(COALESCE(binding->'provisionWireguard'->>'peerAddress',binding->'provisionGre'->>'peerAddress'))) hosts(address)
WHERE (s.configuration->>'deleted') IS DISTINCT FROM 'true' AND binding ? 'linux' AND address LIKE '10.254.%'`)
return new Set(rows.map(row => {
const [, , third, last] = row.address.split(".").map(Number)
return third * 256 + (last & ~3)
}))
} }
export function nextIxRouterId(used: ReadonlySet<string>) { export function nextIxRouterId(used: ReadonlySet<string>) {
@@ -134,7 +192,8 @@ export async function writeIxRevision(id: string, expected: number, configuratio
? await client.query<SegmentRow>(`INSERT INTO ix_segments(id,name,revision,configuration,applied_revision) ? await client.query<SegmentRow>(`INSERT INTO ix_segments(id,name,revision,configuration,applied_revision)
VALUES ($1,$2,$3,$4::jsonb,$5) ON CONFLICT DO NOTHING RETURNING ${columns}`, VALUES ($1,$2,$3,$4::jsonb,$5) ON CONFLICT DO NOTHING RETURNING ${columns}`,
[id, configuration.name, revision, JSON.stringify(configuration), applied ? revision : null]) [id, configuration.name, revision, JSON.stringify(configuration), applied ? revision : null])
: await client.query<SegmentRow>(`UPDATE ix_segments SET name=$2,revision=$3,configuration=$4::jsonb, : await client.query<SegmentRow>(`UPDATE ix_segments SET name=$2,revision=$3,configuration=$4::jsonb ||
CASE WHEN configuration ? 'linuxBonds' THEN jsonb_build_object('linuxBonds', configuration->'linuxBonds') ELSE '{}'::jsonb END,
applied_revision=CASE WHEN $5::boolean THEN $3 ELSE applied_revision END,updated_at=now() applied_revision=CASE WHEN $5::boolean THEN $3 ELSE applied_revision END,updated_at=now()
WHERE id=$1 AND revision=$6 AND ${visible} RETURNING ${columns}`, WHERE id=$1 AND revision=$6 AND ${visible} RETURNING ${columns}`,
[id, configuration.name, revision, JSON.stringify(configuration), applied, expected]) [id, configuration.name, revision, JSON.stringify(configuration), applied, expected])
@@ -47,7 +47,7 @@ async function getSettingsRow() {
retentionDays: 14, retentionDays: 14,
createdAt: now, createdAt: now,
updatedAt: now, updatedAt: now,
}) }).onConflictDoNothing({ target: internetPathSettings.id })
return (await db.select().from(internetPathSettings).where(eq(internetPathSettings.id, 1)).limit(1))[0] return (await db.select().from(internetPathSettings).where(eq(internetPathSettings.id, 1)).limit(1))[0]
} }
@@ -0,0 +1,42 @@
import assert from "node:assert/strict"
import { readFileSync } from "node:fs"
import { test } from "node:test"
import { ixBondBundleSchema, type IxSite } from "@mmapp/contracts/internet-exchange"
import { ixGreClientTemplate, ixWireguardClientTemplate } from "./internet-exchange-client.js"
const bundle = ixBondBundleSchema.parse(JSON.parse(readFileSync(
new URL("../../../packages/contracts/testdata/ix-bond-v1.json", import.meta.url), "utf8")))
test("the shared ix-client fixture accepts weighted members and rejects overlapping tunnel addresses", () => {
assert.deepEqual(bundle.members.map(path => path.weight), [3, 1])
const changed = structuredClone(bundle)
changed.members[0].probe = changed.members[1].address
assert.equal(ixBondBundleSchema.safeParse(changed).success, false)
const invalidKey = structuredClone(bundle)
invalidKey.members[0].peerPublicKey = "B".repeat(43) + "="
assert.equal(ixBondBundleSchema.safeParse(invalidKey).success, false)
})
test("group transport brings up an encrypted link without claiming routes used by other members", () => {
const [wg, gre] = bundle.members
const linux = { name: bundle.name, enabled: true, exit: "wan", destinations: [], peerEndpoint: "192.0.2.99" }
const binding: IxSite["interfaces"][number] = {
name: "wg-test", kind: "wireguard", linux, prefixes: [], provisionWireguard: {
listenPort: 51820, endpointPort: 51820, localAddress: wg.probe + "/30", peerAddress: wg.address,
hubEndpoint: wg.endpoint, peerPublicKey: wg.peerPublicKey!,
},
}
const wgConfig = ixWireguardClientTemplate(binding, wg.peerPublicKey!, bundle.destinations, undefined, true)
assert.match(wgConfig, /Table = off/)
assert.doesNotMatch(wgConfig, /PostUp|PreDown/)
assert.match(wgConfig, /0\.0\.0\.0\/0/)
assert.match(ixWireguardClientTemplate(binding, wg.peerPublicKey!, bundle.destinations), /Table = auto/)
const greConfig = ixGreClientTemplate({ name: "gre-test", kind: "gre-ipsec", linux, prefixes: [],
localEndpoint: gre.endpoint, endpoint: linux.peerEndpoint, provisionGre: {
localAddress: gre.probe + "/30", peerAddress: gre.address, credentialId: bundle.id,
} }, 17, undefined, undefined, true)
assert.match(greConfig.template, /start_action = trap/)
assert.match(greConfig.setup, /systemctl enable --now ix-gre-/)
assert.match(greConfig.setup, /ExecStart=.*ip address add 10\.123\.2\.2\/32/)
assert.doesNotMatch(greConfig.setup, /ip -[46] rule|route replace|secret =/)
})
@@ -0,0 +1,26 @@
import assert from "node:assert/strict"
import { test } from "node:test"
import { createIxImportLinks, type IxImportBundle } from "./ix-import-links.js"
const bundle: IxImportBundle = { version: 1, kind: "wireguard", name: "ixw000000000000", config: "fixture" }
test("only one concurrent request can claim a link", async () => {
const links = createIxImportLinks(() => 10)
let reads = 0
const code = links.issue(20, async () => { reads++; return bundle })
assert.match(code, /^[A-Za-z0-9_-]{32}$/)
const responses = await Promise.allSettled([links.redeem(code), links.redeem(code)])
assert.deepEqual(responses[0], { status: "fulfilled", value: bundle })
assert.equal(responses[1].status, "rejected")
assert.equal(reads, 1)
})
test("expiry is enforced before and after loading the bundle", async () => {
let now = 10
const links = createIxImportLinks(() => now)
const expired = links.issue(20, async () => { assert.fail("expired link read its source") })
const tooSlow = links.issue(30, async () => { now = 31; return bundle })
now = 20
await assert.rejects(links.redeem(expired), /истекла/)
await assert.rejects(links.redeem(tooSlow), /истекла/)
})
+39
View File
@@ -0,0 +1,39 @@
import { createHash, randomBytes } from "node:crypto"
import { performance } from "node:perf_hooks"
import type { IxBondBundle } from "@mmapp/contracts/internet-exchange"
import { IxConflict } from "./internet-exchange-plan.js"
export type IxImportGre = { local: string; remote: string; address: string; psk: string }
export type IxImportBundle =
| { version: 1; kind: "wireguard"; name: string; config: string }
| { version: 1; kind: "gre-ipsec"; name: string; gre: IxImportGre }
| { version: 1; kind: "bond"; bond: IxBondBundle }
const digest = (code: string) => createHash("sha256").update(code).digest("hex")
const maxLinks = 256
const expired = () => new IxConflict("Ссылка истекла или уже использована", 410)
export function createIxImportLinks(now = () => performance.now()) {
const links = new Map<string, { deadline: number; load: () => Promise<IxImportBundle> }>()
return {
issue(deadline: number, load: () => Promise<IxImportBundle>) {
const current = now()
for (const [key, entry] of links) if (entry.deadline <= current) links.delete(key)
if (deadline <= current) throw expired()
if (links.size >= maxLinks) throw new IxConflict("Слишком много активных ссылок импорта", 429)
const code = randomBytes(24).toString("base64url")
// shortcut: pending links live in this backend process, use shared storage if the backend is replicated.
links.set(digest(code), { deadline, load })
return code
},
async redeem(code: string) {
const key = digest(code), entry = links.get(key)
links.delete(key)
if (!entry || entry.deadline <= now()) throw expired()
const bundle = await entry.load()
if (entry.deadline <= now()) throw expired()
return bundle
},
}
}
@@ -1,5 +1,4 @@
import {assertOwnedBandwidthSql,prepareOwnedBandwidthState} from "./bandwidth-admission-process.sql-helper.js" import {assertOwnedBandwidthSql,prepareOwnedBandwidthState} from "./bandwidth-admission-process.sql-helper.js"
assertOwnedBandwidthSql();await prepareOwnedBandwidthState() assertOwnedBandwidthSql();await prepareOwnedBandwidthState()
const {pool,closePool}=await import("../db/index.js") const {pool,closePool}=await import("../db/index.js")
const {applySqlMigrations}=await import("../db/migrate.js") const {applySqlMigrations}=await import("../db/migrate.js")
@@ -12,6 +11,8 @@ try{
const {acceptRoutingMeasurementPoolSql}=await import("../modules/mcp/routing-measurement-pool.sql-helper.js") const {acceptRoutingMeasurementPoolSql}=await import("../modules/mcp/routing-measurement-pool.sql-helper.js")
const routing=await acceptRoutingMeasurementPoolSql(ids) const routing=await acceptRoutingMeasurementPoolSql(ids)
console.log("Owned operation lock routing: "+JSON.stringify(routing)) console.log("Owned operation lock routing: "+JSON.stringify(routing))
const { checkCatalogReadContention } = await import("./routing-catalog-observation.sql-helper.js")
await checkCatalogReadContention(ids[0])
const {acceptAutomaticSchedulerSql}=await import("./scheduler-automatic-root.sql-helper.js") const {acceptAutomaticSchedulerSql}=await import("./scheduler-automatic-root.sql-helper.js")
console.log("Owned automatic scheduler: "+JSON.stringify(await acceptAutomaticSchedulerSql(ids))) console.log("Owned automatic scheduler: "+JSON.stringify(await acceptAutomaticSchedulerSql(ids)))
}finally{ }finally{
@@ -0,0 +1,167 @@
import assert from "node:assert/strict"
import { AsyncResource } from "node:async_hooks"
import { mock } from "node:test"
import { setTimeout as delay } from "node:timers/promises"
import { assertOwnedBandwidthSql } from "./bandwidth-admission-process.sql-helper.js"
export async function checkCatalogReadContention(serverId: number) {
assertOwnedBandwidthSql()
const { db, pool } = await import("../db/index.js")
const { default: Fastify } = await import("fastify")
const { installDatabaseRequestGate } = await import("../plugins/database-request-gate.js")
const app = Fastify()
installDatabaseRequestGate(app)
let releaseHttp!: () => void
const httpGate = new Promise<void>(resolve => { releaseHttp = resolve })
let activeReads = 0
app.get("/api/test/catalog", async () => { activeReads++; await httpGate; return { ok: true } })
app.put("/api/test/catalog", async () => ({ ok: true }))
await app.ready()
const requests = Promise.all(Array.from({ length: 12 }, () => app.inject({ method: "GET", url: "/api/test/catalog" })))
try {
const until = Date.now() + 5000
while (activeReads < 8) { assert(Date.now() < until, "REST read pool did not fill"); await delay(10) }
assert.equal((await app.inject({ method: "PUT", url: "/api/test/catalog" })).statusCode, 200)
assert.equal(activeReads, 8, "Write admitted while every ordinary REST lease was held by a GET")
} finally {
releaseHttp()
try { assert((await requests).every(response => response.statusCode === 200)) }
finally { await app.close() }
}
const { ensurePartitionFor } = await import("../db/partitions.js")
await ensurePartitionFor(pool, "internet_path_snapshots", "week", new Date())
const { getSettings } = await import("./uptime-collector.js")
const { getTrafficSettings } = await import("./traffic-collector.js")
const { getInternetPathSettings } = await import("./internet-path-collector.js")
const { getServersApiPingSettings } = await import("./servers-rest-ping-collector.js")
for (const [table, get] of [["uptime_settings", getSettings], ["traffic_settings", getTrafficSettings],
["internet_path_settings", getInternetPathSettings], ["servers_api_ping_settings", getServersApiPingSettings]] as const) {
// Two readers see the missing row before either INSERT can commit.
await pool.query(`DELETE FROM ${table} WHERE id=1`)
const gate = await pool.connect()
let results
try {
await gate.query("BEGIN")
await gate.query(`LOCK TABLE ${table} IN SHARE MODE`)
results = Promise.allSettled([get(), get()])
const until = Date.now() + 5000
while ((await gate.query("SELECT count(*)::int AS n FROM pg_locks WHERE relation=$1::regclass AND NOT granted", [table])).rows[0].n < 2) {
assert(Date.now() < until, "Concurrent initializers did not reach INSERT: " + table)
await delay(10)
}
} finally { await gate.query("ROLLBACK"); gate.release() }
const [first, second] = await results
assert(first.status === "fulfilled" && second.status === "fulfilled", table)
assert.deepEqual(first.value, second.value)
}
const { readFilterRulesCatalog } = await import("../routes/filters.js")
const { readRecursiveRoutesForServer, readRecursiveCatalogForServer, applyRecursiveToServer } = await import("../routes/recursive-routes.js")
const { servers } = await import("../db/schema.js")
const { eq } = await import("drizzle-orm")
const { runSchedulerJobNow } = await import("./scheduler.js")
const { MikrotikClient } = await import("./mikrotik.js")
const { coalesceCatalogReads, readCatalogWithObservedCache } = await import("./routing-catalog-observation.js")
const { ConfigurationBusyError, withApplicationCollectorLock, withApplicationMutationLock } = await import("./config-mutation-lock.js")
const [fixture] = await db.select().from(servers).where(eq(servers.id, serverId))
const server = { ...fixture, enabled: true }
let attempts = 0
const poll = coalesceCatalogReads(async () => {
attempts++
if (attempts === 1) throw new Error("RouterOS unavailable")
return attempts
})
const first = poll(server)
assert.equal(first, poll(server))
assert.equal(await poll({ ...server, routingEndpointEpoch: "new-source" }), 2)
await assert.rejects(first, /RouterOS unavailable/)
assert.equal(await poll(server), 3, "Errors must not be cached")
assert.equal(await poll(server), 4, "A later refresh must start a new poll")
const independent = new AsyncResource("other-catalog-request")
const route = { id: "", dstAddress: "192.0.2.1/32", gateway: "192.0.2.2", distance: 1, scope: 30, targetScope: 10,
routingTable: "main", checkGateway: "ping", disabled: false, country: "", comment: "test" }
let native: Record<string, string>[] = [], blocked = 0, hold = false
let resume!: () => void
const gate = new Promise<void>(resolve => { resume = resolve })
const readRouter = async (path: string) => {
if (path === "/interface/gre") return []
assert(["/routing/filter/rule", "/ip/route/print"].includes(path))
const snapshot = path === "/ip/route/print" ? [...native] : []
if (hold) { blocked++; await gate }
return snapshot
}
const get = mock.method(MikrotikClient.prototype, "get", readRouter)
const post = mock.method(MikrotikClient.prototype, "post", readRouter)
const put = mock.method(MikrotikClient.prototype, "put", async (path: string, body: Record<string, string>) => {
assert.equal(path, "/ip/route")
native = [{ ...body, ".id": "*A", static: "true" }]
return { ".id": "*A" }
})
const load = () => Promise.all([readFilterRulesCatalog([server], { source: "live", persistObserved: true }),
readRecursiveCatalogForServer(server), readRecursiveRoutesForServer(server)])
try {
const jobs = ["uptime_resources", "uptime_ping"]
const startedAt = new Date().toISOString()
const pending = await withApplicationMutationLock(async () => {
const runs = independent.runInAsyncScope(() => Promise.all(jobs.map(runSchedulerJobNow)))
const state = await Promise.race([runs.then(() => "finished", () => "failed"), delay(600, "waiting")])
assert.equal(state, "waiting", "Scheduler must wait for a transient exclusive lock")
await independent.runInAsyncScope(() => assert.rejects(
withApplicationCollectorLock(async () => assert.fail("Collector entered during a write"), { waitMs: 50 }),
ConfigurationBusyError,
))
return { runs }
})
assert.deepEqual((await pending.runs).map(run => run.status), ["ok", "ok"])
const { rows } = await pool.query("SELECT job_key,status FROM scheduler_runs WHERE started_at >= $1 AND job_key=ANY($2::text[]) ORDER BY job_key", [startedAt, jobs])
assert.deepEqual(rows, [{ job_key: "uptime_ping", status: "ok" }, { job_key: "uptime_resources", status: "ok" }])
let executions = 0
await assert.rejects(withApplicationCollectorLock(async () => {
executions++
throw new ConfigurationBusyError("server")
}), ConfigurationBusyError)
assert.equal(executions, 1, "An admitted collector must never be replayed")
const cold = await Promise.all(Array.from({ length: 24 }, load))
assert(cold.every(([filters, catalog, routes]) => filters[0].live && catalog.live && routes.live))
const revisions = () => pool.query("SELECT section,source FROM config_revisions WHERE server_id=$1 ORDER BY section,created_at", [server.id])
assert.equal((await revisions()).rowCount, 2)
hold = true
const reading = Promise.all(Array.from({ length: 24 }, load))
try {
const until = Date.now() + 5000
while (blocked < 2) { assert(Date.now() < until, "Read traffic blocked before reaching RouterOS"); await delay(10) }
assert.equal(blocked, 2, "72 simultaneous requests share one RouterOS poll per catalogue")
hold = false
for (const job of ["uptime_resources", "uptime_ping", "traffic", "internet_path"]) {
const run = await runSchedulerJobNow(job)
assert.equal(run.status, "ok", job + ": " + run.error)
}
const apply = () => independent.runInAsyncScope(() => applyRecursiveToServer(server, [route], "apply", () =>
independent.runInAsyncScope(() => assert.rejects(withApplicationMutationLock(async () => assert.fail("Overlapping writer")), ConfigurationBusyError))))
let pending!: Promise<PromiseSettledResult<Awaited<ReturnType<typeof apply>>>[]>
await withApplicationCollectorLock(async () => {
pending = Promise.allSettled([apply(), apply()])
await delay(500)
assert.equal(put.mock.callCount(), 0)
})
const results = await pending
assert.equal(results.filter(result => result.status === "fulfilled" && result.value.pushed === 1).length, 1)
assert.equal(results.filter(result => result.status === "rejected" && result.reason.code === "STATE_CONFLICT").length, 1)
} finally { hold = false; resume(); await reading }
for (const [filters, catalog, routes] of await reading) {
assert(filters[0].live && catalog.live && routes.live)
assert.equal(catalog.routes[0].dstAddress, route.dstAddress)
assert.match(routes.routes[0].id, /^\d+$/)
}
assert.equal(put.mock.callCount(), 1)
assert.equal((await revisions()).rowCount, 3, "Late reads must not overwrite the applied revision")
let writes = 0
await assert.rejects(readCatalogWithObservedCache(server, async () => ({ current: false }), async () => {
writes++; throw new ConfigurationBusyError()
}), ConfigurationBusyError)
assert.equal(writes, 1)
await assert.rejects(readCatalogWithObservedCache({ ...server, routingEndpointEpoch: "retired" },
async () => ({ current: false }), async () => assert.fail("Old endpoint wrote to cache")), { code: "STATE_CONFLICT" })
console.log("Catalog contention: 72 simultaneous WebUI reads, two shared catalogue polls, four scheduler jobs, one verified route write and no stale cache publication")
} finally { get.mock.restore(); post.mock.restore(); put.mock.restore(); independent.emitDestroy() }
}
@@ -0,0 +1,87 @@
import { setTimeout as delay } from "node:timers/promises"
import { and, desc, eq } from "drizzle-orm"
import { db } from "../db/index.js"
import { configRevisions, servers, type Server } from "../db/schema.js"
import { McpError } from "../modules/mcp/security.js"
import { fingerprintPayload, type ConfigSection } from "./config-revisions.js"
import { ConfigurationBusyError, withApplicationCollectorLock, withApplicationMutationLock, withConfigMutationLock } from "./config-mutation-lock.js"
/** Web reads share only the in-flight poll of this catalogue and endpoint generation. */
export function coalesceCatalogReads<T>(poll: (server: Server) => Promise<T>) {
const pending = new Map<string, Promise<T>>()
return (server: Server) => {
const key = server.id + ":" + server.routingEndpointEpoch
const current = pending.get(key)
if (current) return current
const request = poll(server).finally(() => { pending.delete(key) })
pending.set(key, request)
return request
}
}
async function latestRevision(serverId: number, section: ConfigSection) {
const [latest] = await db.select({ id: configRevisions.id, fingerprint: configRevisions.fingerprint }).from(configRevisions)
.where(and(eq(configRevisions.serverId, serverId), eq(configRevisions.section, section)))
.orderBy(desc(configRevisions.createdAt)).limit(1)
return latest
}
/** A live read matching both the cache and its revision has nothing to persist. */
export async function observationIsCurrent(serverId: number, section: ConfigSection, live: unknown[], cached: unknown[]) {
const fingerprint = fingerprintPayload(live)
return fingerprint === fingerprintPayload(cached) && (await latestRevision(serverId, section))?.fingerprint === fingerprint
}
async function assertCatalogSource(server: Server) {
const [source] = await db.select({ epoch: servers.routingEndpointEpoch }).from(servers).where(eq(servers.id, server.id))
if (!source || source.epoch !== server.routingEndpointEpoch) throw new McpError("STATE_CONFLICT", "Источник опроса изменился. Обновите каталог.", 409)
}
/** Retry only lock admission. Release DB clients before sleeping and never replay admitted work. */
async function enterCatalogLock<T>(lock: (run: () => Promise<T>) => Promise<T>, run: () => Promise<T>) {
const deadline = performance.now() + 5000
for (;;) {
let admitted = false
try { return await lock(() => { admitted = true; return run() }) }
catch (error) {
if (admitted || !(error instanceof ConfigurationBusyError) || performance.now() >= deadline) throw error
}
await delay(200)
}
}
export async function withCatalogWriteLock<T>(server: Server, section: ConfigSection, run: () => Promise<T>) {
const before = await latestRevision(server.id, section)
return enterCatalogLock(work => withApplicationMutationLock(() => withConfigMutationLock([server.id], work)), async () => {
await assertCatalogSource(server)
if ((await latestRevision(server.id, section))?.id !== before?.id) throw new McpError("STATE_CONFLICT", "Конфигурация изменилась во время ожидания. Обновите каталог.", 409)
return run()
})
}
// Waiting for a cache refresh must not occupy the DB connections needed by writers.
const catalogRefreshes = new Map<number, Promise<void>>()
export async function readCatalogWithObservedCache<T extends { current: boolean }>(
server: Server, read: (fresh: boolean) => Promise<T>, save: (observed: T) => Promise<T>,
): Promise<T> {
const observed = await read(false)
if (observed.current) return observed
const serverId = server.id
while (catalogRefreshes.has(serverId) || catalogRefreshes.size >= 2) {
const refreshing = catalogRefreshes.get(serverId)
await (refreshing ?? Promise.race(catalogRefreshes.values()))
if (refreshing) {
const latest = await read(false)
if (latest.current) return latest
}
}
let done!: () => void
catalogRefreshes.set(serverId, new Promise(resolve => { done = resolve }))
try {
return await enterCatalogLock(work => withApplicationCollectorLock(() => withConfigMutationLock([serverId], work), { waitMs: 0 }), async () => {
await assertCatalogSource(server)
const latest = await read(true)
return latest.current ? latest : save(latest)
})
} finally { catalogRefreshes.delete(serverId); done() }
}
+1 -1
View File
@@ -216,7 +216,7 @@ export async function runSchedulerJobNow(jobKey: string): Promise<SchedulerRunRe
throw new Error(`Unknown job key: ${jobKey}`) throw new Error(`Unknown job key: ${jobKey}`)
} }
if (!tryBeginSchedulerJob(jobKey)) { if (!tryBeginSchedulerJob(jobKey)) {
const err = new Error(isSchedulerJobsPaused() ? "Планировщик приостановлен для операции с базой" : "Job already running") const err = new Error(isSchedulerJobsPaused() ? "Планировщик приостановлен для операции с базой" : "Задача уже выполняется")
;(err as Error & { statusCode?: number }).statusCode = 409 ;(err as Error & { statusCode?: number }).statusCode = 409
if (isSchedulerJobsPaused()) (err as Error & { code?: string }).code = "SCHEDULER_PAUSED" if (isSchedulerJobsPaused()) (err as Error & { code?: string }).code = "SCHEDULER_PAUSED"
throw err throw err
@@ -20,7 +20,7 @@ async function getSettingsRow() {
intervalSec: 120, intervalSec: 120,
createdAt: now, createdAt: now,
updatedAt: now, updatedAt: now,
}) }).onConflictDoNothing({ target: serversApiPingSettings.id })
return (await db.select().from(serversApiPingSettings).where(eq(serversApiPingSettings.id, 1)).limit(1))[0] return (await db.select().from(serversApiPingSettings).where(eq(serversApiPingSettings.id, 1)).limit(1))[0]
} }
+1 -1
View File
@@ -80,7 +80,7 @@ async function getSettingsRow() {
...trafficSettingsDefaults, ...trafficSettingsDefaults,
createdAt: now, createdAt: now,
updatedAt: now, updatedAt: now,
}) }).onConflictDoNothing({ target: trafficSettings.id })
return readSettingsRow() return readSettingsRow()
} }
@@ -46,6 +46,8 @@ assert.equal(isNamedInternetService("DNS", "DNS"), false)
assert.equal(mapServiceNodeId("AWS"), "svc:aws") assert.equal(mapServiceNodeId("AWS"), "svc:aws")
assert.equal(mapServiceNodeId("Cloudflare"), "svc:cloudflare") assert.equal(mapServiceNodeId("Cloudflare"), "svc:cloudflare")
assert.equal(mapServiceNodeId("Прочее"), "svc:other") assert.equal(mapServiceNodeId("Прочее"), "svc:other")
assert.notEqual(mapServiceNodeId("Видео"), mapServiceNodeId("Игры"))
assert.notEqual(mapServiceNodeId("Microsoft Работа"), mapServiceNodeId("Microsoft Игры"))
assert.equal(mapCountryNodeId("US"), "cc:us") assert.equal(mapCountryNodeId("US"), "cc:us")
assert.equal(mapCountryNodeId("nl"), "cc:nl") assert.equal(mapCountryNodeId("nl"), "cc:nl")
assert.equal(mapCountryNodeId(""), "cc:other") assert.equal(mapCountryNodeId(""), "cc:other")
@@ -358,6 +358,7 @@ export function isNamedInternetService(service: string, category: string): boole
export function mapServiceNodeId(label: string): string { export function mapServiceNodeId(label: string): string {
const raw = label.trim() const raw = label.trim()
if (raw === OTHER_SERVICE) return "svc:other" if (raw === OTHER_SERVICE) return "svc:other"
if (/[^\x00-\x7f]/.test(raw)) return `svc:label:${encodeURIComponent(raw.normalize("NFC").toLowerCase())}`
const slug = raw const slug = raw
.toLowerCase() .toLowerCase()
.replace(/[^a-z0-9]+/g, "-") .replace(/[^a-z0-9]+/g, "-")
@@ -5,12 +5,16 @@ import { classifyFlowDst, disableCatalogFetchForTests, resetFlowCatalogForTests,
disableCatalogFetchForTests() disableCatalogFetchForTests()
resetFlowCatalogForTests() resetFlowCatalogForTests()
seedFlowCatalogForTests({ 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) const hit = classifyFlowDst("192.0.2.10", 6, 443, 50000, null)
assert.equal(hit.category, "Игры") assert.equal(hit.category, "Игры")
assert.equal(hit.service, "steam-gaming") 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) const miss = classifyFlowDst("203.0.113.9", 17, 53, 53000, null)
assert.equal(miss.category, "DNS") 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 { export function categoryFromPurpose(purpose: string, proto: number, dstPort: number, srcPort: number): string {
const p = purpose.toLowerCase() const p = purpose.trim().toLowerCase()
if (/gaming|steam|epic|riot|playstation|roblox|ubisoft/.test(p)) return "Игры" if (/игры|gaming|steam|epic|riot|playstation|roblox|ubisoft/.test(p)) return "Игры"
if (/streaming|youtube|netflix|twitch|video|spotify|instagram/.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 (/cdn|cloudflare|akamai|fastly|hetzner|ovh|apple/.test(p)) return "CDN"
if (/voip|discord|zoom/.test(p)) return "Голос" if (/голос|voip|discord|zoom/.test(p)) return "Голос"
if (/openai|chatgpt|\bai\b/.test(p)) return "ИИ" if (p === "ии" || /openai|chatgpt|\bai\b/.test(p)) return "ИИ"
if (/quad9|opendns/.test(p)) return "DNS" if (/quad9|opendns/.test(p)) return "DNS"
if (/веб|web|google|github|paypal|vk|linkedin/.test(p)) return "Веб" if (/веб|web|google|github|paypal|vk|linkedin/.test(p)) return "Веб"
const app = applicationName(proto, dstPort, srcPort) const app = applicationName(proto, dstPort, srcPort)
@@ -142,6 +142,7 @@ assert.equal(classifyInternetBrand("8.8.8.8", 6, 443, 51234, {
fetchedAt: Date.now(), fetchedAt: Date.now(),
})?.service, "Google") })?.service, "Google")
assert.equal(mapInternetBrand("203.0.113.50", 6, 443, 51234, null).service, "Прочее") 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", 47, 0, 0, null).service, "Прочее")
assert.equal(mapInternetBrand("8.8.8.8", 6, 443, 51234, { assert.equal(mapInternetBrand("8.8.8.8", 6, 443, 51234, {
prefix: "8.8.8.0/24", 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 if (isTunnelProto(proto, dstPort, srcPort)) return OTHER_BRAND
const classified = classifyFlowDst(dst, proto, dstPort, srcPort, ripe, { ignoreTunnelProto: true }) const classified = classifyFlowDst(dst, proto, dstPort, srcPort, ripe, { ignoreTunnelProto: true })
if (isNamedInternetService(classified.service, classified.category)) return classified if (isNamedInternetService(classified.service, classified.category)) return classified
return OTHER_BRAND return { service: classified.category, category: classified.category }
} }
export function resolveInternetDest(opts: { export function resolveInternetDest(opts: {
@@ -11,6 +11,7 @@ import * as proof from "./traffic-flow-batch-proof.js"
import * as accumulator from "./traffic-flow-fact-accumulator.js" import * as accumulator from "./traffic-flow-fact-accumulator.js"
import * as serial from "./serial-operation.js" import * as serial from "./serial-operation.js"
import * as parse from "./traffic-flow-parse.js" import * as parse from "./traffic-flow-parse.js"
import * as planes from "./traffic-flow-planes.js"
import * as ip from "./traffic-flow-ip.js" import * as ip from "./traffic-flow-ip.js"
import * as ifindex from "./traffic-flow-ifindex.js" import * as ifindex from "./traffic-flow-ifindex.js"
import { pruneRipeSqlite } from "./traffic-flow-ripe.js" import { pruneRipeSqlite } from "./traffic-flow-ripe.js"
@@ -46,7 +47,7 @@ const dependencies:Record<string,unknown>={
reconcileFlowWrite:async()=>({committed:receiptPresent,result:receiptPresent?{buckets:1,ingestQuality:identified?.ingestQuality}:null}), reconcileFlowWrite:async()=>({committed:receiptPresent,result:receiptPresent?{buckets:1,ingestQuality:identified?.ingestQuality}:null}),
}, },
"../db/partitions.js":{specForParent:()=>null,ensurePartitionFor:()=>{throw Error("unexpected DDL")}}, "../db/partitions.js":{specForParent:()=>null,ensurePartitionFor:()=>{throw Error("unexpected DDL")}},
"./traffic-flow-planes.js":{classifyFlowPlaneLite:()=>"internet"}, "./traffic-flow-planes.js":planes,
"./traffic-flow-map-exporter.js":{pickServerIdForExporter:()=>1}, "./traffic-flow-map-exporter.js":{pickServerIdForExporter:()=>1},
"./traffic-flow-apps.js":{applicationName:()=>"https"}, "./traffic-flow-apps.js":{applicationName:()=>"https"},
"./traffic-flow-ripe.js":{enqueueRipeMisses:()=>{throw Error("unexpected RIPE enqueue")},pruneRipeSqlite}, "./traffic-flow-ripe.js":{enqueueRipeMisses:()=>{throw Error("unexpected RIPE enqueue")},pruneRipeSqlite},
+16 -10
View File
@@ -9,7 +9,7 @@ import { createFlowFactAccumulator, type FactRow } from "./traffic-flow-fact-acc
import { createSerialOperation } from "./serial-operation.js" import { createSerialOperation } from "./serial-operation.js"
import { ensurePartitionFor, specForParent } from "../db/partitions.js" import { ensurePartitionFor, specForParent } from "../db/partitions.js"
import { normalizeParsedFlow, parseFlowPacket, FlowTemplateRefused, protoName, type ParsedFlow, type ParsedFlowInput, type FlowDatagramTransport } from "./traffic-flow-parse.js" import { normalizeParsedFlow, parseFlowPacket, FlowTemplateRefused, protoName, type ParsedFlow, type ParsedFlowInput, type FlowDatagramTransport } from "./traffic-flow-parse.js"
import { classifyFlowPlaneLite } from "./traffic-flow-planes.js" import { classifyFlowPlane, classifyFlowPlaneLite } from "./traffic-flow-planes.js"
import { pickServerIdForExporter, type OverlayPeerRef } from "./traffic-flow-map-exporter.js" import { pickServerIdForExporter, type OverlayPeerRef } from "./traffic-flow-map-exporter.js"
import { applicationName } from "./traffic-flow-apps.js" import { applicationName } from "./traffic-flow-apps.js"
import { enqueueRipeMisses, pruneRipeSqlite } from "./traffic-flow-ripe.js" import { enqueueRipeMisses, pruneRipeSqlite } from "./traffic-flow-ripe.js"
@@ -45,6 +45,8 @@ export const DAILY_ASN_TOP = 500
export const DAILY_RETENTION_DAYS = 396 export const DAILY_RETENTION_DAYS = 396
export const MINUTE_RETENTION_HOURS = 48 export const MINUTE_RETENTION_HOURS = 48
export const OBSERVED_FLOW_IFACE_DIM = "observed-iface-v1" export const OBSERVED_FLOW_IFACE_DIM = "observed-iface-v1"
export const FLOW_IFACE_RX_DIM = "iface-rx-v1"
export const FLOW_IFACE_TX_DIM = "iface-tx-v1"
export const OBSERVED_FLOW_IFACE_COVERAGE_DIM = "observed-iface-coverage-v1" export const OBSERVED_FLOW_IFACE_COVERAGE_DIM = "observed-iface-coverage-v1"
export const ADMITTED_FLOW_DAY_DIM = "admitted-v1" export const ADMITTED_FLOW_DAY_DIM = "admitted-v1"
@@ -437,10 +439,13 @@ export function queueParsedFlows(serverId: number, flows: ParsedFlowInput[]): vo
serverId,inIface:flow.inIface,outIface:flow.outIface,topo,natSrc:flow.natSrc,natDst:flow.natDst,natSrcPort:flow.natSrcPort,natDstPort:flow.natDstPort}) serverId,inIface:flow.inIface,outIface:flow.outIface,topo,natSrc:flow.natSrc,natDst:flow.natDst,natSrcPort:flow.natSrcPort,natDstPort:flow.natDstPort})
const classified=destMeta.classified,country=destMeta.country const classified=destMeta.classified,country=destMeta.country
const seenIfaces = new Map<string, string>() const seenIfaces = new Map<string, string>()
const directions: Array<{dim: string; key: string}> = []
const ingress = resolveIfaceName(serverId, flow.inIface), egress = resolveIfaceName(serverId, flow.outIface)
const plane = classifyFlowPlane({ ...flow, inIface: ingress.name, outIface: egress.name }, topo?.plane)
let interfaceUncertain = false let interfaceUncertain = false
for (const rawIface of [flow.inIface, flow.outIface]) { for (const [dim, {name, index}] of [[FLOW_IFACE_RX_DIM, ingress], [FLOW_IFACE_TX_DIM, egress]] as const) {
const {name, index} = resolveIfaceName(serverId, rawIface)
if (name === "—") continue if (name === "—") continue
if (plane !== "mgmt") directions.push({ dim: dim + ":" + plane, key: name })
if (index && name === `#${index}`) interfaceUncertain = true if (index && name === `#${index}`) interfaceUncertain = true
if (index || !seenIfaces.has(name)) seenIfaces.set(name, index ? String(Number(index)) : name) if (index || !seenIfaces.has(name)) seenIfaces.set(name, index ? String(Number(index)) : name)
} }
@@ -451,7 +456,7 @@ export function queueParsedFlows(serverId: number, flows: ParsedFlowInput[]): vo
] ]
const dims=[{dim:"proto",key:protoName(flow.proto)},{dim:"app",key:applicationName(flow.proto,flow.dstPort,flow.srcPort)}, const dims=[{dim:"proto",key:protoName(flow.proto)},{dim:"app",key:applicationName(flow.proto,flow.dstPort,flow.srcPort)},
{dim:"iface",key:flow.inIface||"__unknown__"},{dim:"category",key:classified.category},{dim:"service",key:classified.service}, {dim:"iface",key:flow.inIface||"__unknown__"},{dim:"category",key:classified.category},{dim:"service",key:classified.service},
...observedDimensions, ...observedDimensions, ...directions,
{dim:"country",key:country||"unknown"},{dim:"asn",key:destMeta.asn?String(destMeta.asn):"unknown"}].map(row=>({...row,cacheKey:dimKey(serverId,bucketAt,row.dim,row.key)})) {dim:"country",key:country||"unknown"},{dim:"asn",key:destMeta.asn?String(destMeta.asn):"unknown"}].map(row=>({...row,cacheKey:dimKey(serverId,bucketAt,row.dim,row.key)}))
const fact:FactRow|null=shouldWriteFlowFact({serverId,serverType,inIface:flow.inIface,outIface:flow.outIface,proto:flow.proto, const fact:FactRow|null=shouldWriteFlowFact({serverId,serverType,inIface:flow.inIface,outIface:flow.outIface,proto:flow.proto,
srcPort:flow.srcPort,dstPort:flow.dstPort,src:flow.src,dst:flow.dst,topo,dest:destMeta.dest, srcPort:flow.srcPort,dstPort:flow.dstPort,src:flow.src,dst:flow.dst,topo,dest:destMeta.dest,
@@ -471,8 +476,9 @@ export function queueParsedFlows(serverId: number, flows: ParsedFlowInput[]): vo
if (prev) { if (prev) {
prev.bytes += flow.bytes prev.bytes += flow.bytes
prev.packets += flow.packets prev.packets += flow.packets
if (flow.outIface && !prev.flow.outIface) prev.flow.outIface = flow.outIface // This tuple is keyed by ingress. Only retain egress metadata shared by all its bytes.
if (flow.nextHop && !prev.flow.nextHop) prev.flow.nextHop = flow.nextHop if (prev.flow.outIface !== flow.outIface) prev.flow.outIface = ""
if (prev.flow.nextHop !== flow.nextHop) prev.flow.nextHop = ""
if (flow.natSrc && !prev.flow.natSrc) prev.flow.natSrc = flow.natSrc if (flow.natSrc && !prev.flow.natSrc) prev.flow.natSrc = flow.natSrc
if (flow.natDst && !prev.flow.natDst) prev.flow.natDst = flow.natDst if (flow.natDst && !prev.flow.natDst) prev.flow.natDst = flow.natDst
if (flow.natSrcPort && !prev.flow.natSrcPort) prev.flow.natSrcPort = flow.natSrcPort if (flow.natSrcPort && !prev.flow.natSrcPort) prev.flow.natSrcPort = flow.natSrcPort
@@ -549,8 +555,8 @@ function mergeInto(map: Map<string, PendingFlowRow>, row: PendingFlowRow): void
if (prev) { if (prev) {
prev.bytes += row.bytes prev.bytes += row.bytes
prev.packets += row.packets prev.packets += row.packets
if (row.outIface && !prev.outIface) prev.outIface = row.outIface if (prev.outIface !== row.outIface) prev.outIface = ""
if (row.nextHop && !prev.nextHop) prev.nextHop = row.nextHop if (prev.nextHop !== row.nextHop) prev.nextHop = ""
if (row.natSrc && !prev.natSrc) prev.natSrc = row.natSrc if (row.natSrc && !prev.natSrc) prev.natSrc = row.natSrc
if (row.natDst && !prev.natDst) prev.natDst = row.natDst if (row.natDst && !prev.natDst) prev.natDst = row.natDst
if (row.natSrcPort && !prev.natSrcPort) prev.natSrcPort = row.natSrcPort if (row.natSrcPort && !prev.natSrcPort) prev.natSrcPort = row.natSrcPort
@@ -959,8 +965,8 @@ async function upsertFlowBucketsBatch(rows: PendingFlowRow[]): Promise<void> {
DO UPDATE SET DO UPDATE SET
bytes = flow_buckets.bytes + excluded.bytes, bytes = flow_buckets.bytes + excluded.bytes,
packets = flow_buckets.packets + excluded.packets, packets = flow_buckets.packets + excluded.packets,
out_iface = CASE WHEN excluded.out_iface != '' THEN excluded.out_iface ELSE flow_buckets.out_iface END, out_iface = CASE WHEN flow_buckets.out_iface = excluded.out_iface THEN excluded.out_iface ELSE '' END,
next_hop = COALESCE(excluded.next_hop, flow_buckets.next_hop), next_hop = CASE WHEN flow_buckets.next_hop = excluded.next_hop THEN excluded.next_hop END,
flow_start_ms = CASE flow_start_ms = CASE
WHEN excluded.flow_start_ms > 0 AND (flow_buckets.flow_start_ms = 0 OR excluded.flow_start_ms < flow_buckets.flow_start_ms) WHEN excluded.flow_start_ms > 0 AND (flow_buckets.flow_start_ms = 0 OR excluded.flow_start_ms < flow_buckets.flow_start_ms)
THEN excluded.flow_start_ms ELSE flow_buckets.flow_start_ms END, THEN excluded.flow_start_ms ELSE flow_buckets.flow_start_ms END,
+2 -2
View File
@@ -429,8 +429,8 @@ function mergeInto(map: Map<string, PendingFlowRow>, row: PendingFlowRow): void
if (prev) { if (prev) {
prev.bytes += row.bytes prev.bytes += row.bytes
prev.packets += row.packets prev.packets += row.packets
if (row.outIface && !prev.outIface) prev.outIface = row.outIface if (prev.outIface !== row.outIface) prev.outIface = ""
if (row.nextHop && !prev.nextHop) prev.nextHop = row.nextHop if (prev.nextHop !== row.nextHop) prev.nextHop = ""
if (row.natSrc && !prev.natSrc) prev.natSrc = row.natSrc if (row.natSrc && !prev.natSrc) prev.natSrc = row.natSrc
if (row.natDst && !prev.natDst) prev.natDst = row.natDst if (row.natDst && !prev.natDst) prev.natDst = row.natDst
if (row.natSrcPort && !prev.natSrcPort) prev.natSrcPort = row.natSrcPort if (row.natSrcPort && !prev.natSrcPort) prev.natSrcPort = row.natSrcPort
@@ -1,4 +1,8 @@
import assert from "node:assert/strict" import assert from "node:assert/strict"
import { mock } from "node:test"
import { dbQuery } from "../db/index.js"
import { configureEngine, flushEngineNow } from "./traffic-flow-engine.js"
import { parseFlowPacket } from "./traffic-flow-parse.js"
import { rememberServerIfaces, resetIfaceCacheForTests } from "./traffic-flow-ifindex.js" import { rememberServerIfaces, resetIfaceCacheForTests } from "./traffic-flow-ifindex.js"
import { import {
ingestParsedFlowsForServerForTests, ingestParsedFlowsForServerForTests,
@@ -98,6 +102,20 @@ disableRipePersistForTests()
resetRipeCacheForTests() resetRipeCacheForTests()
disableRipeEnqueueForTests() disableRipeEnqueueForTests()
const bucket = Math.floor(Date.now() / 60000) * 60000 - 60000
function ingestClosed(serverId: number, flows: Parameters<typeof ingestParsedFlowsForServerForTests>[1], at = bucket) {
const clock = mock.method(Date, "now", () => at)
try { ingestParsedFlowsForServerForTests(serverId, flows) } finally { clock.mock.restore() }
}
const { rows: [snapshot] } = await dbQuery<{id: number}>(`
INSERT INTO internet_path_snapshots(sampled_at,payload_json) VALUES (?,?::jsonb) RETURNING id
`, [new Date(bucket).toISOString(), JSON.stringify({ collectionComplete: true, greTunnels: [
{serverId: "7", name: "gre-jh-en", remoteAddress: "198.51.100.1", enabled: true},
{serverId: "7", name: "SWE-VEESP", remoteAddress: "198.51.100.1", enabled: true},
{serverId: "7", name: "gre-second", remoteAddress: "198.51.100.2", enabled: true},
] })])
const topo: FlowTopology = { const topo: FlowTopology = {
clientIfaces: new Map([[7, new Set(["gre-client"])]]), clientIfaces: new Map([[7, new Set(["gre-client"])]]),
clientByIface: new Map([["7|gre-client", { clientByIface: new Map([["7|gre-client", {
@@ -130,7 +148,7 @@ rememberServerIfaces(3, [
{ ".id": "*1", name: "ether1-rt" }, { ".id": "*1", name: "ether1-rt" },
]) ])
ingestParsedFlowsForServerForTests(7, [ ingestClosed(7, [
{ {
src: "10.100.1.17", src: "10.100.1.17",
dst: "8.8.8.8", dst: "8.8.8.8",
@@ -177,7 +195,7 @@ ingestParsedFlowsForServerForTests(7, [
outIface: "", outIface: "",
}, },
]) ])
ingestParsedFlowsForServerForTests(3, [ ingestClosed(3, [
{ {
src: "192.168.1.10", src: "192.168.1.10",
dst: "8.8.4.4", dst: "8.8.4.4",
@@ -288,7 +306,7 @@ rememberServerIfaces(7, [
{ ".id": "*3", name: "gre-jh-en" }, { ".id": "*3", name: "gre-jh-en" },
]) ])
googleRipe() googleRipe()
ingestParsedFlowsForServerForTests(7, [ ingestClosed(7, [
payloadFlow("8.8.8.8", 600), payloadFlow("8.8.8.8", 600),
payloadFlow("11.0.113.50", 9400), payloadFlow("11.0.113.50", 9400),
]) ])
@@ -320,7 +338,7 @@ try {
assert.ok(usPath) assert.ok(usPath)
assert.equal(usPath.clientName, "Alice") assert.equal(usPath.clientName, "Alice")
ingestParsedFlowsForServerForTests(7, [{ ...payloadFlow("8.8.8.8", 2000), proto: 17, dstPort: 51820 }]) ingestClosed(7, [{ ...payloadFlow("8.8.8.8", 2000), proto: 17, dstPort: 51820 }])
const mixedPeer = await buildFlowMapHops({ minutes: 5, serverId: 7, excludeOverlay: false }) const mixedPeer = await buildFlowMapHops({ minutes: 5, serverId: 7, excludeOverlay: false })
assert.equal(mixedPeer.totalBytes, 12_000) assert.equal(mixedPeer.totalBytes, 12_000)
assert.equal(mixedPeer.namedBytes, 600, "WireGuard to the same peer is separate from the HTTPS service") assert.equal(mixedPeer.namedBytes, 600, "WireGuard to the same peer is separate from the HTTPS service")
@@ -340,7 +358,7 @@ rememberServerIfaces(7, [
{ ".id": "*3", name: "gre-jh-en" }, { ".id": "*3", name: "gre-jh-en" },
]) ])
googleRipe() googleRipe()
ingestParsedFlowsForServerForTests(7, [ ingestClosed(7, [
payloadFlow("8.8.8.8", 400), payloadFlow("8.8.8.8", 400),
payloadFlow("11.0.113.50", 9600), payloadFlow("11.0.113.50", 9600),
]) ])
@@ -374,7 +392,7 @@ rememberServerIfaces(7, [
{ ".id": "*2", name: "gre-client" }, { ".id": "*2", name: "gre-client" },
{ ".id": "*3", name: "gre-jh-en" }, { ".id": "*3", name: "gre-jh-en" },
]) ])
ingestParsedFlowsForServerForTests(7, [ ingestClosed(7, [
payloadFlow("8.8.8.8", 400), payloadFlow("8.8.8.8", 400),
payloadFlow("104.18.35.51", 400), payloadFlow("104.18.35.51", 400),
payloadFlow("11.0.113.50", 9200), payloadFlow("11.0.113.50", 9200),
@@ -407,7 +425,7 @@ rememberServerIfaces(7, [
{ ".id": "*3", name: "gre-jh-en" }, { ".id": "*3", name: "gre-jh-en" },
]) ])
seedRipeAsn("162.254.192.71", 32590, "VALVE-CORP") seedRipeAsn("162.254.192.71", 32590, "VALVE-CORP")
ingestParsedFlowsForServerForTests(7, [ ingestClosed(7, [
payloadFlow("162.254.192.71", 2000), payloadFlow("162.254.192.71", 2000),
]) ])
try { try {
@@ -429,7 +447,7 @@ rememberServerIfaces(7, [
{ ".id": "*2", name: "gre-client" }, { ".id": "*2", name: "gre-client" },
{ ".id": "*3", name: "gre-jh-en" }, { ".id": "*3", name: "gre-jh-en" },
]) ])
ingestParsedFlowsForServerForTests(7, [ ingestClosed(7, [
payloadFlow("64.233.161.1", 10_000), payloadFlow("64.233.161.1", 10_000),
payloadFlow("11.0.113.50", 20_000), payloadFlow("11.0.113.50", 20_000),
]) ])
@@ -480,7 +498,7 @@ rememberServerIfaces(7, [
]) ])
googleRipe() googleRipe()
for (const b of smallBrands) seedRipeAsn(b.ip, b.asn, b.holder) for (const b of smallBrands) seedRipeAsn(b.ip, b.asn, b.holder)
ingestParsedFlowsForServerForTests(7, [ ingestClosed(7, [
payloadFlow("8.8.8.8", 5000), payloadFlow("8.8.8.8", 5000),
...smallBrands.map((b) => payloadFlow(b.ip, b.bytes)), ...smallBrands.map((b) => payloadFlow(b.ip, b.bytes)),
]) ])
@@ -508,7 +526,7 @@ rememberServerIfaces(7, [
{ ".id": "*2", name: "gre-client" }, { ".id": "*2", name: "gre-client" },
{ ".id": "*3", name: "gre-jh-en" }, { ".id": "*3", name: "gre-jh-en" },
]) ])
ingestParsedFlowsForServerForTests(7, [ ingestClosed(7, [
{ {
src: "203.0.113.10", src: "203.0.113.10",
dst: "198.51.100.1", dst: "198.51.100.1",
@@ -544,7 +562,7 @@ rememberServerIfaces(7, [
{ ".id": "*3", name: "gre-jh-en" }, { ".id": "*3", name: "gre-jh-en" },
]) ])
googleRipe() googleRipe()
ingestParsedFlowsForServerForTests(7, [ ingestClosed(7, [
{ {
src: "10.100.1.17", src: "10.100.1.17",
dst: "8.8.8.8", dst: "8.8.8.8",
@@ -609,7 +627,7 @@ rememberServerIfaces(7, [
{ ".id": "*2", name: "gre-client" }, { ".id": "*2", name: "gre-client" },
{ ".id": "*3", name: "gre-jh-en" }, { ".id": "*3", name: "gre-jh-en" },
]) ])
ingestParsedFlowsForServerForTests(7, [ ingestClosed(7, [
{ {
src: "173.194.151.65", src: "173.194.151.65",
dst: "10.200.100.53", dst: "10.200.100.53",
@@ -618,9 +636,9 @@ ingestParsedFlowsForServerForTests(7, [
dstPort: 57182, dstPort: 57182,
bytes: 9_000, bytes: 9_000,
packets: 90, packets: 90,
inIface: "2", inIface: "3",
outIface: "3", outIface: "2",
nextHop: "198.51.100.1", nextHop: "",
}, },
{ {
src: "104.18.35.51", src: "104.18.35.51",
@@ -630,9 +648,9 @@ ingestParsedFlowsForServerForTests(7, [
dstPort: 53880, dstPort: 53880,
bytes: 1_000, bytes: 1_000,
packets: 10, packets: 10,
inIface: "2", inIface: "3",
outIface: "3", outIface: "2",
nextHop: "198.51.100.1", nextHop: "",
}, },
]) ])
try { try {
@@ -659,7 +677,7 @@ rememberServerIfaces(7, [
{ ".id": "*2", name: "gre-client" }, { ".id": "*2", name: "gre-client" },
{ ".id": "*3", name: "gre-jh-en" }, { ".id": "*3", name: "gre-jh-en" },
]) ])
ingestParsedFlowsForServerForTests(7, [ ingestClosed(7, [
payloadFlow("8.8.8.8", 500), payloadFlow("8.8.8.8", 500),
{ {
src: "173.194.151.65", src: "173.194.151.65",
@@ -697,9 +715,9 @@ resetRipeCacheForTests()
disableRipeEnqueueForTests() disableRipeEnqueueForTests()
seedFlowTopologyForTests(topo) seedFlowTopologyForTests(topo)
rememberServerIfaces(7, [ rememberServerIfaces(7, [
{ ".id": "*1", name: "SWE-VEESP" }, { ".id": "*1", name: "ether1" },
]) ])
ingestParsedFlowsForServerForTests(7, [ ingestClosed(7, [
{ {
src: "173.194.151.65", src: "173.194.151.65",
dst: "10.200.100.53", dst: "10.200.100.53",
@@ -716,16 +734,12 @@ ingestParsedFlowsForServerForTests(7, [
try { try {
resetFlowMapHopsCacheForTests() resetFlowMapHopsCacheForTests()
const wanOnly = await buildFlowMapHops({ minutes: 5, minSharePct: 0 }) const wanOnly = await buildFlowMapHops({ minutes: 5, minSharePct: 0 })
const googleEdge = wanOnly.serviceEdges?.find((e) => e.toId === "svc:youtube") assert.equal(wanOnly.services?.find(s => s.id === "svc:youtube")?.bytes, 9000)
assert.ok(googleEdge, "YouTube WAN без GRE payload") assert.deepEqual(wanOnly.serviceEdges, [])
assert.equal(googleEdge.fromId, "9", "единственный EN, даже без nextHop") assert.deepEqual(wanOnly.servicePaths, [])
assert.ok(googleEdge.bps > 0, "скорость на hop EN→сервис") assert.deepEqual(wanOnly.countryEdges, [])
assert.ok(!(wanOnly.serviceEdges ?? []).some((e) => e.fromId === "7"), "нет пунктира с JH") assert.ok(wanOnly.countryServiceGroups?.every(group => !group.edges.length && !group.paths.length))
const googlePath = wanOnly.servicePaths?.find((p) => p.serviceId === "svc:youtube")
assert.ok(googlePath, "путь WAN YouTube")
assert.equal(googlePath.viaId, "7", "via = JH exporter")
assert.equal(googlePath.enId, "9", "якорь EN")
assert.ok(googlePath.bps > 0, "скорость на пути клиента")
} finally { } finally {
seedFlowTopologyForTests(null) seedFlowTopologyForTests(null)
resetFlowRingsForTests() resetFlowRingsForTests()
@@ -747,14 +761,14 @@ rememberServerIfaces(9, [
{ ".id": "*1", name: "ether1" }, { ".id": "*1", name: "ether1" },
]) ])
googleRipe() googleRipe()
ingestParsedFlowsForServerForTests(7, [payloadFlow("8.8.8.8", 12_000)]) ingestClosed(7, [payloadFlow("8.8.8.8", 12_000)])
ingestParsedFlowsForServerForTests(9, [{ ingestClosed(9, [{
src: "10.100.1.17", src: "10.100.1.17",
dst: "8.8.8.8", dst: "8.8.8.8",
proto: 6, proto: 6,
srcPort: 51234, srcPort: 51234,
dstPort: 443, dstPort: 443,
bytes: 12_000, bytes: 120_000,
packets: 10, packets: 10,
inIface: "1", inIface: "1",
outIface: "1", outIface: "1",
@@ -772,7 +786,8 @@ try {
assert.equal(googlePaths[0]?.viaId, "7") assert.equal(googlePaths[0]?.viaId, "7")
const googleEdge = dual.serviceEdges?.find((e) => e.toId === "svc:google" && e.fromId === "9") const googleEdge = dual.serviceEdges?.find((e) => e.toId === "svc:google" && e.fromId === "9")
assert.ok(googleEdge) assert.ok(googleEdge)
assert.equal(googleEdge.bytes, 12_000) assert.equal(googleEdge.bytes, 120_000)
assert.equal(dual.totalBytes, 120_000, "объём крупнейшей копии с атрибуцией маршрута JH")
assert.equal(googleEdge.bps, googlePaths[0]?.bps) assert.equal(googleEdge.bps, googlePaths[0]?.bps)
} finally { } finally {
seedFlowTopologyForTests(null) seedFlowTopologyForTests(null)
@@ -792,7 +807,7 @@ rememberServerIfaces(7, [
{ ".id": "*3", name: "gre-jh-en" }, { ".id": "*3", name: "gre-jh-en" },
]) ])
googleRipe() googleRipe()
ingestParsedFlowsForServerForTests(7, [ ingestClosed(7, [
payloadFlow("8.8.8.8", 8_000), payloadFlow("8.8.8.8", 8_000),
{ {
src: "8.8.8.8", src: "8.8.8.8",
@@ -818,6 +833,8 @@ try {
assert.ok(!(bothDir.servicePaths ?? []).some((p) => p.serviceId === "svc:google" && p.clientId === "—")) assert.ok(!(bothDir.servicePaths ?? []).some((p) => p.serviceId === "svc:google" && p.clientId === "—"))
const googleEdge = bothDir.serviceEdges?.find((e) => e.toId === "svc:google" && e.fromId === "9") const googleEdge = bothDir.serviceEdges?.find((e) => e.toId === "svc:google" && e.fromId === "9")
assert.ok(googleEdge) assert.ok(googleEdge)
assert.equal(googleEdge.bpsFwd, 8000 * 8 / 300)
assert.equal(googleEdge.bpsRev, 4000 * 8 / 300)
assert.equal(googleEdge.bytes, 12_000) assert.equal(googleEdge.bytes, 12_000)
assert.equal(googleEdge.bps, googlePaths[0]?.bps) assert.equal(googleEdge.bps, googlePaths[0]?.bps)
} finally { } finally {
@@ -848,7 +865,7 @@ seedRipeCacheForTests({
ok: true, ok: true,
fetchedAt: Date.now(), fetchedAt: Date.now(),
}) })
ingestParsedFlowsForServerForTests(7, [ ingestClosed(7, [
payloadFlow("8.8.8.8", 5000), payloadFlow("8.8.8.8", 5000),
payloadFlow("185.45.12.10", 5000), payloadFlow("185.45.12.10", 5000),
]) ])
@@ -885,7 +902,7 @@ rememberServerIfaces(7, [
{ ".id": "*3", name: "gre-jh-en" }, { ".id": "*3", name: "gre-jh-en" },
]) ])
googleRipe() googleRipe()
ingestParsedFlowsForServerForTests(7, [ ingestClosed(7, [
payloadFlow("8.8.8.8", 600), payloadFlow("8.8.8.8", 600),
payloadFlow("11.0.113.50", 9400), payloadFlow("11.0.113.50", 9400),
]) ])
@@ -938,7 +955,7 @@ seedRipeCacheForTests({
ok: true, ok: true,
fetchedAt: Date.now(), fetchedAt: Date.now(),
}) })
ingestParsedFlowsForServerForTests(7, [ ingestClosed(7, [
payloadFlow("8.8.8.8", 5000), payloadFlow("8.8.8.8", 5000),
payloadFlow("185.45.12.10", 5000), payloadFlow("185.45.12.10", 5000),
]) ])
@@ -974,7 +991,7 @@ rememberServerIfaces(7, [
]) ])
googleRipe() googleRipe()
for (const b of smallBrands) seedRipeAsn(b.ip, b.asn, b.holder) for (const b of smallBrands) seedRipeAsn(b.ip, b.asn, b.holder)
ingestParsedFlowsForServerForTests(7, [ ingestClosed(7, [
payloadFlow("8.8.8.8", 5000), payloadFlow("8.8.8.8", 5000),
...smallBrands.map((b) => payloadFlow(b.ip, b.bytes)), ...smallBrands.map((b) => payloadFlow(b.ip, b.bytes)),
]) ])
@@ -1005,3 +1022,98 @@ try {
} }
console.log("traffic-flow-map-hops.test.ts: ok") console.log("traffic-flow-map-hops.test.ts: ok")
// Identical destination/ports on two exits and the local WAN must remain separate.
seedFlowTopologyForTests({ ...topo, enNodes: [...topo.enNodes, {id: 10, name: "FIN", hosts: ["198.51.100.2"]}] })
try {
const flow = { ...payloadFlow("173.194.151.65", 0), nextHop: "", inIface: "gre-client" }
ingestClosed(7, [
{ ...flow, src: "10.0.0.1", bytes: 1000, outIface: "SWE-VEESP" },
{ ...flow, src: "10.0.0.2", bytes: 2000, outIface: "gre-second" },
{ ...flow, src: "10.0.0.3", bytes: 9000, outIface: "ether1" },
])
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]), [["10", 2000], ["9", 1000]])
assert.equal(map.servicePaths?.reduce((n, p) => n + p.bytes, 0), 3000)
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()
seedFlowTopologyForTests(null)
}
// Captured on the test CHR. Three 64-byte UDP packets traversed GRE A -> GRE B.
// RouterOS also exported three 88-byte outer GRE packets on GRE B -> underlay.
const datagram = Buffer.from(
"0005000201dd5ad06b0530a3227e55740000000000000000" +
"c612971ec612970e00000000000a000b00000003000000c0" +
"01dd470c01dd470c4e388866000011000000000000000000" +
"c6129705c612970600000000000b00090000000300000108" +
"01dd470c01dd470c0000000000002f000000000000000000",
"hex",
)
const decoded = parseFlowPacket(datagram, "198.18.151.1")
assert.equal(decoded.length, 2)
const { rows: [fixture] } = await dbQuery<{id: number}>("INSERT INTO servers(name, host, enabled) VALUES ('flow-map-gre-test', '127.0.0.1', false) RETURNING id")
const sid = fixture.id
try {
resetFlowRingsForTests()
configureEngine({ topN: 200 })
seedFlowTopologyForTests(topo)
rememberServerIfaces(sid, [{ ifindex: "10", name: "gre-a" }, { ifindex: "11", name: "gre-b" }, { ifindex: "9", name: "underlay" }])
const now = Date.now()
const clock = mock.method(Date, "now", () => now - 10 * 60000)
try {
ingestParsedFlowsForServerForTests(sid, [{ ...decoded[0], inIface: "quiet-old", outIface: "0" }])
clock.mock.mockImplementation(() => now - 60000)
const busy = Array.from({length: 201}, (_, i) => ({ ...decoded[0], srcPort: 5000 + i, bytes: 16000, inIface: "wan", outIface: "lan" }))
const privatePing = { ...decoded[0], src: "10.1.0.1", dst: "10.2.0.1", proto: 1, srcPort: 0, dstPort: 0,
inIface: "site-gre", outIface: "site-lan", bytes: 84, packets: 1 }
ingestParsedFlowsForServerForTests(sid, [...busy, privatePing, ...decoded])
} finally { clock.mock.restore() }
await flushEngineNow({ prune: false })
assert.equal((await dbQuery("SELECT 1 FROM flow_buckets WHERE server_id=? AND in_iface IN ('10','11')", [sid])).rowCount, 0)
const map = await buildFlowMapHops({ serverId: sid, minutes: 5 })
const quiet = map.interfaceTraffic?.find(row => row.iface === "quiet-old")
assert(quiet && !quiet.inWindow && quiet.lastBucketAt && quiet.rxBytes === 0)
assert.equal(map.interfaceTraffic?.find(row => row.iface === "site-gre")?.rxBytes, 84)
const a = map.interfaceTraffic?.find(row => row.iface === "gre-a")
const b = map.interfaceTraffic?.find(row => row.iface === "gre-b")
assert(a?.inWindow && b?.inWindow)
assert.deepEqual([a.rxBytes, a.txBytes, a.rxPackets, a.txPackets], [192, 0, 3, 0])
assert.deepEqual([b.rxBytes, b.txBytes, b.rxPackets, b.txPackets], [0, 192, 0, 3])
const overlay = await buildFlowMapHops({ serverId: sid, minutes: 5, iface: "gre-b", excludeOverlay: false })
assert.deepEqual(overlay.interfaceTraffic?.map(row => [row.iface, row.rxBytes, row.txBytes]), [["gre-b", 264, 192]])
// One tuple reroutes within a minute, first in memory and then across SQL flushes.
const routed = { ...payloadFlow("173.194.151.65", 1000), inIface: "mixed-lan", outIface: "uplink-a" }
const rerouted = { ...routed, outIface: "uplink-b", nextHop: "198.51.100.2" }
const split = { ...routed, srcPort: 40001 }
ingestClosed(sid, [routed, rerouted, routed, split], bucket - 60000)
await flushEngineNow({ prune: false })
ingestClosed(sid, [{ ...rerouted, srcPort: split.srcPort }], bucket - 60000)
await flushEngineNow({ prune: false })
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, [])
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)
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])
resetFlowRingsForTests()
seedFlowTopologyForTests(null)
resetIfaceCacheForTests()
}
+161 -96
View File
@@ -1,7 +1,8 @@
import { flowReadDbAll } from "./traffic-flow-read-policy.js" import { flowReadDbAll } from "./traffic-flow-read-policy.js"
import { isDeepStrictEqual } from "node:util" import { isDeepStrictEqual } from "node:util"
import { readFlowMapSourceLimits } from "./traffic-flow-source-limits.js" import { readFlowMapSourceLimits } from "./traffic-flow-source-limits.js"
import { flowCounterSum } from "./traffic-flow-observed-values.js" import { flowCounter, flowCounterSum } from "./traffic-flow-observed-values.js"
import type { FlowMapInterfaceTraffic } from "@mmapp/contracts/traffic-flow"
import type { ScopedFlowAnalyticsRead } from "./traffic-flow-analytics.js" import type { ScopedFlowAnalyticsRead } from "./traffic-flow-analytics.js"
import type { FlowMapCountryServiceGroup, FlowMapHop, FlowMapHopsDto, FlowMapService, FlowMapServiceEdge, FlowMapServicePath } from "@mmapp/contracts/traffic-flow" import type { FlowMapCountryServiceGroup, FlowMapHop, FlowMapHopsDto, FlowMapService, FlowMapServiceEdge, FlowMapServicePath } from "@mmapp/contracts/traffic-flow"
import { flowRowMatchesFilter } from "./traffic-flow-apps.js" import { flowRowMatchesFilter } from "./traffic-flow-apps.js"
@@ -9,15 +10,15 @@ import { OTHER_SERVICE, isNamedInternetService, mapCountryNodeId, mapCountryServ
import type { FlowIpMeta } from "./traffic-flow-ripe.js" import type { FlowIpMeta } from "./traffic-flow-ripe.js"
import { refreshFlowCatalogInBackground } from "./traffic-flow-classify.js" import { refreshFlowCatalogInBackground } from "./traffic-flow-classify.js"
import { collapseGreEspRows, dedupFlowRowsAcrossExporters, dedupFlowRowsMaxBytes } from "./traffic-flow-dedup.js" import { collapseGreEspRows, dedupFlowRowsAcrossExporters, dedupFlowRowsMaxBytes } from "./traffic-flow-dedup.js"
import { getFlowListenerState, listFlowRowsForWindow } from "./traffic-flow-ingest.js" import { getFlowListenerState, listStoredFlowRows } from "./traffic-flow-ingest.js"
import { resolveIfaceName } from "./traffic-flow-ifaces.js" import { resolveIfaceName } from "./traffic-flow-ifaces.js"
import { classifyFlowPlane, shouldKeepPlane } from "./traffic-flow-planes.js" import { classifyFlowPlane, shouldKeepPlane } from "./traffic-flow-planes.js"
import { destCtxForIface, flowRateDirection, mapInternetBrand } from "./traffic-flow-dest.js" import { destCtxForIface, flowRateDirection, mapInternetBrand } from "./traffic-flow-dest.js"
import { resolveFlowEndpoints } from "./traffic-flow-ip.js" import { resolveFlowEndpoints } from "./traffic-flow-ip.js"
import { geoipReadersStatus, resolveFlowIp } from "./traffic-flow-geoip.js" import { geoipReadersStatus, resolveFlowIp } from "./traffic-flow-geoip.js"
import { getTrafficFlowSettingsRow } from "./traffic-flow-settings.js" import { getTrafficFlowSettingsRow } from "./traffic-flow-settings.js"
import { loadFlowTopology, resolveClient, resolveEn, getServerCatalog, type FlowTopology } from "./traffic-flow-topology.js" import { loadFlowTopology, resolveClient, getServerCatalog, type FlowTopology } from "./traffic-flow-topology.js"
import { flowDataEpoch } from "./traffic-flow-engine.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 export const DEFAULT_MAP_SERVICE_MIN_SHARE_PCT = 5
export const MAP_SERVICE_NODE_CAP = 20 export const MAP_SERVICE_NODE_CAP = 20
@@ -32,6 +33,7 @@ const HOPS_CACHE_TTL_MS = 2000
export interface FlowMapHopsQuery { export interface FlowMapHopsQuery {
minutes: number minutes: number
includeCurrentMinute?: boolean
serverId?: number serverId?: number
userId?: string userId?: string
iface?: string iface?: string
@@ -60,6 +62,9 @@ interface ClientAcc {
} }
interface FromAcc { interface FromAcc {
exporterId: string
enId: string
reverseBytes: number
bytes: number bytes: number
clients: Map<string, ClientAcc> clients: Map<string, ClientAcc>
} }
@@ -110,16 +115,13 @@ function bumpClient(clients: Map<string, ClientAcc>, bytes: number, client: { us
clients.set(id, { name, bytes }) clients.set(id, { name, bytes })
} }
function bumpFrom(acc: DstAcc, exporterId: string, bytes: number, client: { userId: string; name: string } | null): void { function bumpFrom(acc: DstAcc, exporterId: string, enId: string, bytes: number, reverse: boolean, client: { userId: string; name: string } | null): void {
const prev = acc.fromBytes.get(exporterId) const key = exporterId + "|" + enId
if (prev) { const from = acc.fromBytes.get(key) ?? { exporterId, enId, bytes: 0, reverseBytes: 0, clients: new Map<string, ClientAcc>() }
prev.bytes += bytes from.bytes += bytes
bumpClient(prev.clients, bytes, client) if (reverse) from.reverseBytes += bytes
return bumpClient(from.clients, bytes, client)
} acc.fromBytes.set(key, from)
const clients = new Map<string, ClientAcc>()
bumpClient(clients, bytes, client)
acc.fromBytes.set(exporterId, { bytes, clients })
} }
let hopsCache: { key: string; at: number; dto: FlowMapHopsDto } | null = null let hopsCache: { key: string; at: number; dto: FlowMapHopsDto } | null = null
@@ -179,27 +181,24 @@ function bumpDestFrom(
} }
if (prevEdge) { if (prevEdge) {
prevEdge.bytes += from.bytes prevEdge.bytes += from.bytes
prevEdge.bytesFwd += from.bytes prevEdge.bytesFwd += from.bytes - from.reverseBytes
prevEdge.bytesRev += from.reverseBytes
for (const [id, name] of namedClients) prevEdge.clients.set(id, name) for (const [id, name] of namedClients) prevEdge.clients.set(id, name)
} else { } else {
edges.set(edgeKey, { edges.set(edgeKey, {
fromId: edgeFromId, fromId: edgeFromId,
toId, toId,
bytes: from.bytes, bytes: from.bytes,
bytesFwd: from.bytes, bytesFwd: from.bytes - from.reverseBytes,
bytesRev: 0, bytesRev: from.reverseBytes,
clients: namedClients, clients: namedClients,
}) })
} }
for (const [clientId, c] of from.clients) { for (const [clientId, c] of from.clients) {
const pathKey = `${clientId}|${fromId}|${toId}` const pathKey = `${clientId}|${exporterId}|${fromId}|${toId}`
const prevPath = paths.get(pathKey) const prevPath = paths.get(pathKey)
if (prevPath) { if (prevPath) {
prevPath.bytes += c.bytes prevPath.bytes += c.bytes
if (exporterId !== fromId && prevPath.viaId === fromId) {
prevPath.viaId = exporterId
prevPath.viaName = viaName
}
if (prevPath.clientName === "—" && c.name !== "—") prevPath.clientName = c.name if (prevPath.clientName === "—" && c.name !== "—") prevPath.clientName = c.name
} else { } else {
paths.set(pathKey, { paths.set(pathKey, {
@@ -331,6 +330,7 @@ function hopsQueryKey(q: FlowMapHopsQuery, minSharePct: number): string {
return JSON.stringify({ return JSON.stringify({
epoch: flowDataEpoch(), epoch: flowDataEpoch(),
minutes: q.minutes, minutes: q.minutes,
includeCurrentMinute: q.includeCurrentMinute === true,
serverId: q.serverId ?? null, serverId: q.serverId ?? null,
userId: q.userId ?? null, userId: q.userId ?? null,
iface: q.iface ?? null, iface: q.iface ?? null,
@@ -411,14 +411,84 @@ async function resolveMinSharePct(q: FlowMapHopsQuery): Promise<number> {
} }
} }
// 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 []
// 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 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(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) {
const name = resolveIfaceName(row.server_id, row.key).name
if (iface && name !== resolveIfaceName(row.server_id, iface).name) continue
const key = JSON.stringify([row.server_id, name])
const last = new Date(row.last_at).toISOString()
const value = totals.get(key) ?? { serverId: String(row.server_id), iface: name, rxBytes: 0, txBytes: 0,
rxPackets: 0, txPackets: 0, lastBucketAt: last, inWindow: false }
const rx = row.dim.startsWith(FLOW_IFACE_RX_DIM + ":")
const bytes = rx ? "rxBytes" : "txBytes", packets = rx ? "rxPackets" : "txPackets"
value[bytes] = flowCounterSum([value[bytes], flowCounter(row.bytes)])
value[packets] = flowCounterSum([value[packets], flowCounter(row.packets)])
if (last > value.lastBucketAt) value.lastBucketAt = last
value.inWindow = value.lastBucketAt >= start
totals.set(key, value)
}
return [...totals.values()].sort((a,b) => a.serverId.localeCompare(b.serverId) || a.iface.localeCompare(b.iface))
}
// Interface names are local to the exporter; match them against the GRE inventory for the flow minute.
async function readMapGrePeers(rows: { serverId: number; bucketAt: string; inIface: string; outIface: string }[]) {
const peers = new Map<string, Map<string, string>>()
if (!rows.length) return peers
const buckets = new Set<string>(), names = new Set<string>()
for (const row of rows) {
buckets.add(row.bucketAt)
for (const iface of [row.inIface, row.outIface]) names.add(row.serverId + "|" + resolveIfaceName(row.serverId, iface).name)
}
const bindings = await flowReadDbAll<{ bucket: string; key: string; remote: string }>(`
SELECT b.bucket, (t->>'serverId') || '|' || (t->>'name') AS key, t->>'remoteAddress' AS remote
FROM unnest(?::text[]) AS b(bucket)
CROSS JOIN LATERAL (
SELECT payload_json FROM internet_path_snapshots
WHERE sampled_at < b.bucket::timestamptz + interval '1 minute'
AND sampled_at >= b.bucket::timestamptz - interval '15 minutes'
ORDER BY sampled_at DESC, id DESC LIMIT 1
) snapshot
CROSS JOIN LATERAL jsonb_array_elements(CASE WHEN jsonb_typeof(payload_json->'greTunnels')='array'
THEN payload_json->'greTunnels' ELSE '[]'::jsonb END) AS t
WHERE payload_json->>'collectionComplete'='true' AND t->>'serverId' ~ '^[1-9][0-9]*$'
AND ((t->>'serverId') || '|' || (t->>'name'))=ANY(?::text[])
AND t->>'enabled'='true' AND t->>'name'<>'' AND t->>'remoteAddress'<>''
`, [[...buckets], [...names]])
for (const row of bindings) {
const interfaces = peers.get(row.bucket) ?? new Map<string, string>()
interfaces.set(row.key, interfaces.has(row.key) ? "" : row.remote.trim().toLowerCase())
peers.set(row.bucket, interfaces)
}
return peers
}
async function buildFlowMapHopsUncached(q: FlowMapHopsQuery, minSharePct: number, scope?: ScopedFlowAnalyticsRead): Promise<FlowMapHopsDto> { async function buildFlowMapHopsUncached(q: FlowMapHopsQuery, minSharePct: number, scope?: ScopedFlowAnalyticsRead): Promise<FlowMapHopsDto> {
const authorize = scope?.authorize ?? (async () => {}) const authorize = scope?.authorize ?? (async () => {})
if (!scope) refreshFlowCatalogInBackground() if (!scope) refreshFlowCatalogInBackground()
await authorize() await authorize()
const limits = scope ? await readFlowMapSourceLimits() : undefined 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() await authorize()
const raw = await listFlowRowsForWindow(q.minutes, q.serverId, { ...(scope ? { maxRows: scope.maxRows } : {}), untilIso: new Date().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("Строка карты вне выбранного сервера") if (scope && raw.some(row => row.serverId !== q.serverId)) throw new Error("Строка карты вне выбранного сервера")
await authorize() await authorize()
const catalog = await getServerCatalog(scope?.serverIds) const catalog = await getServerCatalog(scope?.serverIds)
@@ -472,7 +542,16 @@ async function buildFlowMapHopsUncached(q: FlowMapHopsQuery, minSharePct: number
if (scope) flowCounterSum(working.map(row => row.bytes)) if (scope) flowCounterSum(working.map(row => row.bytes))
const hops = new Map<string, HopAcc>() const hops = new Map<string, HopAcc>()
const dstAcc = new Map<string, DstAcc>() const dstAcc = new Map<string, DstAcc>()
const jhToEn = new Map<number, number>() const hostIds = new Map<string, number | null>()
for (const node of topo.enNodes) for (const host of node.hosts) {
const key = host.trim().split("/")[0]!.toLowerCase()
if (!key || key === "0.0.0.0" || key === "::") continue
const previous = hostIds.get(key)
hostIds.set(key, previous === undefined || previous === node.id ? node.id : null)
}
await authorize()
const peers = await readMapGrePeers(working)
const observed = new Map<(typeof working)[number], { endpoints: ReturnType<typeof resolveFlowEndpoints>; exitId?: number; reverse: boolean }>()
const enIds = new Set(topo.enNodes.map((n) => n.id)) const enIds = new Set(topo.enNodes.map((n) => n.id))
let totalBytes = 0 let totalBytes = 0
@@ -482,15 +561,6 @@ async function buildFlowMapHopsUncached(q: FlowMapHopsQuery, minSharePct: number
return resolveMapClient(topo, r.serverId, inName, outName) return resolveMapClient(topo, r.serverId, inName, outName)
} }
const payloadRows = wantDedup
? dedupFlowRowsAcrossExporters(working, (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
})
: working
for (const r of working) { for (const r of working) {
const inRes = resolveIfaceName(r.serverId, r.inIface) const inRes = resolveIfaceName(r.serverId, r.inIface)
const outRes = resolveIfaceName(r.serverId, r.outIface) const outRes = resolveIfaceName(r.serverId, r.outIface)
@@ -535,20 +605,37 @@ async function buildFlowMapHopsUncached(q: FlowMapHopsQuery, minSharePct: number
} }
} }
const enOut = ifaceUsable(outName) ? resolveEn(topo, r.nextHop, outName) : null const bindings = peers.get(r.bucketAt)
const enIn = ifaceUsable(inName) ? resolveEn(topo, "", inName) : null const outPeer = bindings?.get(fromId + "|" + outName)
const en = (enOut && enOut.id !== r.serverId ? enOut : null) const outId = outPeer === undefined ? hostIds.get(r.nextHop) : hostIds.get(outPeer)
?? (enIn && enIn.id !== r.serverId ? enIn : null) const inId = hostIds.get(bindings?.get(fromId + "|" + inName) ?? "")
if (en) { const peerId = outId && inId && outId !== inId ? null : outId ?? inId
jhToEn.set(r.serverId, en.id) const endpoints = resolveFlowEndpoints({
const toId = String(en.id) src: r.src,
const dir: "fwd" | "rev" = enOut && enOut.id === en.id ? "fwd" : "rev" dst: r.dst,
srcPort: r.srcPort,
dstPort: r.dstPort,
ctx: destCtxForIface(topo, r.serverId, inName, {
outIface: outName,
natSrc: r.natSrc,
natDst: r.natDst,
natSrcPort: r.natSrcPort,
natDstPort: r.natDstPort,
}),
})
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 })
if (peerId && peerId !== r.serverId) {
const toId = String(peerId)
const dir = outId === peerId ? "fwd" : "rev"
const greIface = dir === "fwd" && ifaceUsable(outName) ? outName : (ifaceUsable(inName) ? inName : undefined) const greIface = dir === "fwd" && ifaceUsable(outName) ? outName : (ifaceUsable(inName) ? inName : undefined)
bump(hops, `gre|${fromId}|${toId}`, { bump(hops, JSON.stringify(["gre", fromId, toId, greIface]), {
fromId, fromId,
fromLabel, fromLabel,
toId, toId,
toLabel: en.name, toLabel: nodeName(toId),
kind: "gre", kind: "gre",
iface: greIface, iface: greIface,
}, r.bytes, dir) }, r.bytes, dir)
@@ -578,44 +665,37 @@ 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
const aCli = Boolean(rowClient(a))
const bCli = Boolean(rowClient(b))
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))
return attributed
})
: working
for (const r of payloadRows) { for (const r of payloadRows) {
const inName = resolveIfaceName(r.serverId, r.inIface).name const inName = resolveIfaceName(r.serverId, r.inIface).name
const outName = resolveIfaceName(r.serverId, r.outIface).name const outName = resolveIfaceName(r.serverId, r.outIface).name
totalBytes += r.bytes const bytes = payloadBytes.get(r) ?? r.bytes
const ep = resolveFlowEndpoints({ totalBytes += bytes
src: r.src, const { endpoints: ep, exitId, reverse } = observed.get(r)!
dst: r.dst,
srcPort: r.srcPort,
dstPort: r.dstPort,
ctx: destCtxForIface(topo, r.serverId, inName, {
outIface: outName,
natSrc: r.natSrc,
natDst: r.natDst,
natSrcPort: r.natSrcPort,
natDstPort: r.natDstPort,
}),
})
const dst = ep.internetPeer const dst = ep.internetPeer
const dstPort = ep.peerPort || r.dstPort const dstPort = ep.peerPort || r.dstPort
const srcPort = ep.otherPort || r.srcPort const srcPort = ep.otherPort || r.srcPort
const destKey = dst ? JSON.stringify([dst, r.proto, dstPort, srcPort]) : "" const destKey = dst ? JSON.stringify([dst, r.proto, dstPort, srcPort]) : ""
const client = resolveMapClient(topo, r.serverId, inName, outName) const client = resolveMapClient(topo, r.serverId, inName, outName)
const prevDst = dstAcc.get(destKey) const acc = dstAcc.get(destKey) ?? { dst, bytes: 0, proto: r.proto, dstPort, srcPort, fromBytes: new Map<string, FromAcc>() }
if (prevDst) { acc.bytes += bytes
prevDst.bytes += r.bytes if (exitId !== undefined) bumpFrom(acc, String(r.serverId), String(exitId), bytes, reverse, client)
bumpFrom(prevDst, String(r.serverId), r.bytes, client) dstAcc.set(destKey, acc)
} else {
const acc: DstAcc = {
dst,
bytes: r.bytes,
proto: r.proto,
dstPort,
srcPort,
fromBytes: new Map(),
}
bumpFrom(acc, String(r.serverId), r.bytes, client)
dstAcc.set(destKey, acc)
}
} }
const svcTotals = new Map<string, DestTotal>() const svcTotals = new Map<string, DestTotal>()
@@ -628,25 +708,6 @@ async function buildFlowMapHopsUncached(q: FlowMapHopsQuery, minSharePct: number
const nestedEdges = new Map<string, DestEdgeAcc>() const nestedEdges = new Map<string, DestEdgeAcc>()
const nestedPaths = new Map<string, DestPathAcc>() const nestedPaths = new Map<string, DestPathAcc>()
for (const h of hops.values()) {
if (h.kind !== "gre" || !h.toId) continue
const from = Number(h.fromId)
const to = Number(h.toId)
if (!Number.isFinite(from) || !Number.isFinite(to)) continue
if (enIds.has(to) && !enIds.has(from)) jhToEn.set(from, to)
}
const soleEnId = topo.enNodes.length === 1 ? String(topo.enNodes[0]!.id) : null
function anchorEnId(exporterId: string): string | null {
const n = Number(exporterId)
if (enIds.has(n)) return exporterId
const mapped = jhToEn.get(n)
if (mapped != null) return String(mapped)
if (soleEnId) return soleEnId
return null
}
function nodeName(id: string): string { function nodeName(id: string): string {
const n = Number(id) const n = Number(id)
if (Number.isFinite(n)) { if (Number.isFinite(n)) {
@@ -670,9 +731,8 @@ async function buildFlowMapHopsUncached(q: FlowMapHopsQuery, minSharePct: number
bumpDestTotal(ccTotals, country.id, country.label, country.category, acc.bytes) bumpDestTotal(ccTotals, country.id, country.label, country.category, acc.bytes)
const nestedId = mapCountryServiceNodeId(country.id, svcId) const nestedId = mapCountryServiceNodeId(country.id, svcId)
bumpDestTotal(nestedTotals, nestedId, classified.service, classified.category, acc.bytes) bumpDestTotal(nestedTotals, nestedId, classified.service, classified.category, acc.bytes)
for (const [exporterId, from] of acc.fromBytes) { for (const from of acc.fromBytes.values()) {
const fromId = anchorEnId(exporterId) const { exporterId, enId: fromId } = from
if (!fromId) continue
const enName = nodeName(fromId) const enName = nodeName(fromId)
const viaName = nodeName(exporterId) const viaName = nodeName(exporterId)
bumpDestFrom(svcEdges, svcPaths, svcId, from, exporterId, fromId, enName, viaName) bumpDestFrom(svcEdges, svcPaths, svcId, from, exporterId, fromId, enName, viaName)
@@ -702,12 +762,17 @@ async function buildFlowMapHopsUncached(q: FlowMapHopsQuery, minSharePct: number
await authorize() await authorize()
if (scope && (!isDeepStrictEqual(topo, await loadFlowTopology(scope.serverIds, authorize)) || !isDeepStrictEqual(limits, await readFlowMapSourceLimits()))) throw new Error("Топология или пределы карты NetFlow изменились во время чтения") if (scope && (!isDeepStrictEqual(topo, await loadFlowTopology(scope.serverIds, authorize)) || !isDeepStrictEqual(limits, await readFlowMapSourceLimits()))) throw new Error("Топология или пределы карты NetFlow изменились во время чтения")
await authorize() 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, start, end)
await authorize()
return { return {
...(interfaceTraffic ? { interfaceTraffic } : {}),
hops: [...hops.values()] hops: [...hops.values()]
.map((a) => toHop(a, windowSec)) .map((a) => toHop(a, windowSec))
.sort((a, b) => a.bytes === b.bytes ? 0 : b.bytes - a.bytes), .sort((a, b) => a.bytes === b.bytes ? 0 : b.bytes - a.bytes),
live: listener.bound, live: listener.bound,
rangeMinutes: q.minutes, rangeMinutes: q.minutes,
...(q.includeCurrentMinute ? { includesCurrentMinute: true as const } : {}),
windowSec, windowSec,
totalBytes, totalBytes,
namedBytes, namedBytes,
@@ -38,6 +38,27 @@ else {
try { try {
await initDatabase();await app.listen({host:"127.0.0.1",port:0}) await initDatabase();await app.listen({host:"127.0.0.1",port:0})
serverId=Number((await pool.query("INSERT INTO servers(name,host,port,use_ssl,enabled,username,password,updated_at) VALUES($1,'127.0.0.1',$2,false,true,'fixture','fixture',$3) RETURNING id",[prefix+"server",address.port,new Date(Date.now()-3_600_000).toISOString()])).rows[0].id) serverId=Number((await pool.query("INSERT INTO servers(name,host,port,use_ssl,enabled,username,password,updated_at) VALUES($1,'127.0.0.1',$2,false,true,'fixture','fixture',$3) RETURNING id",[prefix+"server",address.port,new Date(Date.now()-3_600_000).toISOString()])).rows[0].id)
const sampleUrl = `/traffic/servers/${serverId}/live?once=1`
const beforeSample = nativeRequests
assert.equal((await app.inject(sampleUrl + "&iface=ether1,ether2")).statusCode, 400)
assert.equal(nativeRequests, beforeSample)
const sample = await app.inject(sampleUrl + "&iface=ether1")
assert.equal(sample.statusCode, 200)
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 += 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++ 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++} 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++ 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 assert from "node:assert/strict"
import { parseMonitorTraffic, rateBpsFromDelta, bpsToMbps } from "./traffic-rate.js" 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" 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}) 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")]]) { 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"> }} as unknown as Pick<MikrotikClient,"get"|"post">
const bounded=await readTrafficLiveSample(many,undefined,{names:[],joinedFailed:false},new AbortController().signal,async()=>{}) const bounded=await readTrafficLiveSample(many,undefined,{names:[],joinedFailed:false},new AbortController().signal,async()=>{})
assert.equal(bounded.rxMbps,0);assert.equal(maximum,4) 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") 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 { 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 const TIMEOUT_MS = 4000
export class TrafficLiveSourceChanged extends Error {} export class TrafficLiveSourceChanged extends Error {}
export interface TrafficLiveCache { names: string[]; joinedFailed: boolean } export interface TrafficLiveCache { names: string[]; joinedFailed: boolean }
type Client = Pick<MikrotikClient, "get" | "post"> 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. */ /** Check the source before every new native request. */
export async function readTrafficLiveSample(client: Client, onlyInterface: string | undefined, async function withTrafficMonitor<T>(client: Client, signal: AbortSignal, assertSource: () => Promise<void>,
cache: TrafficLiveCache, signal: AbortSignal, assertSource: () => Promise<void>): Promise<MonitorLiveSample> { read: (monitor: Monitor, ensure: () => Promise<void>) => Promise<T>): Promise<T> {
const parentSignal = signal, wave = new AbortController() const parentSignal = signal, wave = new AbortController()
const onAbort = () => wave.abort(parentSignal.reason) const onAbort = () => wave.abort(parentSignal.reason)
parentSignal.addEventListener("abort", onAbort, { once: true }) 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) const timeout = setTimeout(() => wave.abort(new Error("Не успели получить полный live-срез за 8 секунд. Выберите отдельный интерфейс")), 8000)
signal = wave.signal signal = wave.signal
try { try {
const ensure = async () => { signal.throwIfAborted(); await assertSource(); signal.throwIfAborted() } const ensure = async () => { signal.throwIfAborted(); await assertSource(); signal.throwIfAborted() }
const monitor = async (name: string) => { 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(","))
await ensure() await ensure()
return parseMonitorTraffic(result, { expectedInterfaces: names }) return client.post<unknown>("/interface/monitor-traffic", { interface: name, once: "" }, TIMEOUT_MS, signal)
} 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 await read(monitor, ensure)
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" }
} catch (error) { } catch (error) {
if (signal.aborted && !parentSignal.aborted && signal.reason instanceof Error) throw signal.reason if (signal.aborted && !parentSignal.aborted && signal.reason instanceof Error) throw signal.reason
throw error throw error
@@ -71,3 +32,71 @@ export async function readTrafficLiveSample(client: Client, onlyInterface: strin
wave.abort() 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) } } : acc,waves)
} }
export function parseMonitorTraffic( type MonitorTrafficSelection = { onlyInterface?: string; expectedInterfaces?: readonly string[]; allowMissing?: boolean }
raw: unknown,
opts?: { onlyInterface?: string; expectedInterfaces?: readonly string[] }, function monitorTrafficRates(raw: unknown, opts?: MonitorTrafficSelection) {
): MonitorLiveSample {
const items = Array.isArray(raw) ? raw : raw != null ? [raw] : [] const items = Array.isArray(raw) ? raw : raw != null ? [raw] : []
let rxBps = 0 const samples = new Map<string, { rxBps: number; txBps: number }>()
let txBps = 0
const seen = new Set<string>()
const expected = opts?.expectedInterfaces ? new Set(opts.expectedInterfaces) : null const expected = opts?.expectedInterfaces ? new Set(opts.expectedInterfaces) : null
const rate = (raw: unknown) => { const rate = (raw: unknown) => {
if (typeof raw !== "number" && (typeof raw !== "string" || !/^(?:\d+(?:\.\d+)?|\.\d+)$/.test(raw.trim()))) throw new Error("Некорректная скорость monitor-traffic") 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 (typeof name !== "string" || !name.trim()) throw new Error("Не указан интерфейс monitor-traffic")
if (opts?.onlyInterface) { if (opts?.onlyInterface) {
if (name !== opts.onlyInterface) throw new Error("Ответ monitor-traffic относится к другому интерфейсу") if (name !== opts.onlyInterface) throw new Error("Ответ monitor-traffic относится к другому интерфейсу")
} else if (isLoopbackName(name)) { } else if (isLoopbackName(name) && !expected?.has(name)) {
continue continue
} }
if (seen.has(name) || expected && !expected.has(name)) throw new Error("Некорректный набор интерфейсов monitor-traffic") if (samples.has(name) || expected && !expected.has(name)) throw new Error("Некорректный набор интерфейсов monitor-traffic")
seen.add(name) samples.set(name, {
rxBps += rate(rec["rx-bits-per-second"]) rxBps: rate(rec["rx-bits-per-second"]),
txBps += rate(rec["tx-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 (!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" }
} }
+1 -1
View File
@@ -72,7 +72,7 @@ export async function getSettings() {
retentionDays: 14, retentionDays: 14,
createdAt: now, createdAt: now,
updatedAt: now, updatedAt: now,
}) }).onConflictDoNothing({ target: uptimeSettings.id })
return (await db.select().from(uptimeSettings).where(eq(uptimeSettings.id, 1)).limit(1))[0] return (await db.select().from(uptimeSettings).where(eq(uptimeSettings.id, 1)).limit(1))[0]
} }
+21 -81
View File
@@ -1,7 +1,7 @@
"use client" "use client"
import * as React from "react" 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 { AppSwitcher } from "@/components/app-switcher"
import { NavUser } from "@/components/nav-user" import { NavUser } from "@/components/nav-user"
import { import {
@@ -12,103 +12,43 @@ import {
} from "@/components/ui/sidebar" } from "@/components/ui/sidebar"
import { navigationGroups } from "@/lib/navigation" import { navigationGroups } from "@/lib/navigation"
import { useDataSource } from "@/lib/data-source" import { useDataSource } from "@/lib/data-source"
import { can,ensureAuthConfig } from "@/lib/auth" import { pingProbes, servers } from "@/lib/data"
import { useEvoBGP } from "@/lib/evobgp-context"
import {getSidebarCounts,getSidebarGreCount} from "@/shared/api/sidebar-counts"
import {
formatSidebarBadgeCount,
mockSidebarBadgesByUrl,
type SidebarCountsDto,
} from "@/lib/sidebar-badges"
type LiveSidebarCounts = Partial<SidebarCountsDto> & { /**
greTunnels?: number * Точки проблем у разделов. В демо — из моков; живой источник проблем по разделам API пока не отдаёт,
certificates?: number * поэтому в live-режиме точек нет (неизвестное не выдаём за «всё в норме» и не рисуем ложные сбои).
wireguard?: number */
ipsec?: number function demoProblems(): Record<string, NavItem["problem"]> {
users?: number const offline = servers.filter((s) => s.enabled && s.status === "offline").length
bgpSessions?: number const degraded = servers.filter((s) => s.enabled && s.status === "degraded").length
vxlan?: number const down = pingProbes.filter((p) => p.enabled && p.status === "down").length
containers?: number 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>) { export function AppSidebar({ ...props }: React.ComponentProps<typeof Sidebar>) {
const { mode, backendUrl, prefsHydrated } = useDataSource() const { mode, 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 navGroups = React.useMemo((): NavGroup[] => { const navGroups = React.useMemo((): NavGroup[] => {
function badgeFor(url: string): string | undefined { const problems = prefsHydrated && mode !== "live" ? demoProblems() : {}
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
}
return navigationGroups.map((g) => ({ return navigationGroups.map((g) => ({
label: g.label, label: g.label,
items: g.items.map((it) => ({ items: g.items.map((it) => ({
title: it.title, title: it.title,
url: it.url, url: it.url,
icon: React.createElement(it.icon, { "aria-hidden": true }), 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 ( return (
<Sidebar collapsible="icon" {...props}> <Sidebar collapsible="icon" {...props}>
<SidebarHeader> <SidebarHeader className="pb-1.5">
<AppSwitcher /> <AppSwitcher />
</SidebarHeader> </SidebarHeader>
<SidebarContent> <SidebarContent>
+11 -1
View File
@@ -5,6 +5,7 @@ import {
DropdownMenu, DropdownMenu,
DropdownMenuContent, DropdownMenuContent,
DropdownMenuItem, DropdownMenuItem,
DropdownMenuSeparator,
DropdownMenuShortcut, DropdownMenuShortcut,
DropdownMenuTrigger, DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu" } from "@/components/ui/dropdown-menu"
@@ -17,6 +18,7 @@ import {
import { import {
APP_SWITCHER_ICONS, APP_SWITCHER_ICONS,
CURRENT_APP_ID, CURRENT_APP_ID,
authPortalBaseUrl,
getCurrentApp, getCurrentApp,
} from "@/lib/app-switcher-config" } from "@/lib/app-switcher-config"
import { useAppSwitcherConfig } from "@/hooks/use-app-switcher" import { useAppSwitcherConfig } from "@/hooks/use-app-switcher"
@@ -26,6 +28,8 @@ export function AppSwitcher() {
const { isMobile } = useSidebar() const { isMobile } = useSidebar()
const { config, isLoading } = useAppSwitcherConfig() const { config, isLoading } = useAppSwitcherConfig()
const current = getCurrentApp(config) 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 const CurrentIcon = APP_SWITCHER_ICONS[current.icon] ?? APP_SWITCHER_ICONS.server
return ( return (
@@ -34,7 +38,7 @@ export function AppSwitcher() {
<DropdownMenu> <DropdownMenu>
<DropdownMenuTrigger <DropdownMenuTrigger
render={ render={
<SidebarMenuButton size="lg" className="aria-expanded:bg-muted" /> <SidebarMenuButton size="lg" aria-label={`Переключатель приложений: ${current.name}`} className="aria-expanded:bg-muted" />
} }
> >
<div <div
@@ -89,6 +93,12 @@ export function AppSwitcher() {
</DropdownMenuItem> </DropdownMenuItem>
) )
})} })}
{portalAppsUrl ? (
<>
<DropdownMenuSeparator />
<DropdownMenuItem render={<a href={portalAppsUrl} />}>Настроить на портале</DropdownMenuItem>
</>
) : null}
</DropdownMenuContent> </DropdownMenuContent>
</DropdownMenu> </DropdownMenu>
</SidebarMenuItem> </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 { Command, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList } from "@/components/ui/command"
import { Dialog, DialogContent, DialogDescription, DialogTitle } from "@/components/ui/dialog" 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. */ /** Keyboard search from the App Shell 12 composition, using installed Base UI primitives. */
export function CommandPalette() { export function CommandPalette() {
const [open, setOpen] = useState(false) const [open, setOpen] = useState(false)
@@ -26,8 +33,18 @@ export function CommandPalette() {
setOpen(!open) setOpen(!open)
} }
} }
function onOpen() {
if (open) return
returnFocusRef.current = document.activeElement instanceof HTMLElement ? document.activeElement : null
setQuery("")
setOpen(true)
}
window.addEventListener("keydown", onKey) 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]) }, [open])
useEffect(() => { 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" "use client"
import { useEffect, useState } from "react"
import Link from "next/link" 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 { buttonVariants } from "@/components/ui/button"
import { import { Alert, AlertDescription, AlertTitle } from "@/components/reui/alert"
Collapsible, import { SectionFrame, TONE_COLOR, type Tone } from "@/components/reui-kit/ops-blocks"
CollapsibleContent,
CollapsibleTrigger,
} from "@/components/ui/collapsible"
import { cn } from "@/lib/utils"
import type { InternetPathViewModel } from "@/lib/dashboard-internet-path" 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" 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 { type TopoNode = { label: string; sub: string; tone: Tone }
if (typeof window === "undefined") return true
try { /** Схема пути Home → WAN → JH → Exit (блок topo макета v3); участок WAN→JH — модель связности, пунктиром. */
const raw = localStorage.getItem(PATH_MAP_OPEN_LS) function InternetPathTopo({ model }: { model: InternetPathViewModel | null }) {
if (raw === "0") return false const hop = model?.currentHop ?? model?.primaryHop ?? null
if (raw === "1") return true const wan = hop?.wan ?? model?.activeWanUplink ?? null
} catch { const jh = hop?.jumpHost ?? model?.fallbackJumpHost ?? null
/* ignore */ 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({ export function InternetPathPanel({
model, model,
loading, loading,
@@ -39,59 +66,30 @@ export function InternetPathPanel({
loading?: boolean loading?: boolean
error?: string | null 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 ( return (
<OpsPanel <>
title="Internet path" <SectionFrame
description="Home → WAN → JH → Exit" title="Internet path"
headerRight={ description="Home → WAN → JH → Exit · пунктир WAN→JH — модель связности, маршрут не подтверждён"
<Link href="/network-map" className={cn(buttonVariants({ variant: "outline", size: "sm" }), "h-7 text-xs")}> 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]"
</Link> >
} {error ? (
contentClassName="flex flex-col gap-3 px-5 pb-4" <Alert variant="destructive" className="m-3 w-auto">
> <AlertTitle>Не удалось загрузить путь</AlertTitle>
{error ? ( <AlertDescription>{error}</AlertDescription>
<Alert variant="destructive"> </Alert>
<AlertTitle>Не удалось загрузить путь</AlertTitle> ) : null}
<AlertDescription>{error}</AlertDescription> <div className="min-w-[720px]">
</Alert> {loading && !model ? <div className="bg-muted/40 m-4 h-[268px] animate-pulse rounded-md" /> : <InternetPathTopo model={model} />}
) : null} </div>
{loading && !model ? ( </SectionFrame>
<div className="h-20 animate-pulse rounded-md bg-muted/40" /> <SectionFrame
) : ( title="Сводка маршрута"
<InternetPathSummary model={model} /> description={`Модель связности; маршрут не подтверждён. ${model?.currentPath?.reason ?? "Текущий маршрут не подтверждён"}`}
)} >
{loading && !model ? <div className="bg-muted/40 m-4 h-20 animate-pulse rounded-md" /> : <InternetPathSummary model={model} />}
<Collapsible open={hydrated ? open : true} onOpenChange={handleOpenChange}> </SectionFrame>
<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>
) )
} }
+30 -85
View File
@@ -3,13 +3,10 @@
import type { ReactNode } from "react" import type { ReactNode } from "react"
import Link from "next/link" import Link from "next/link"
import { Badge } from "@/components/reui/badge" import { Badge } from "@/components/reui/badge"
import { IconTile } from "@/components/reui/icon-tile"
import { StatusBadge } from "@/components/status-badge" import { StatusBadge } from "@/components/status-badge"
import { Flag } from "@/components/flag" import { Flag } from "@/components/flag"
import type { InternetPathViewModel } from "@/lib/dashboard-internet-path" import type { InternetPathViewModel } from "@/lib/dashboard-internet-path"
import type { ServerStatus } from "@/lib/data" 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 { function pathStateToServerStatus(state: InternetPathViewModel["pathState"]): ServerStatus {
if (state === "healthy") return "online" if (state === "healthy") return "online"
@@ -17,44 +14,32 @@ function pathStateToServerStatus(state: InternetPathViewModel["pathState"]): Ser
return "unknown" return "unknown"
} }
function HopChip({ function Kv({ label, children }: { label: string; children: ReactNode }) {
label,
name,
country,
icon,
iconClassName,
}: {
label: string
name: string
country?: string
icon: ReactNode
iconClassName?: string
}) {
return ( return (
<div className="flex min-w-0 items-center gap-2 rounded-md border border-border/60 px-2 py-1.5"> <div className="min-w-0">
<IconTile variant="elevated" size="sm" className={cn("shrink-0", iconClassName)} aria-hidden="true"> <small className="text-muted-foreground block text-xs">{label}</small>
{icon} <b className="mt-0.5 flex min-w-0 items-center gap-1.5 font-mono text-[13px] font-medium">{children}</b>
</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> </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. * Сводка маршрута (блок kv макета v3): узлы пути и последние подтверждённые метрики участка WAN → JH.
* Preview: https://reui.io/preview/base/stats-12 * Docs: https://reui.io/docs/components/base/frame
* Docs: https://reui.io/docs/components/base/icon-tile
*/ */
export function InternetPathSummary({ model }: { model: InternetPathViewModel | null }) { export function InternetPathSummary({ model }: { model: InternetPathViewModel | null }) {
if (!model) { if (!model) {
return ( return (
<p className="text-muted-foreground text-sm"> <p className="text-muted-foreground px-4 py-3.5 text-sm">
Недостаточно данных для пути. Добавьте home-router и проверьте{" "} Недостаточно данных для пути. Добавьте home-router и проверьте{" "}
<Link href="/network-map" className="underline underline-offset-2"> <Link href="/network-map" className="underline underline-offset-2">
карту сети карту сети
@@ -71,61 +56,21 @@ export function InternetPathSummary({ model }: { model: InternetPathViewModel |
const dl = hop?.wanJhMetrics.dlMbps const dl = hop?.wanJhMetrics.dlMbps
return ( return (
<div className="flex flex-col gap-3"> <div className="flex flex-col gap-3 px-4 py-3.5">
<div className="flex flex-wrap items-center gap-2"> <div className="grid grid-cols-1 gap-x-3.5 gap-y-3 sm:grid-cols-2">
<StatusBadge status={pathStateToServerStatus(model.pathState)} /> <Kv label="Маршрут">Home → WAN → JH → Exit</Kv>
{model.pathState === "failover" ? ( <Kv label="Состояние">
<Badge variant="warning-light" size="sm">failover</Badge> <StatusBadge status={pathStateToServerStatus(model.pathState)} />
) : null} {model.pathState === "failover" ? <Badge variant="warning-light" size="sm">failover</Badge> : null}
{ping != null ? ( </Kv>
<Badge variant="outline" size="sm" className="tabular-nums"> <Kv label="RTT WAN → JH">{ping != null ? <span className="tabular-nums">{`${ping} мс`}</span> : "—"}</Kv>
{ping} мс <Kv label="Загрузка WAN → JH">{dl != null ? <span className="tabular-nums">{`${Math.round(dl)} ↓ Мбит/с`}</span> : "—"}</Kv>
</Badge> <Kv label="Home"><Node name={model.homeRouter.name} country={model.homeRouter.country} /></Kv>
) : null} <Kv label="Активный WAN"><span className="truncate">{`${wanName} · ${wanIsp}`}</span></Kv>
{dl != null ? ( <Kv label="JumpHost"><Node name={hop?.jumpHost.name ?? model.fallbackJumpHost?.name ?? "—"} country={hop?.jumpHost.country ?? model.fallbackJumpHost?.country} /></Kv>
<Badge variant="outline" size="sm" className="tabular-nums"> <Kv label="Exit"><Node name={hop?.exitNode.name ?? model.fallbackExitNode?.name ?? "—"} country={hop?.exitNode.country ?? model.fallbackExitNode?.country} /></Kv>
{Math.round(dl)} ↓ Мбит/с
</Badge>
) : null}
</div> </div>
<p className="text-muted-foreground border-t border-dashed pt-2.5 text-xs">JH/Exit — схема кандидатов. Default route подтверждает только WAN. Метрики — последние подтверждённые пробы участков.</p>
<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>
</div> </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" "use client"
import { useEffect, useState } from "react"
import Link from "next/link" import Link from "next/link"
import { usePathname } from "next/navigation" import { usePathname } from "next/navigation"
import { ChevronDownIcon, SearchIcon, StarIcon } from "lucide-react"
import { import {
SidebarGroup, SidebarGroup,
SidebarGroupContent,
SidebarGroupLabel, SidebarGroupLabel,
SidebarMenu, SidebarMenu,
SidebarMenuAction,
SidebarMenuButton, SidebarMenuButton,
SidebarMenuItem, SidebarMenuItem,
SidebarSeparator,
useSidebar, useSidebar,
} from "@/components/ui/sidebar" } from "@/components/ui/sidebar"
import { Kbd } from "@/components/ui/kbd"
import { cn } from "@/lib/utils"
import { openCommandPalette } from "@/components/command-palette"
export interface NavItem { export interface NavItem {
title: string title: string
url: string url: string
icon?: React.ReactNode icon?: React.ReactNode
/** Если `undefined` — счётчик не показываем (нет данных или раздел без live-источника). */ /** Точка проблемы у пункта: сбой (er) или внимание (wn); без данных — не показываем. */
badge?: string problem?: { tone: "er" | "wn"; label: string }
} }
export interface NavGroup { export interface NavGroup {
@@ -24,36 +32,144 @@ export interface NavGroup {
items: NavItem[] 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 pathname = usePathname()
const { setOpenMobile } = useSidebar() 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 ( return (
<nav aria-label="Основная навигация"> <nav aria-label="Основная навигация" className="flex flex-col">
{groups.map((group) => ( <SidebarGroup className="pb-1">
<SidebarGroup key={group.label}> <SidebarMenu>
<SidebarGroupLabel>{group.label}</SidebarGroupLabel> <SidebarMenuItem>
<SidebarMenu> <SidebarMenuButton
{group.items.map((item) => ( tooltip="Поиск и команды"
<SidebarMenuItem key={item.title}> onClick={openCommandPalette}
<SidebarMenuButton className="border-sidebar-border text-sidebar-foreground/70 border"
isActive={pathname === item.url} >
tooltip={item.title} <SearchIcon aria-hidden />
render={<Link href={item.url} aria-current={pathname === item.url ? "page" : undefined} onNavigate={() => setOpenMobile(false)} />} <span>Поиск и команды</span>
> <Kbd className="ml-auto group-data-[collapsible=icon]:hidden">⌘K</Kbd>
{item.icon} </SidebarMenuButton>
<span>{item.title}</span> </SidebarMenuItem>
{item.badge != null && item.badge !== "" && ( </SidebarMenu>
<span className="ml-auto text-[10.5px] font-mono tabular-nums text-sidebar-foreground/50 group-data-[collapsible=icon]:hidden"> </SidebarGroup>
{item.badge}
</span> {pinned.length > 0 ? (
)} <SidebarGroup className="py-0 group-data-[collapsible=icon]:hidden">
</SidebarMenuButton> <SidebarGroupLabel className="text-xs font-semibold tracking-wide uppercase">Закреплённые</SidebarGroupLabel>
</SidebarMenuItem> <SidebarGroupContent>
))} <SidebarMenu className="gap-px">
</SidebarMenu> {pinned.map((item) => <NavEntry key={item.url} item={item} pinned onTogglePin={() => togglePin(item.url)} />)}
</SidebarMenu>
</SidebarGroupContent>
</SidebarGroup> </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> </nav>
) )
} }
+36 -32
View File
@@ -1,46 +1,50 @@
"use client" "use client"
import { useEffect, useRef } from "react" import { useEffect, useRef } from "react"
import { Badge } from "@/components/ui/badge" import { InfoIcon } from "lucide-react"
export function NetworkMapLegend() { 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) const details = useRef<HTMLDetailsElement>(null)
useEffect(() => { useEffect(() => {
if (window.matchMedia("(max-width: 767px)").matches && details.current) details.current.open = false if (compact && details.current) details.current.open = false
}, []) }, [compact])
const head = "text-muted-foreground mt-1 text-[11px] font-semibold tracking-wider uppercase"
return ( 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"> <details ref={details} data-map-legend className="relative">
<summary className="cursor-pointer px-3 py-2 text-xs font-semibold focus-visible:outline-2 focus-visible:outline-ring">Легенда карты</summary> <summary className="border-border bg-background hover:bg-muted/60 text-foreground flex h-8 cursor-pointer list-none items-center gap-1.5 rounded-lg border px-2.5 text-[13px] font-medium transition-colors focus-visible:outline-2 focus-visible:outline-ring [&::-webkit-details-marker]:hidden [[open]>&]:bg-muted">
<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]"> <InfoIcon aria-hidden="true" className="size-4" />Легенда
<div> </summary>
<p className="mb-1.5 font-medium text-muted-foreground">Статус устройства</p> <div role="region" aria-label="Легенда карты" className="bg-popover text-popover-foreground absolute top-full right-0 z-30 mt-1 max-sm:fixed max-sm:inset-x-4 max-sm:top-auto max-sm:w-auto flex max-h-[60vh] w-[310px] max-w-[calc(100vw-2rem)] flex-col gap-2 overflow-y-auto rounded-lg border p-3 text-xs shadow-lg">
<div className="grid grid-cols-2 gap-x-2 gap-y-1.5"> <p className={head}>Статус</p>
{[["var(--status-online)", "Онлайн"], ["var(--status-degraded)", "Внимание"], ["var(--status-offline)", "Оффлайн"], ["var(--muted-foreground)", "Неизвестно"]].map(([color, label]) => ( <div className="grid grid-cols-2 gap-x-2.5 gap-y-1.5">
<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> {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>
</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>
))} ))}
<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>
<div className="flex flex-col gap-1.5"> <p className={head}>Узлы</p>
<p className="font-medium text-muted-foreground">Связи и измерения</p> <div className="grid grid-cols-2 gap-x-2.5 gap-y-1.5">
{[ {ROLES.map(([label, name, color]) => (
["GRE", "var(--status-online)", undefined], <span key={label} className="flex items-center gap-2">
["GRE + IPsec", "var(--status-online)", "7 4"], <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>
["Поток NetFlow", "var(--chart-4)", "6 5"], </span>
["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="text-muted-foreground">RTT · задержка пробы. «—» · нет измерения.</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>
<p className="text-muted-foreground">NetFlow · трафик за 5 минут, не пропускная способность канала.</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="3" fill="none" stroke="var(--muted-foreground)" strokeWidth="1.5" /></svg>Сервис / страна</span>
</div> </div>
<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"><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" strokeDasharray="8 5" /></svg>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" strokeDasharray="4 5" /></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)" strokeWidth="2" strokeDasharray="2 6" strokeLinecap="round" /></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)" strokeOpacity="0.55" strokeWidth="6" /></svg>Лента NetFlow · толщина = скорость</span>
</div>
<p className="text-muted-foreground leading-snug">Live — последний замер RX/TX интерфейса RouterOS. «≈» и ленты NetFlow показывают среднюю скорость по принятым записям IPFIX. RTT — задержка пробы, «—» означает, что нет измерения.</p>
</div> </div>
</details> </details>
) )
@@ -0,0 +1,146 @@
"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 } 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 } 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 { projectTrafficObservations } from "@/lib/traffic-observations"
import { getFlowAnalytics, getFlowMapHops } from "@/shared/api/traffic-flow"
import { requestJson } from "@/shared/api/http-client"
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 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 }: {
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: { viaId: string; enId: string; serviceId: string } | null; onPath: (path: FlowMapServicePath) => void
onClose: () => void; filtered: boolean; onFilter: () => void
}) {
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 !== "Прочее"
useEffect(() => {
if (base === null) return
const controller = new AbortController()
const init = { signal: controller.signal }
if (canMatchService) void getFlowAnalytics(base, { range: "5m" }, init)
.then(data => { if (!controller.signal.aborted) setRecent({data, at: new Date().toISOString()}) })
.catch(() => { if (!controller.signal.aborted) setRecent(null) })
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])
const flows = recent?.data.conversationsList.filter(row => {
const categoryFallback = row.category === service.label && (row.service === "Прочее" || ["DNS", "SSH", "BGP"].includes(row.category))
if (row.service !== service.label && !categoryFallback) return false
if (!country) return true
if (service.id.startsWith("cc:other|")) return !row.dstCountry || row.dstCountry.toLowerCase() === "unknown"
return row.dstCountry?.toUpperCase() === country.toUpperCase()
})
.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.map(e => e.fromId), ...paths.map(p => p.enId)])]
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
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>}</>],
["Exit-узел", exitIds.map(exitName).join(", ") || "—", remainder ? "Часть трафика без подтверждённого выхода" : undefined],
]} />
<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 active = activePath?.viaId === p.viaId && activePath.enId === p.enId && activePath.serviceId === p.serviceId
return <button type="button" key={JSON.stringify([p.clientId,p.viaId,p.enId])} onClick={() => onPath(p)} aria-pressed={active} title={formatNetflowRate({bps:p.bps})} 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>)}
</button>
})}
{rates.filter(e => !paths.some(p => p.enId === e.fromId)).map(e => <div key={e.fromId} className="flex justify-between gap-2 text-xs"><span>{exitName(e.fromId)} → {service.label}</span><span className="shrink-0 font-mono">{formatNetflowRate({bps:e.bps})}</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">
<Button size="xs" nativeButton={false} render={<Link href="/traffic" />}>Открыть в «Трафике»</Button>
<Button size="xs" variant="outline" aria-pressed={filtered} onClick={onFilter}>{filtered ? "Снять фильтр" : "Фильтр по сервису"}</Button>
</div>
</div>
</>
}
+172
View File
@@ -0,0 +1,172 @@
"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"
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 }
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, eventsError, stat }: {
tab: MapBottomTab
onTab: (tab: MapBottomTab) => void
flows: MapFlowRow[]
rtt: MapRttRow[]
destinations: MapDestRow[]
events: MapEventRow[]
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={["Источник", "Exit", "Назначение", "Скорость", "Объём"]} 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>
<span className="truncate font-medium">{r.title}</span>
<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" "use client"
import { Fragment, type ReactNode } from "react" import { Fragment, type ReactNode } from "react"
import { usePathname } from "next/navigation"
import { InfoIcon, SearchIcon } from "lucide-react"
import { Separator } from "@/components/ui/separator" import { Separator } from "@/components/ui/separator"
import { SidebarTrigger } from "@/components/ui/sidebar" 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 { import {
Breadcrumb, Breadcrumb,
BreadcrumbItem, BreadcrumbItem,
@@ -11,8 +16,8 @@ import {
BreadcrumbPage, BreadcrumbPage,
BreadcrumbSeparator, BreadcrumbSeparator,
} from "@/components/ui/breadcrumb" } from "@/components/ui/breadcrumb"
import { AppsMenu } from "@/components/apps-menu"
import { SystemMonitorPopover } from "@/components/system-monitor-popover" import { SystemMonitorPopover } from "@/components/system-monitor-popover"
import { openCommandPalette } from "@/components/command-palette"
interface Crumb { interface Crumb {
label: string label: string
@@ -22,23 +27,57 @@ interface Crumb {
interface PageHeaderProps { interface PageHeaderProps {
crumbs: Crumb[] crumbs: Crumb[]
actions?: ReactNode actions?: ReactNode
/** Состояние данных страницы в шапке, например `<DataFreshness />`. */
status?: ReactNode
} }
/** Header chrome — AppsMenu + SystemMonitor; theme in NavUser. @see https://reui.io/preview/base/app-shell-12 */ /** Откуда раздел берёт данные — окно «Источники и свежесть данных» (как в шапке EvoBGP и макета v2). */
export function PageHeader({ crumbs, actions }: PageHeaderProps) { 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 ( 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" /> <SidebarTrigger className="-ml-1" />
<Separator orientation="vertical" className="mr-2 data-[orientation=vertical]:h-4" /> <Separator orientation="vertical" className="mr-2 data-[orientation=vertical]:h-4" />
<Breadcrumb aria-label="Путь страницы" className="min-w-0 flex-1"> <Breadcrumb aria-label="Путь страницы" className="min-w-0 flex-1">
<BreadcrumbList className="flex-nowrap"> <BreadcrumbList className="flex-nowrap">
{crumbs.map((crumb, i) => ( {trail.map((crumb, i) => (
<Fragment key={i}> <Fragment key={i}>
{i > 0 && <BreadcrumbSeparator className="hidden shrink-0 sm:block" />} {i > 0 && <BreadcrumbSeparator className="text-muted-foreground hidden shrink-0 sm:block">/</BreadcrumbSeparator>}
<BreadcrumbItem className={i < crumbs.length - 1 ? "hidden shrink-0 sm:inline-flex" : "min-w-0"}> <BreadcrumbItem className={i < trail.length - 1 ? "hidden shrink-0 sm:inline-flex" : "min-w-0"}>
{i < crumbs.length - 1 && crumb.href ? ( {i < trail.length - 1 && crumb.href ? (
<BreadcrumbLink href={crumb.href}>{crumb.label}</BreadcrumbLink> <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> <span className="text-muted-foreground text-sm">{crumb.label}</span>
) : ( ) : (
<BreadcrumbPage className="wrap-anywhere">{crumb.label}</BreadcrumbPage> <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"}`}> <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} {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"> <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 /> <SystemMonitorPopover />
</div> </div>
</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>
)
}
@@ -1,7 +1,8 @@
"use client" "use client"
import { Area, AreaChart, CartesianGrid, XAxis, YAxis } from "recharts" 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 { ChartContainer, ChartTooltip, type ChartConfig } from "@/components/ui/chart"
import { formatBytes } from "@/lib/fmt-rate" import { formatBytes } from "@/lib/fmt-rate"
import type { StatisticsSeriesPoint } from "@mmapp/contracts/statistics" import type { StatisticsSeriesPoint } from "@mmapp/contracts/statistics"
@@ -45,9 +46,14 @@ function CustomTooltip({
export function StatisticsVolumeChart({ export function StatisticsVolumeChart({
series, series,
grain, grain,
scope,
actions,
}: { }: {
series: StatisticsSeriesPoint[] series: StatisticsSeriesPoint[]
grain: "hour" | "day" grain: "hour" | "day"
/** Какие плоскости в объёме, для подписи под заголовком. */
scope?: string
actions?: ReactNode
}) { }) {
const data = series.map((p) => ({ const data = series.map((p) => ({
t: p.t, t: p.t,
@@ -57,14 +63,12 @@ export function StatisticsVolumeChart({
const tickEvery = Math.max(1, Math.ceil(data.length / 8)) const tickEvery = Math.max(1, Math.ceil(data.length / 8))
return ( return (
<Frame className="w-full"> <SectionFrame
<FramePanel className="flex flex-col gap-4"> title="Объём по времени"
<div className="flex items-baseline justify-between gap-2"> description={[scope, grain === "hour" ? "по часам" : "по суткам"].filter(Boolean).join(" · ")}
<h2 className="text-sm font-medium">Объём по времени</h2> actions={actions}
<span className="text-muted-foreground text-xs"> panelClassName="px-3.5 pt-3.5 pb-2"
{grain === "hour" ? "по часам" : "по суткам"} >
</span>
</div>
{data.length === 0 ? ( {data.length === 0 ? (
<p className="text-muted-foreground py-10 text-center text-sm">Нет данных за выбранный период</p> <p className="text-muted-foreground py-10 text-center text-sm">Нет данных за выбранный период</p>
) : ( ) : (
@@ -99,7 +103,6 @@ export function StatisticsVolumeChart({
</AreaChart> </AreaChart>
</ChartContainer> </ChartContainer>
)} )}
</FramePanel> </SectionFrame>
</Frame>
) )
} }
+64 -45
View File
@@ -1,7 +1,8 @@
"use client" "use client"
import { useEffect, useMemo, useState, type ReactNode } from "react" 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 { Badge } from "@/components/reui/badge"
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover" import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover"
@@ -151,7 +152,15 @@ export function SystemMonitorPopover() {
[apiOk, filtersCount, healthOk, monitoringCount, serversCount], [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 ( return (
<Popover> <Popover>
@@ -159,63 +168,73 @@ export function SystemMonitorPopover() {
render={ render={
<button <button
type="button" type="button"
aria-label="Монитор системы" aria-label={`Состояние системы: ${label.toLowerCase()}, сбоев ${errors}, предупреждений ${warnings}`}
className={cn( className={cn(
"relative inline-flex h-8 items-center gap-1.5 rounded-md border px-2 transition-colors outline-none", "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",
"border-border hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring", 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-4", tone === "destructive" ? "text-destructive" : tone === "warning" ? "text-warning" : "text-success")} />
<Activity <span className={cn("hidden min-[1000px]:inline", tone === "destructive" ? "text-destructive-foreground" : tone === "warning" ? "text-warning-foreground" : "text-foreground")}>{label}</span>
aria-hidden <span className="hidden items-center gap-1.5 tabular-nums min-[1240px]:inline-flex">
className={cn( <span className="bg-destructive size-1.5 rounded-full" aria-hidden />
"size-3.5 transition-colors", {errors}
spiking ? "text-destructive" : "text-muted-foreground", <span className="bg-warning size-1.5 rounded-full" aria-hidden />
)} {warnings}
/>
{spiking ? (
<span className="bg-destructive/25 absolute inset-0 animate-ping rounded-full" aria-hidden />
) : null}
</span> </span>
<span className="text-foreground hidden text-xs font-medium sm:inline">Система</span> {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}
<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>
</PopoverTrigger> </PopoverTrigger>
<PopoverContent align="end" sideOffset={8} className="flex w-80 max-w-[calc(100vw-2rem)] flex-col gap-0! p-0!"> <PopoverContent align="end" sideOffset={8} className="flex w-[24rem] max-w-[calc(100vw-1.5rem)] flex-col gap-2 p-2">
<div className="border-border flex items-center justify-between border-b px-3 py-2.5"> <div className="flex items-start justify-between gap-2 px-1.5 pt-1.5">
<span className="text-foreground text-xs font-medium">Монитор MikrotikManager</span> <div className="grid leading-tight">
<span className="text-muted-foreground text-[11px] tabular-nums"> <b className="text-sm font-semibold">Состояние системы</b>
{mode!=="live"?"Демо":data?.receivedAt?new Date(data.receivedAt).toLocaleTimeString("ru-RU"):"Снимок не получен"} <span className="text-muted-foreground text-xs">
</span> {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> </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-3 gap-1.5">
<div className="grid grid-cols-2"> {[
{ 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) => ( {metrics.map((metric, i) => (
<div <div key={metric.id} className={cn(i % 2 === 1 && "border-l", i >= 2 && "border-t")}>
key={metric.id}
className={cn(
i % 2 === 1 && "border-border border-l",
i >= 2 && "border-border border-t",
)}
>
<MetricCell metric={metric} /> <MetricCell metric={metric} />
</div> </div>
))} ))}
</div> </div>
<div className="border-border text-muted-foreground border-t px-3 py-2 text-[11px]"> <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">
Источник:{" "} Мониторинг
<span className="text-foreground font-medium"> <ArrowRightIcon className="size-3.5" aria-hidden />
{mode === "live" ? "API" : "мок"} </Link>
</span>
</div>
</PopoverContent> </PopoverContent>
</Popover> </Popover>
) )
+9 -9
View File
@@ -74,22 +74,22 @@ export function FlowEntityCardView({
<StatusDot status={card.status} /> <StatusDot status={card.status} />
<span className="text-xs font-medium truncate">{card.name}</span> <span className="text-xs font-medium truncate">{card.name}</span>
</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">
{card.country !== "UN" ? <Flag code={card.country} /> : null} {card.country !== "UN" ? <Flag code={card.country} /> : null}
{card.site} {card.site}
</span> </span>
</div> </div>
<TrafficMiniChart rx={card.rxSeries} tx={card.txSeries} /> <TrafficMiniChart rx={card.rxSeries} tx={card.txSeries} />
<div className="flex justify-between mt-2 gap-2"> <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" /> <ArrowDownIcon className="size-3 text-success" />
<span className="font-mono font-medium text-success">{fmtRate(card.rxNow)}</span> <span className="font-mono font-medium text-success">{fmtRate(card.rxNow)}</span>
</div> </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" /> <ArrowUpIcon className="size-3 text-info" />
<span className="font-mono font-medium text-info">{fmtRate(card.txNow)}</span> <span className="font-mono font-medium text-info">{fmtRate(card.txNow)}</span>
</div> </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} <GitBranchIcon className="size-3" />{card.sessions}
</div> </div>
</div> </div>
@@ -265,7 +265,7 @@ function FlowPathsGrid({
cell: ({ row }) => ( cell: ({ row }) => (
<span className="flex min-w-0 flex-col gap-0.5 text-xs"> <span className="flex min-w-0 flex-col gap-0.5 text-xs">
<span className="font-mono">{row.original.dst}</span> <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(" · ")} {[row.original.category, row.original.service].filter(Boolean).join(" · ")}
</span> </span>
</span> </span>
@@ -445,12 +445,12 @@ export function FlowAnalyticsDetail({
{analytics?.ifaces && analytics.ifaces.length > 0 ? ( {analytics?.ifaces && analytics.ifaces.length > 0 ? (
<div className="mb-3 pb-3 border-b"> <div className="mb-3 pb-3 border-b">
<div className="flex items-center gap-2 flex-wrap"> <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 <button
type="button" type="button"
onClick={() => onIface("__all__")} onClick={() => onIface("__all__")}
className={cn( 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__" selectedIface === "__all__"
? "bg-foreground text-background border-foreground" ? "bg-foreground text-background border-foreground"
: "border-border text-muted-foreground hover:text-foreground hover:border-foreground/40", : "border-border text-muted-foreground hover:text-foreground hover:border-foreground/40",
@@ -466,7 +466,7 @@ export function FlowAnalyticsDetail({
type="button" type="button"
onClick={() => onIface(iface.name)} onClick={() => onIface(iface.name)}
className={cn( 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 active
? "bg-foreground text-background border-foreground" ? "bg-foreground text-background border-foreground"
: "border-border text-muted-foreground hover:text-foreground hover:border-foreground/40", : "border-border text-muted-foreground hover:text-foreground hover:border-foreground/40",
@@ -477,7 +477,7 @@ export function FlowAnalyticsDetail({
) )
})} })}
</div> </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> </div>
) : null} ) : null}
+25 -7
View File
@@ -55,12 +55,30 @@
### Доступ конечных Linux-серверов ### Доступ конечных Linux-серверов
1. На вкладке **Linux-клиенты** нажмите **Подключить Linux**. Выберите транспорт, права на сети и выход. Адреса IPv4 внутри туннеля и порт WireGuard выделяются автоматически. Для ручного назначения IPv4 или IPv6 откройте параметры адресов туннеля. 1. Откройте сегмент IX и нажмите **Подключить Linux**. Выберите транспорт и выход VPS. **Только разрешённые сети** направляет в туннель выбранные префиксы, **Интернет с этого IX** выводит трафик через его WAN. Для удалённого выхода выберите конкретный ExitNode или другой IX. Менеджер использует подходящий настроенный выход либо подготовит транзит вместе с клиентом.
2. Нажмите **Подготовить доступ** и примените план. Скачайте файлы из применённой ревизии по кнопке **Конфиг Linux**. 2. Нажмите **Сохранить**. В окне подтверждения проверьте узлы и изменения RouterOS, затем нажмите **Подтвердить**. Кнопка **Конфиг Linux** в строке клиента выдаёт файлы из применённой ревизии. Отмена до подтверждения оставляет изменения в черновике. Его можно открыть той же кнопкой **Сохранить**.
3. В карточке **Доступ и выход** можно сменить политику или приостановить подключение. Действие **Отозвать** удаляет управляемые объекты клиента после проверки плана. 3. В строке клиента нажмите на название выхода, чтобы сменить маршрут или приостановить доступ. В меню действий **Проверить путь** показывает фактический шлюз, а **Отозвать доступ** удаляет клиентское подключение после подтверждения. Во вкладке **Маршрутизация** можно настроить общие выходы и резерв, интерфейсы CHR, статические маршруты и BGP.
- **WireGuard.** Создайте пару ключей на Linux и вставьте публичный ключ. Подставьте приватный ключ в скачанный файл и поднимите соединение через `wg-quick`. Указанный внешний IP Linux используется в конфиге для сохранения исходного пути управления при полном туннеле. - **WireGuard.** IX автоматически создаёт пару ключей Linux. После применения скачайте готовый `.conf` из карточки клиента, сохраните под исходным именем в `/etc/wireguard/` с правами `0600` и запустите `sudo wg-quick up <имя-файла-без-.conf>`. Указанный внешний IP Linux сохраняет исходный путь управления при полном туннеле. Для клиента со своей парой ключей доступен шаблон с полем для его приватного ключа.
- **GRE/IPsec.** Укажите два фиксированных внешних IPv4-адреса. Менеджер создаёт на CHR GRE с выключенным FastPath и IKEv2/IPsec в транспортном режиме. Оператор с правами записи скачивает конфиг strongSwan с индивидуальным PSK и команды настройки Linux. Старые вручную подготовленные подключения остаются доступны по прежнему шаблону. - **Получение WireGuard через MCP.** Вызовите `mm_wireguard_export_plan` с полями `serverId`, `interfaceName` клиента, `ixSegmentId` и `format: "peer-conf"`. После подтверждения и выполнения плана ссылка на готовый файл доступна авторизованному владельцу подключения 15 минут. Ключ находится только в скачиваемом файле.
- **Два протокола.** Отметьте WireGuard и GRE/IPsec при создании. Для существующего клиента откройте **Доступ и выход**, выберите свободный протокол и нажмите **Добавить туннель**. Туннели имеют отдельные адреса и ключи, входят в одну VRF сегмента на выбранном IX, настраиваются и отключаются отдельно. Для второго туннеля по умолчанию предложен доступ к разрешённым сетям. Если на VPS одновременно запущены оба туннеля с маршрутом по умолчанию, сгенерированные правила GRE направляют обычный трафик через GRE.
- **GRE/IPsec.** Укажите два фиксированных внешних IPv4-адреса. После применения скачайте конфиг strongSwan и скрипт GRE в одну папку на VPS. На Ubuntu установите `charon-systemd strongswan-swanctl`, запустите `sudo systemctl start strongswan` и выполните показанную в карточке команду `sudo sh ./…-setup.sh`. Скрипт копирует профиль с правами `0600`, устанавливает IKEv2/IPsec, создаёт GRE и использует отдельную таблицу для туннельных маршрутов. Транспорт до IX и ответы с внешнего IPv4 VPS, включая SSH, идут по основной таблице Linux.
### Несколько туннелей на одном VPS
Для подготовки транспорта из меню WireGuard или GRE/IPsec выберите **Скопировать ссылку для ix-client**. На VPS нажмите **L** в ix-client, вставьте ссылку и нажмите **F2**. Ссылка действует до пяти минут и погашается при первой попытке загрузки. В **P → Зависимости** можно проверить и по подтверждению установить недостающие пакеты. После подготовки транспорта сохраните группу и скопируйте её ссылку рядом с кнопкой **Скачать для ix-client**. JSON по-прежнему можно импортировать через **B → I**.
Карточка Linux-клиента объединяет его туннели и группы резервирования. Для нового интерфейса RouterOS имя включает протокол, имя клиента и уникальный суффикс, например `il-gre-tg-a1b2c3d4e5f6`. Существующие подключения сохраняют свои имена. RX и TX в строке GRE/IPsec показывают накопленные байты интерфейса на CHR.
1. В **Linux-клиенты** откройте меню действующего подключения и выберите **Создать группу с этим туннелем**. Интерфейс уже будет первым в списке. Для участника существующей группы это же меню открывает её редактор. Ключи VPS и CHR при создании группы сохраняются. Для нового транспорта откройте меню клиента и скачайте **Конфиг для группы ix-client**.
2. Добавьте второе подключение одного VPS. Старые управляемые подключения без идентификатора VPS можно выбрать вместе, подтвердив их принадлежность одному серверу. Для исправления прежней привязки свободного подключения откройте **Доступ и выход → Привязка к VPS**, выберите VPS и сохраните ревизию. У всех участников должны различаться внутренние IP-адреса VPS и IX и совпадать семейство адресов и сети назначения. В режиме резервирования первым поставьте основной, затем резервы в порядке предпочтения. В параллельном режиме задайте равное распределение или веса. В прямые исключения внесите сети, к которым VPS должен обращаться через WAN.
3. Нажмите **Скачать для ix-client** и импортируйте JSON группы через **B → I**. Если имя интерфейса на VPS отличается от имени в JSON, ix-client сопоставит существующий транспорт по адресам и параметрам пира. Проверьте найденное локальное имя и соответствие туннеля в предварительном просмотре **F2**. Нажмите **Enter** для применения и **Y** для подтверждения. Без подтверждения через 60 секунд восстановится предыдущая конфигурация. Одиночные интерфейсы можно продолжать использовать отдельно.
**Интерфейсы, созданные вручную на CHR и VPS.** Пользователь с правом управления сетью может открыть **Группы туннелей VPS → Создать группу → Добавить из интерфейсов RouterOS** и выбрать узел применённого сегмента и действующий WG или GRE. Укажите фактическое имя интерфейса Linux, внутренние адреса обеих сторон, внешний IP IX и сети назначения. Для WG укажите публичный ключ **VPS**. Manager проверит, что он принадлежит включённому пиру, что его `allowed-address` включает адрес VPS и внешний IP назначен узлу IX. Для GRE укажите внешний IPv4 VPS. Manager сверит пару внешних адресов, выключенный FastPath и обязательную транспортную политику IPsec. Внутренний адрес VPS должен подтверждаться подсетью, адресом point-to-point или отдельным хост-маршрутом через GRE.
При сохранении и экспорте Manager читает RouterOS. Параметры ручного подключения сохраняются в группе, а существующие ключи, VRF, маршруты и интерфейсы CHR продолжают работать. Для межузловых туннелей, BGP-подключений и интерфейсов другой VRF используйте их собственную схему маршрутизации. У ручного подключения оператор указывает назначения, которые уже доступны через IX. При экспорте JSON для WG Manager подставляет публичный ключ CHR. Ручной импорт WG через внешний NAT поддерживает только адреса, назначенные самой CHR. Если публичный адрес есть лишь на вышестоящем NAT, проверка Manager отклонит его.
Фактический активный путь, состояние резервов и распределение соединений видны на VPS в **B → Группы** или в выводе `sudo ix-client bond status`. Клиент раз в секунду посылает ICMP-пробу на внутренний адрес IX через каждый туннель, в том числе в отсутствие пользовательского трафика. Разрешите ответы на эти пробы. После трёх пропущенных ответов клиент исключает путь. Если резерв работает, клиент возвращает новые соединения на основной после 30 секунд устойчивых ответов. Уже открытое соединение через упавший туннель может потребовать переподключения. Ответы на входящие прямые соединения возвращаются через тот WAN, на который пришёл запрос.
### Выход и резерв ### Выход и резерв
@@ -68,9 +86,9 @@
При выборе **Только разрешённые сети** клиенту открываются согласованные префиксы, которые маршрутизируются внутри IX. **Проверить путь** показывает FIB и активный next hop. Доступность назначения и фактический внешний адрес проверяйте с Linux. При выборе **Только разрешённые сети** клиенту открываются согласованные префиксы, которые маршрутизируются внутри IX. **Проверить путь** показывает FIB и активный next hop. Доступность назначения и фактический внешний адрес проверяйте с Linux.
Если операция оборвалась после записи части объектов, откройте **План изменений** для текущей ревизии и выберите **Сверить и продолжить**. Менеджер проверяет запись о предыдущей попытке и адресатов, перечитывает CHR и предлагает план оставшихся изменений. Если операция оборвалась после записи части объектов, нажмите **Сохранить** для текущей ревизии. Если обычное сравнение выявит частично применённые изменения, выберите в окне **Сверить и продолжить**. Менеджер проверяет запись о предыдущей попытке и адресатов, перечитывает CHR и предлагает план оставшихся изменений.
На изолированном стенде с двумя CHR RouterOS 7.24.5 проверены скачанные конфигурации WireGuard и GRE/IKEv2, IPv4 TCP на локальных выходах и блокировка открытого GRE после снятия IPsec. Для выхода через ExitNode получатель увидел смену WAN второй CHR на WAN первой и обратно после восстановления туннеля. В роли второго IX та же пара передала IPv6 с сохранением адреса Linux. Стендовый BGP-анонс выбран через заданный шлюз, после отзыва активировался защитный маршрут отбрасывания. До автоматической выдачи ключей на изолированном стенде с двумя CHR RouterOS 7.24.5 проверены WireGuard и GRE/IKEv2, IPv4 TCP на локальных выходах и блокировка открытого GRE после снятия IPsec. Для выхода через ExitNode получатель увидел смену WAN второй CHR на WAN первой и обратно после восстановления туннеля. В роли второго IX та же пара передала IPv6 с сохранением адреса Linux. Стендовый BGP-анонс выбран через заданный шлюз, после отзыва активировался защитный маршрут отбрасывания. Автоматическая выдача WireGuard проверена через REST и MCP с временной PostgreSQL и имитацией RouterOS.
### Удаление сегмента ### Удаление сегмента
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

Loaded 100 of 147 files, more files were not shown because too many files have changed in this diff. Show more