Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b896e469a7 | ||
|
|
c44bcd8f59 | ||
|
|
ed7b1e0350 | ||
|
|
4097e1a6fc | ||
|
|
7cf17c7283 | ||
|
|
4eafc78c8e | ||
|
|
d174bca5d6 | ||
|
|
2ca40fbb4d | ||
|
|
589fc782f9 | ||
|
|
fcbf219725 | ||
|
|
95a0ebeb18 | ||
|
|
2b0b9a5fa5 | ||
|
|
9b2c2327a6 | ||
|
|
ec2fb54e04 | ||
|
|
c94d417f1b | ||
|
|
63c0fc6506 | ||
|
|
682d6c8d55 | ||
|
|
a41c70b104 | ||
|
|
dd6e6b0b77 | ||
|
|
a4694b8481 | ||
|
|
640726aa86 | ||
|
|
67b1d9cde2 | ||
|
|
8781f68674 | ||
|
|
5fd028800a | ||
|
|
01779d7ee6 | ||
|
|
1b927dcf68 | ||
|
|
af82497f20 | ||
|
|
ca65969728 | ||
|
|
ee6fd675ac |
No files matched your search
+394
-306
@@ -1,349 +1,437 @@
|
||||
"use client"
|
||||
|
||||
import { useState } from "react"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { useEffect, useMemo, useState } from "react"
|
||||
import Link from "next/link"
|
||||
import {
|
||||
ActivityIcon,
|
||||
BellIcon,
|
||||
CableIcon,
|
||||
FilterIcon,
|
||||
GitMergeIcon,
|
||||
HardDriveIcon,
|
||||
ChartColumnIcon,
|
||||
CircleAlertIcon,
|
||||
HeartPulseIcon,
|
||||
MapIcon,
|
||||
LayoutDashboardIcon,
|
||||
ServerIcon,
|
||||
ShieldIcon,
|
||||
SlidersHorizontalIcon,
|
||||
TableIcon,
|
||||
} from "lucide-react"
|
||||
import { Button, buttonVariants } from "@/components/ui/button"
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuCheckboxItem,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuGroup,
|
||||
DropdownMenuLabel,
|
||||
DropdownMenuTrigger,
|
||||
} from "@/components/ui/dropdown-menu"
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
|
||||
import { Alert, AlertAction, AlertDescription, AlertTitle } from "@/components/reui/alert"
|
||||
import { Badge } from "@/components/reui/badge"
|
||||
import { PageHeader } from "@/components/page-header"
|
||||
import { OpsPanel } from "@/components/ops-panel"
|
||||
import { KpiStatGrid } from "@/components/reui-kit/kpi-stat-grid"
|
||||
import { QuickActionGrid } from "@/components/reui-kit/quick-action-grid"
|
||||
import { AttentionQueue } from "@/components/reui-kit/attention-queue"
|
||||
import { PageTitle } from "@/components/page-title"
|
||||
import { DataFreshness } from "@/components/data-freshness"
|
||||
import { EmptyState } from "@/components/empty-state"
|
||||
import { CapacityGrid, SectionFrame, SparkKpiGrid, ToneBadge, seriesDelta, type Tone } from "@/components/reui-kit/ops-blocks"
|
||||
import { TrafficRxTxChart } from "@/components/reui-kit/traffic-rx-tx-chart"
|
||||
import { LatencyChart } from "@/components/dashboard/latency-chart"
|
||||
import { DashboardEventsTimeline } from "@/components/dashboard/dashboard-events-timeline"
|
||||
import { InternetPathPanel } from "@/components/dashboard/internet-path-panel"
|
||||
import { DashboardSourcesSummary, dashboardSourceRows, sourceErrorText } from "@/components/dashboard/dashboard-sources-summary"
|
||||
import {
|
||||
DashboardAttentionGrid,
|
||||
DashboardHealth,
|
||||
DashboardIncidents,
|
||||
DashboardQuickLinks,
|
||||
type AttentionGridRow,
|
||||
} from "@/components/dashboard/dashboard-overview-blocks"
|
||||
import { DashboardActiveProbesDataGrid } from "@/components/data-grids/dashboard-active-probes-data-grid"
|
||||
import { EmptyState } from "@/components/empty-state"
|
||||
import { DashboardDataStatus } from "@/components/dashboard/dashboard-data-status"
|
||||
import { Badge } from "@/components/reui/badge"
|
||||
import { buttonVariants } from "@/components/ui/button"
|
||||
import { cn } from "@/lib/utils"
|
||||
import { fmtRate } from "@/lib/fmt-rate"
|
||||
import { DASHBOARD_SOURCES, type DashboardSource, type DashboardSources } from "@/lib/dashboard-source-state"
|
||||
import { useDashboardLive, type AttentionRow } from "@/hooks/use-dashboard-live"
|
||||
|
||||
const WIDGETS = {
|
||||
cap: "Ёмкость",
|
||||
spark: "Показатели",
|
||||
sources: "Сводка источников",
|
||||
health: "Здоровье сети",
|
||||
timeline: "Лента инцидентов",
|
||||
path: "Internet path",
|
||||
attention: "Требует внимания",
|
||||
latency: "Задержка до серверов",
|
||||
traffic: "Пропускная способность",
|
||||
probes: "Активные пробы",
|
||||
links: "Быстрые переходы",
|
||||
} as const
|
||||
type Widget = keyof typeof WIDGETS
|
||||
const HIDDEN_WIDGETS_LS = "mm:dashboard-hidden-widgets"
|
||||
|
||||
function useHiddenWidgets() {
|
||||
const [hidden, setHidden] = useState<Set<Widget>>(new Set())
|
||||
useEffect(() => {
|
||||
try {
|
||||
const raw = JSON.parse(localStorage.getItem(HIDDEN_WIDGETS_LS) ?? "[]")
|
||||
if (Array.isArray(raw)) queueMicrotask(() => setHidden(new Set(raw.filter((key): key is Widget => key in WIDGETS))))
|
||||
} catch {
|
||||
/* повреждённое значение — показываем все виджеты */
|
||||
}
|
||||
}, [])
|
||||
function toggle(key: Widget, visible: boolean) {
|
||||
setHidden((previous) => {
|
||||
const next = new Set(previous)
|
||||
if (visible) next.delete(key)
|
||||
else next.add(key)
|
||||
try {
|
||||
localStorage.setItem(HIDDEN_WIDGETS_LS, JSON.stringify([...next]))
|
||||
} catch {
|
||||
/* хранилище недоступно — настройка действует до перезагрузки */
|
||||
}
|
||||
return next
|
||||
})
|
||||
}
|
||||
return { hidden, toggle }
|
||||
}
|
||||
|
||||
function fmtIntRu(n: number): string {
|
||||
return n.toLocaleString("ru-RU")
|
||||
}
|
||||
|
||||
function AttentionRows({ rows }: { rows: AttentionRow[] }) {
|
||||
const [expanded,setExpanded]=useState(false)
|
||||
const [visible,setVisible]=useState(55)
|
||||
function renderRow(row: AttentionRow) {
|
||||
return (
|
||||
<Link
|
||||
key={row.id}
|
||||
href={row.href}
|
||||
className="hover:bg-muted/40 focus-visible:ring-ring flex min-w-0 items-start justify-between gap-2 rounded-md px-1 py-1.5 focus-visible:ring-2"
|
||||
>
|
||||
<span className="min-w-0 wrap-anywhere text-sm font-medium">{row.title}</span>
|
||||
<Badge
|
||||
size="sm"
|
||||
variant={row.tone === "warning" ? "warning-light" : "destructive-light"}
|
||||
className="shrink-0"
|
||||
>
|
||||
{row.hint}
|
||||
</Badge>
|
||||
</Link>
|
||||
)
|
||||
function averageSeries(series: Record<string, (number | null)[]>): number[] {
|
||||
const rows = Object.values(series)
|
||||
const length = Math.max(0, ...rows.map((values) => values.length))
|
||||
const out: number[] = []
|
||||
for (let i = 0; i < length; i++) {
|
||||
const values = rows.map((row) => row[i]).filter((v): v is number => typeof v === "number" && Number.isFinite(v))
|
||||
if (values.length) out.push(values.reduce((sum, v) => sum + v, 0) / values.length)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-0.5">
|
||||
{rows.slice(0, 5).map(renderRow)}
|
||||
{rows.length > 5 && (
|
||||
<details onToggle={event=>{setExpanded(event.currentTarget.open);if(!event.currentTarget.open)setVisible(55)}}>
|
||||
<summary className="cursor-pointer rounded-md px-1 py-2 text-xs text-muted-foreground focus-visible:ring-2 focus-visible:ring-ring">Ещё {rows.length - 5}</summary>
|
||||
{expanded && rows.slice(5,visible).map(renderRow)}
|
||||
{expanded && rows.length>visible && <Button type="button" variant="ghost" size="sm" onClick={()=>setVisible(count=>Math.min(count+50,rows.length))}>Показать ещё {Math.min(50,rows.length-visible)}</Button>}
|
||||
</details>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
function toGridRows(rows: AttentionRow[], kind: AttentionGridRow["kind"]): AttentionGridRow[] {
|
||||
return rows.map((row) => ({
|
||||
id: row.id,
|
||||
title: row.title,
|
||||
kind,
|
||||
hint: row.hint,
|
||||
href: row.href,
|
||||
tone: row.tone === "destructive" ? "er" : "wn",
|
||||
confirmed: row.hint !== "Статус неизвестен",
|
||||
}))
|
||||
}
|
||||
|
||||
export default function DashboardPage() {
|
||||
const dash = useDashboardLive()
|
||||
const { hidden, toggle } = useHiddenWidgets()
|
||||
const [tab, setTab] = useState("over")
|
||||
const [mockAt] = useState(() => Date.now())
|
||||
const show = (key: Widget) => !hidden.has(key)
|
||||
|
||||
// Демо-режим не опрашивает API: показываем источники полученными в момент открытия страницы.
|
||||
const sources: DashboardSources = useMemo(
|
||||
() => dash.isLive ? dash.sources : Object.fromEntries((Object.keys(DASHBOARD_SOURCES) as DashboardSource[]).map((key) => [key, { receivedAt: mockAt, error: null }])),
|
||||
[dash.isLive, dash.sources, mockAt],
|
||||
)
|
||||
const sourceRows = dashboardSourceRows(sources)
|
||||
const failedSources = sourceRows.filter((row) => row.error)
|
||||
const received = sourceRows.map((row) => row.receivedAt).filter((at): at is number => at != null)
|
||||
const freshAt = received.length ? Math.max(...received) : null
|
||||
|
||||
const offline = dash.offlineCount
|
||||
const health = dash.probeDown + dash.probeWarn
|
||||
const problems = dash.probeDown + dash.probeWarn
|
||||
const serverTrouble = offline > 0 || dash.unknownServerCount > 0 || dash.degradedServerCount > 0
|
||||
const serverCaption = !dash.availability.servers ? "нет данных" : !dash.isLive
|
||||
? "демо"
|
||||
: serverTrouble
|
||||
? [offline > 0 ? `${offline} не в сети` : null, dash.unknownServerCount > 0 ? `Статус неизвестен: ${dash.unknownServerCount}` : null, dash.degradedServerCount > 0 ? `Ухудшение: ${dash.degradedServerCount}` : null].filter(Boolean).join(" · ")
|
||||
: dash.totalServers > 0 ? "все в сети" : "нет серверов"
|
||||
|
||||
const latencySeries = dash.latency.kind === "mock" || dash.latency.kind === "live" ? averageSeries(dash.latency.series) : []
|
||||
const rttNow = latencySeries.length ? Math.round(latencySeries[latencySeries.length - 1]) : null
|
||||
|
||||
const probesMeasured = useMemo(() => dash.enabledProbes.filter((p) => p.status !== "unknown"), [dash.enabledProbes])
|
||||
const avgLoss = probesMeasured.length ? probesMeasured.reduce((sum, p) => sum + (p.loss ?? 0), 0) / probesMeasured.length : null
|
||||
const okSources = sourceRows.filter((row) => row.tone === "ok").length
|
||||
|
||||
const attentionRows = [
|
||||
...toGridRows(dash.attentionServers, "Сервер"),
|
||||
...toGridRows(dash.attentionOverlay, "Туннель"),
|
||||
...toGridRows(dash.attentionProbes, "Проверка"),
|
||||
]
|
||||
const emptyNotes = [
|
||||
dash.attentionServers.length ? null : dash.reliable.servers ? (dash.totalServers > 0 ? "Серверы без проблем" : "Нет серверов") : "Серверы: состояние не подтверждено",
|
||||
dash.attentionOverlay.length ? null : dash.reliable.overlay ? (dash.overlay.total > 0 ? "Туннели работают" : "Нет туннелей") : "Туннели: состояние не подтверждено",
|
||||
dash.attentionProbes.length ? null : dash.reliable.probes ? (dash.probeCount > 0 ? "Проверки без ошибок" : "Нет активных проверок") : "Проверки: состояние не подтверждено",
|
||||
].filter((note): note is string => note != null)
|
||||
|
||||
const latencyBody = dash.latency.kind === "loading" ? (
|
||||
<div className="bg-muted/50 h-[220px] w-full animate-pulse rounded-md" />
|
||||
) : dash.latency.kind === "empty" ? (
|
||||
<p className="text-muted-foreground px-4 py-10 text-center text-sm">{dash.latency.message}</p>
|
||||
) : (
|
||||
<LatencyChart series={dash.latency.series} labels={dash.latency.labels} />
|
||||
)
|
||||
const latencyDescription = dash.latency.kind === "mock" || dash.latency.kind === "live" ? dash.latency.subtitle : dash.latency.kind === "loading" ? "Загрузка…" : "Нет серии RTT"
|
||||
|
||||
return (
|
||||
<div className="flex h-full flex-col">
|
||||
<PageHeader crumbs={[{ label: "Обзор" }, { label: "Дашборд" }]} />
|
||||
<PageHeader crumbs={[{ label: "Главная", href: "/dashboard" }, { label: "Обзор" }, { label: "Дашборд" }]} status={<DataFreshness at={freshAt} live={dash.isLive} />} />
|
||||
|
||||
<div className="flex-1 overflow-y-auto">
|
||||
<div className="flex flex-col gap-4 px-4 py-4 md:gap-6 md:px-6 md:py-5">
|
||||
{dash.isLive && <DashboardDataStatus sources={dash.sources} refreshing={dash.refreshing} onRefresh={dash.retry} />}
|
||||
|
||||
<KpiStatGrid
|
||||
aria-label="Сводка дашборда"
|
||||
isLoading={dash.loading}
|
||||
items={[
|
||||
{
|
||||
id: "fleet",
|
||||
label: "Серверы онлайн",
|
||||
value: dash.availability.servers ? `${dash.onlineCount} / ${dash.totalServers}` : "—",
|
||||
hint: !dash.availability.servers ? "нет данных" : !dash.isLive
|
||||
? "демо"
|
||||
: offline > 0 || dash.unknownServerCount > 0 || dash.degradedServerCount > 0
|
||||
? [offline > 0 ? `${offline} не в сети` : null,dash.unknownServerCount > 0 ? `Статус неизвестен: ${dash.unknownServerCount}` : null,dash.degradedServerCount > 0 ? `Ухудшение: ${dash.degradedServerCount}` : null].filter(Boolean).join(" · ")
|
||||
: dash.totalServers > 0
|
||||
? "все в сети"
|
||||
: "нет серверов",
|
||||
href: "/servers",
|
||||
icon: <ServerIcon />,
|
||||
iconClassName: "text-muted-foreground",
|
||||
variant: offline > 0 || dash.unknownServerCount > 0 || dash.degradedServerCount > 0 ? "warning" : "default",
|
||||
},
|
||||
{
|
||||
id: "overlay",
|
||||
label: "Туннели работают",
|
||||
value: dash.availability.overlay ? String(dash.overlay.up) : "—",
|
||||
hint: !dash.availability.overlay ? "не все источники доступны" : !dash.reliable.overlay ? "Последний успешный снимок; не все источники обновлены" : dash.overlay.total > 0 ? `Не работают: ${dash.overlay.down}` : "нет туннелей",
|
||||
href: "/gre",
|
||||
icon: <CableIcon />,
|
||||
iconClassName: "text-info",
|
||||
variant: dash.overlay.down > 0 ? "warning" : "default",
|
||||
},
|
||||
{
|
||||
id: "bgp",
|
||||
label: "Префиксы BGP",
|
||||
value: dash.bgp?.prefixSum != null ? fmtIntRu(dash.bgp.prefixSum) : "—",
|
||||
hint: dash.bgp ? `Сессий установлено: ${dash.bgp.establishedCount ?? "неизвестно"}${dash.bgp.prefixSum === null ? " · префиксы неизвестны" : ""}` : "нет данных",
|
||||
href: "/bgp",
|
||||
icon: <GitMergeIcon />,
|
||||
iconClassName: "text-primary",
|
||||
},
|
||||
{
|
||||
id: "health",
|
||||
label: "Проверки с проблемами",
|
||||
value: dash.availability.probes && dash.unknownProbeCount===0 ? String(health) : "—",
|
||||
hint: dash.availability.probes ? `${dash.probeDown} ошибок · ${dash.probeWarn} предупреждений${dash.unknownProbeCount>0?` · неизвестны: ${dash.unknownProbeCount}`:""}` : "нет данных",
|
||||
href: "/uptime",
|
||||
icon: <BellIcon />,
|
||||
iconClassName: health > 0 ? "text-destructive" : "text-muted-foreground",
|
||||
variant: health > 0 ? "destructive" : "default",
|
||||
},
|
||||
]}
|
||||
<div className="flex flex-col gap-6 px-4 pt-5 pb-10 md:px-7 md:pt-6">
|
||||
<PageTitle
|
||||
icon={<LayoutDashboardIcon />}
|
||||
title="Дашборд"
|
||||
description="Здоровье сети: индекс, события за период, Internet path, пробы и источники"
|
||||
actions={
|
||||
<>
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger render={<Button type="button" variant="outline"><SlidersHorizontalIcon data-icon="inline-start" />Настроить виджеты</Button>} />
|
||||
<DropdownMenuContent align="end" className="w-60">
|
||||
<DropdownMenuGroup>
|
||||
<DropdownMenuLabel>Виджеты дашборда</DropdownMenuLabel>
|
||||
{(Object.keys(WIDGETS) as Widget[]).map((key) => (
|
||||
<DropdownMenuCheckboxItem key={key} checked={show(key)} onCheckedChange={(value) => toggle(key, !!value)}>
|
||||
{WIDGETS[key]}
|
||||
</DropdownMenuCheckboxItem>
|
||||
))}
|
||||
</DropdownMenuGroup>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
<Button type="button" onClick={dash.retry} disabled={dash.refreshing}>Обновить данные</Button>
|
||||
</>
|
||||
}
|
||||
/>
|
||||
|
||||
<section aria-labelledby="dashboard-attention-title" className="flex min-w-0 flex-col gap-2">
|
||||
<h2 id="dashboard-attention-title" className="text-sm font-semibold">Требует внимания</h2>
|
||||
<AttentionQueue
|
||||
className="lg:grid-cols-3"
|
||||
columns={[
|
||||
{
|
||||
id: "nodes",
|
||||
title: "Серверы",
|
||||
icon: ServerIcon,
|
||||
count: dash.attentionServers.length,
|
||||
countVariant: "warning-light",
|
||||
emptyTitle: dash.reliable.servers ? (dash.totalServers > 0 ? "Серверы без проблем" : "Нет серверов") : "Состояние не подтверждено",
|
||||
emptyDescription: dash.reliable.servers ? "Нет включённых серверов с ошибками доступности." : "Проверьте состояние источников выше.",
|
||||
children: <AttentionRows rows={dash.attentionServers} />,
|
||||
},
|
||||
{
|
||||
id: "overlay",
|
||||
title: "Туннели",
|
||||
icon: CableIcon,
|
||||
iconClassName: "text-info",
|
||||
count: dash.attentionOverlay.length,
|
||||
countVariant: "destructive-light",
|
||||
emptyTitle: dash.reliable.overlay ? (dash.overlay.total > 0 ? "Туннели работают" : "Нет туннелей") : "Состояние не подтверждено",
|
||||
emptyDescription: dash.reliable.overlay ? "В GRE, WireGuard и VXLAN проблем не обнаружено." : "Проверьте состояние источников выше.",
|
||||
children: <AttentionRows rows={dash.attentionOverlay} />,
|
||||
},
|
||||
{
|
||||
id: "probes",
|
||||
title: "Проверки",
|
||||
icon: HeartPulseIcon,
|
||||
iconClassName: "text-destructive",
|
||||
count: dash.attentionProbes.length,
|
||||
countVariant: "destructive-light",
|
||||
emptyTitle: dash.reliable.probes ? (dash.probeCount > 0 ? "Проверки без ошибок" : "Нет активных проверок") : "Состояние не подтверждено",
|
||||
emptyDescription: dash.reliable.probes ? "Нет ошибок и предупреждений активных проверок." : "Проверьте состояние источников выше.",
|
||||
children: <AttentionRows rows={dash.attentionProbes} />,
|
||||
},
|
||||
]}
|
||||
/>
|
||||
</section>
|
||||
<div className="flex flex-col gap-5">
|
||||
{failedSources.length > 0 ? (
|
||||
<Alert variant="warning">
|
||||
<CircleAlertIcon />
|
||||
<AlertTitle>Не все источники доступны.</AlertTitle>
|
||||
<AlertDescription>
|
||||
Последний успешный снимок; не все источники обновлены. Не обновлены: {failedSources.map((row) => row.name).join(", ")}. Проверьте состояние источников ниже.
|
||||
</AlertDescription>
|
||||
<AlertAction>
|
||||
<Button type="button" size="sm" variant="outline" onClick={() => setTab("src")}>Объяснить</Button>
|
||||
</AlertAction>
|
||||
</Alert>
|
||||
) : null}
|
||||
|
||||
<div className="grid grid-cols-1 gap-4 lg:grid-cols-[2fr_1fr]">
|
||||
<OpsPanel
|
||||
title="Задержка до серверов"
|
||||
description={
|
||||
dash.latency.kind === "mock" || dash.latency.kind === "live"
|
||||
? dash.latency.subtitle
|
||||
: dash.latency.kind === "loading"
|
||||
? "Загрузка…"
|
||||
: "Нет серии RTT"
|
||||
}
|
||||
contentClassName="px-3 pb-3"
|
||||
>
|
||||
{dash.latency.kind === "loading" && (
|
||||
<div className="bg-muted/50 h-[220px] w-full animate-pulse rounded-md" />
|
||||
)}
|
||||
{dash.latency.kind === "empty" && (
|
||||
<p className="text-muted-foreground px-4 py-10 text-center text-sm">{dash.latency.message}</p>
|
||||
)}
|
||||
{(dash.latency.kind === "mock" || dash.latency.kind === "live") && (
|
||||
<LatencyChart series={dash.latency.series} labels={dash.latency.labels} />
|
||||
)}
|
||||
</OpsPanel>
|
||||
|
||||
<OpsPanel
|
||||
title="Последние события"
|
||||
description="Система и BGP"
|
||||
headerRight={
|
||||
<Link href="/alerts" className={cn(buttonVariants({ variant: "ghost", size: "sm" }), "h-7 text-xs")}>
|
||||
Все →
|
||||
</Link>
|
||||
}
|
||||
>
|
||||
<DashboardEventsTimeline
|
||||
events={dash.recentEvents}
|
||||
loading={dash.eventsLoading}
|
||||
error={dash.eventsError}
|
||||
{show("cap") ? (
|
||||
<CapacityGrid
|
||||
label="Ёмкость сети"
|
||||
items={[
|
||||
{
|
||||
id: "fleet",
|
||||
title: "Серверы онлайн",
|
||||
caption: serverCaption,
|
||||
value: dash.availability.servers ? dash.onlineCount : null,
|
||||
total: dash.availability.servers ? dash.totalServers : null,
|
||||
tone: serverTrouble ? "wn" : "ok",
|
||||
icon: <ServerIcon />,
|
||||
href: "/servers",
|
||||
},
|
||||
{
|
||||
id: "overlay",
|
||||
title: "Туннели работают",
|
||||
caption: !dash.availability.overlay ? "не все источники доступны" : !dash.reliable.overlay ? "Последний успешный снимок; не все источники обновлены" : dash.overlay.total > 0 ? `GRE · WireGuard · VXLAN · не работают: ${dash.overlay.down}` : "нет туннелей",
|
||||
value: dash.availability.overlay ? dash.overlay.up : null,
|
||||
total: dash.availability.overlay ? dash.overlay.total : null,
|
||||
tone: dash.overlay.down > 0 ? "wn" : "ok",
|
||||
icon: <CableIcon />,
|
||||
href: "/gre",
|
||||
},
|
||||
{
|
||||
id: "health",
|
||||
title: "Проверки с проблемами",
|
||||
caption: dash.availability.probes ? `${dash.probeDown} ошибок · ${dash.probeWarn} предупреждений${dash.unknownProbeCount > 0 ? ` · неизвестны: ${dash.unknownProbeCount}` : ""}` : "нет данных",
|
||||
value: dash.availability.probes && dash.unknownProbeCount === 0 ? problems : null,
|
||||
total: dash.availability.probes && dash.unknownProbeCount === 0 ? dash.probeCount : null,
|
||||
tone: problems > 0 ? "er" : "ok",
|
||||
icon: <HeartPulseIcon />,
|
||||
href: "/uptime",
|
||||
},
|
||||
]}
|
||||
/>
|
||||
</OpsPanel>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<div>
|
||||
<OpsPanel
|
||||
title="Пропускная способность"
|
||||
description={dash.traffic?.demo ? "Суммарный RX / TX · демо" : "Суммарная история RX / TX · 1 ч; значения — последний измеренный снимок"}
|
||||
headerRight={<Link href="/traffic" className={cn(buttonVariants({ variant: "outline", size: "sm" }), "h-7 text-xs")}>Трафик →</Link>}
|
||||
contentClassName="px-3 pb-3"
|
||||
>
|
||||
{dash.loading && !dash.traffic ? (
|
||||
<div className="bg-muted/50 h-[220px] w-full animate-pulse rounded-md" />
|
||||
) : !dash.traffic ? (
|
||||
<p className="text-muted-foreground px-4 py-10 text-center text-sm">
|
||||
Нет данных трафика за последний час.{" "}
|
||||
<Link href="/traffic" className="underline underline-offset-2">
|
||||
Открыть трафик
|
||||
</Link>
|
||||
</p>
|
||||
) : (
|
||||
<>
|
||||
<div className="flex flex-wrap items-center gap-3 px-2 py-3 text-xs">
|
||||
{dash.traffic.demo ? <Badge variant="outline" size="sm">демо</Badge> : !dash.traffic.observationsKnown ? <Badge variant="outline" size="sm">Измерения не подтверждены API</Badge> : null}
|
||||
<span className="tabular-nums">RX {dash.traffic.rxNow===null?"—":fmtRate(dash.traffic.rxNow)}</span>
|
||||
<span className="tabular-nums">TX {dash.traffic.txNow===null?"—":fmtRate(dash.traffic.txNow)}</span>
|
||||
{show("spark") ? (
|
||||
<SparkKpiGrid
|
||||
label="Показатели сети"
|
||||
items={[
|
||||
{
|
||||
id: "bgp",
|
||||
title: "Префиксы BGP",
|
||||
value: dash.bgp?.prefixSum != null ? fmtIntRu(dash.bgp.prefixSum) : "—",
|
||||
footnote: dash.bgp ? `Сессий установлено: ${dash.bgp.establishedCount ?? "неизвестно"}${dash.bgp.prefixSum === null ? " · префиксы неизвестны" : ""}` : "нет данных",
|
||||
href: "/bgp",
|
||||
},
|
||||
{
|
||||
id: "rtt",
|
||||
title: "Средний RTT",
|
||||
value: rttNow ?? "—",
|
||||
unit: rttNow != null ? " мс" : undefined,
|
||||
series: latencySeries,
|
||||
delta: seriesDelta(latencySeries, "wn", "ok"),
|
||||
footnote: "за 1 ч",
|
||||
href: "/uptime",
|
||||
},
|
||||
{
|
||||
id: "rx",
|
||||
title: "RX",
|
||||
value: dash.traffic?.rxNow != null ? fmtRate(dash.traffic.rxNow) : "—",
|
||||
series: dash.traffic?.rx.filter((v): v is number => typeof v === "number"),
|
||||
delta: seriesDelta(dash.traffic?.rx.filter((v): v is number => typeof v === "number")),
|
||||
footnote: "суммарно · 1 ч",
|
||||
href: "/traffic",
|
||||
},
|
||||
{
|
||||
id: "tx",
|
||||
title: "TX",
|
||||
value: dash.traffic?.txNow != null ? fmtRate(dash.traffic.txNow) : "—",
|
||||
series: dash.traffic?.tx.filter((v): v is number => typeof v === "number"),
|
||||
delta: seriesDelta(dash.traffic?.tx.filter((v): v is number => typeof v === "number")),
|
||||
footnote: "суммарно · 1 ч",
|
||||
href: "/traffic",
|
||||
},
|
||||
]}
|
||||
/>
|
||||
) : null}
|
||||
|
||||
{show("sources") ? <DashboardSourcesSummary rows={sourceRows} refreshing={dash.refreshing} onRefresh={dash.retry} /> : null}
|
||||
|
||||
<Tabs value={tab} onValueChange={(value) => setTab(String(value))} className="gap-5">
|
||||
<TabsList variant="line" className="h-auto w-full justify-start gap-1 overflow-x-auto border-b p-0">
|
||||
<TabsTrigger value="over" className="h-auto flex-none px-3 py-2.5 after:bottom-[-1px]">Обзор</TabsTrigger>
|
||||
<TabsTrigger value="src" className="h-auto flex-none px-3 py-2.5 after:bottom-[-1px]">
|
||||
Источники и время получения
|
||||
<Badge variant="secondary" className="font-mono">{sourceRows.length}</Badge>
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="rtt" className="h-auto flex-none px-3 py-2.5 after:bottom-[-1px]">История RTT</TabsTrigger>
|
||||
</TabsList>
|
||||
|
||||
<TabsContent value="over" className="flex flex-col gap-5">
|
||||
{show("health") ? (
|
||||
<DashboardHealth
|
||||
factors={[
|
||||
{ label: "Потери пакетов", value: avgLoss == null ? "—" : `${avgLoss.toLocaleString("ru-RU", { maximumFractionDigits: 1 })}%`, ratio: probesMeasured.length ? probesMeasured.filter((p) => (p.loss ?? 0) === 0).length / probesMeasured.length : null },
|
||||
{ label: "Пробы в норме", value: probesMeasured.length ? `${probesMeasured.filter((p) => p.status === "up").length} из ${probesMeasured.length}` : "—", ratio: probesMeasured.length ? probesMeasured.filter((p) => p.status === "up").length / probesMeasured.length : null },
|
||||
{ label: "Свежесть данных", value: `${okSources} из ${sourceRows.length}`, ratio: sourceRows.length ? okSources / sourceRows.length : null },
|
||||
{ label: "Серверы в сети", value: dash.availability.servers ? `${dash.onlineCount} из ${dash.totalServers}` : "—", ratio: dash.availability.servers && dash.totalServers > 0 ? dash.onlineCount / dash.totalServers : null },
|
||||
{ label: "Туннели", value: dash.availability.overlay ? `${dash.overlay.up} из ${dash.overlay.total}` : "—", ratio: dash.availability.overlay && dash.overlay.total > 0 ? dash.overlay.up / dash.overlay.total : null },
|
||||
]}
|
||||
/>
|
||||
) : null}
|
||||
|
||||
{show("timeline") ? <DashboardIncidents events={dash.recentEvents} loading={dash.eventsLoading} error={dash.eventsError} /> : null}
|
||||
|
||||
{show("path") ? <InternetPathPanel model={dash.internetPath} loading={dash.internetPathLoading} error={dash.isLive ? dash.internetPathError : null} /> : null}
|
||||
|
||||
{show("attention") ? <DashboardAttentionGrid rows={attentionRows} emptyNotes={emptyNotes} /> : null}
|
||||
|
||||
{show("latency") ? (
|
||||
<SectionFrame title="Задержка до серверов" description={latencyDescription} panelClassName="px-3.5 pt-3.5">
|
||||
{latencyBody}
|
||||
</SectionFrame>
|
||||
) : null}
|
||||
|
||||
{show("traffic") ? (
|
||||
<SectionFrame
|
||||
title="Пропускная способность"
|
||||
description={dash.traffic?.demo ? "Суммарный RX / TX · демо" : "Суммарная история RX / TX · 1 ч; значения — последний измеренный снимок"}
|
||||
actions={<Link href="/traffic" className={buttonVariants({ variant: "outline", size: "sm" })}>Трафик →</Link>}
|
||||
panelClassName="px-3.5 pt-3.5 pb-2"
|
||||
>
|
||||
{dash.loading && !dash.traffic ? (
|
||||
<div className="bg-muted/50 h-[220px] w-full animate-pulse rounded-md" />
|
||||
) : !dash.traffic ? (
|
||||
<p className="text-muted-foreground px-4 py-10 text-center text-sm">
|
||||
Нет данных трафика за последний час.{" "}
|
||||
<Link href="/traffic" className="underline underline-offset-2">Открыть трафик</Link>
|
||||
</p>
|
||||
) : (
|
||||
<>
|
||||
<div className="flex flex-wrap items-center gap-3 px-1 pb-3 text-xs">
|
||||
{dash.traffic.demo ? <Badge variant="outline" size="sm">демо</Badge> : !dash.traffic.observationsKnown ? <Badge variant="outline" size="sm">Измерения не подтверждены API</Badge> : null}
|
||||
<span className="tabular-nums">RX {dash.traffic.rxNow === null ? "—" : fmtRate(dash.traffic.rxNow)}</span>
|
||||
<span className="tabular-nums">TX {dash.traffic.txNow === null ? "—" : fmtRate(dash.traffic.txNow)}</span>
|
||||
</div>
|
||||
<TrafficRxTxChart rx={dash.traffic.rx} tx={dash.traffic.tx} range="1h" embedded />
|
||||
</>
|
||||
)}
|
||||
</SectionFrame>
|
||||
) : null}
|
||||
|
||||
{show("probes") ? (
|
||||
<SectionFrame
|
||||
title="Активные пробы"
|
||||
description={<span className={dash.error && dash.isLive ? "text-destructive" : undefined}>{dash.probesSubtitle}</span>}
|
||||
icon={<TableIcon />}
|
||||
actions={<Link href="/uptime" className={buttonVariants({ variant: "outline", size: "sm" })}>Мониторинг →</Link>}
|
||||
>
|
||||
{dash.activeProbes.length === 0 && !dash.probesLoading ? (
|
||||
<EmptyState
|
||||
className="py-10"
|
||||
title={dash.availability.probes ? "Нет проб на дашборде" : "Данные проб недоступны"}
|
||||
description={dash.availability.probes ? "Включите пробу и отметьте ★ на странице мониторинга." : "Повторите обновление данных."}
|
||||
action={<Link href="/uptime" className={buttonVariants({ variant: "outline", size: "sm" })}>Открыть мониторинг</Link>}
|
||||
/>
|
||||
) : (
|
||||
<DashboardActiveProbesDataGrid probes={dash.activeProbes} catalog={dash.servers} isLoading={dash.probesLoading} emptyDescription="Нет проб с звездой на дашборде." />
|
||||
)}
|
||||
</SectionFrame>
|
||||
) : null}
|
||||
|
||||
{show("links") ? (
|
||||
<DashboardQuickLinks
|
||||
links={[
|
||||
{ id: "traffic", title: "Трафик", description: "Приём, передача и потоки IPFIX", href: "/traffic" },
|
||||
{ id: "map", title: "Карта сети", description: "Топология GRE и WAN", href: "/network-map" },
|
||||
{ id: "filters", title: "Фильтры", description: "Правила обхода и списки · цепочки filter / nat", href: "/filters" },
|
||||
{ id: "backups", title: "Бэкапы", description: "Снапшоты и расписание", href: "/backups" },
|
||||
{ id: "uptime", title: "Мониторинг", description: "Сессии и префиксы · пробы", href: "/uptime" },
|
||||
]}
|
||||
/>
|
||||
) : null}
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="src" className="flex flex-col gap-5">
|
||||
{failedSources.length > 0 ? (
|
||||
<Alert variant="destructive">
|
||||
<CircleAlertIcon />
|
||||
<AlertTitle>Не обновлены источники: {failedSources.length}</AlertTitle>
|
||||
<AlertDescription>Последние полученные данные сохранены. Если источник ещё не загрузился, его показатели неизвестны.</AlertDescription>
|
||||
</Alert>
|
||||
) : null}
|
||||
<SectionFrame title="Источники и время получения" description="Каждый источник дашборда: состояние, время получения и замера" icon={<ChartColumnIcon />}>
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full min-w-[640px] text-sm">
|
||||
<thead className="bg-muted/55 text-muted-foreground text-xs">
|
||||
<tr className="h-10 border-b text-left">
|
||||
<th className="px-3.5 font-medium">Источник</th>
|
||||
<th className="px-3 font-medium">Статус</th>
|
||||
<th className="px-3 font-medium">Получено</th>
|
||||
<th className="px-3 font-medium">Замер</th>
|
||||
<th className="px-3 font-medium">Ошибка</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{sourceRows.map((row) => (
|
||||
<tr key={row.key} className="h-[52px] border-b last:border-b-0">
|
||||
<td className="px-3.5 font-mono text-[13px] font-medium">{row.name}</td>
|
||||
<td className="px-3"><ToneBadge tone={row.tone as Tone}>{row.label}</ToneBadge></td>
|
||||
<td className="px-3 font-mono text-[12.5px]">{row.receivedAt != null ? new Date(row.receivedAt).toLocaleString("ru-RU") : "—"}</td>
|
||||
<td className="px-3 font-mono text-[12.5px]">{row.sampledAt ? new Date(row.sampledAt).toLocaleString("ru-RU") : "—"}</td>
|
||||
<td className="text-muted-foreground px-3 text-xs">{sourceErrorText(row) ?? "—"}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<TrafficRxTxChart rx={dash.traffic.rx} tx={dash.traffic.tx} range="1h" embedded />
|
||||
</>
|
||||
)}
|
||||
</OpsPanel>
|
||||
|
||||
</SectionFrame>
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="rtt" className="flex flex-col gap-5">
|
||||
<SectionFrame title="История RTT по источникам" description={latencyDescription} panelClassName="px-3.5 pt-3.5">
|
||||
{latencyBody}
|
||||
</SectionFrame>
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
</div>
|
||||
|
||||
<InternetPathPanel
|
||||
model={dash.internetPath}
|
||||
loading={dash.internetPathLoading}
|
||||
error={dash.isLive ? dash.internetPathError : null}
|
||||
/>
|
||||
|
||||
<OpsPanel
|
||||
title="Активные пробы"
|
||||
description={
|
||||
<span className={dash.error && dash.isLive ? "text-destructive" : undefined}>{dash.probesSubtitle}</span>
|
||||
}
|
||||
headerRight={
|
||||
<Link href="/uptime" className={cn(buttonVariants({ variant: "outline", size: "sm" }), "h-7 text-xs")}>
|
||||
Мониторинг →
|
||||
</Link>
|
||||
}
|
||||
contentClassName="px-0 pb-0"
|
||||
>
|
||||
{dash.activeProbes.length === 0 && !dash.probesLoading ? (
|
||||
<EmptyState
|
||||
className="py-10"
|
||||
title={dash.availability.probes ? "Нет проб на дашборде" : "Данные проб недоступны"}
|
||||
description={dash.availability.probes ? "Включите пробу и отметьте ★ на странице мониторинга." : "Повторите обновление данных."}
|
||||
action={
|
||||
<Link href="/uptime" className={cn(buttonVariants({ variant: "outline", size: "sm" }))}>
|
||||
Открыть мониторинг
|
||||
</Link>
|
||||
}
|
||||
/>
|
||||
) : (
|
||||
<DashboardActiveProbesDataGrid
|
||||
probes={dash.activeProbes}
|
||||
catalog={dash.servers}
|
||||
isLoading={dash.probesLoading}
|
||||
emptyDescription="Нет проб с звездой на дашборде."
|
||||
/>
|
||||
)}
|
||||
</OpsPanel>
|
||||
|
||||
<QuickActionGrid
|
||||
title="Быстрые переходы"
|
||||
description="Другие разделы управления сетью"
|
||||
actions={[
|
||||
{
|
||||
id: "traffic",
|
||||
title: "Трафик",
|
||||
description: "Приём, передача и потоки IPFIX",
|
||||
href: "/traffic",
|
||||
icon: <ActivityIcon />,
|
||||
iconClassName: "text-info",
|
||||
},
|
||||
{
|
||||
id: "map",
|
||||
title: "Карта сети",
|
||||
description: "Топология GRE и WAN",
|
||||
href: "/network-map",
|
||||
icon: <MapIcon />,
|
||||
iconClassName: "text-primary",
|
||||
},
|
||||
{
|
||||
id: "filters",
|
||||
title: "Фильтры",
|
||||
description: "Правила обхода и списки",
|
||||
href: "/filters",
|
||||
icon: <FilterIcon />,
|
||||
iconClassName: "text-info",
|
||||
},
|
||||
{
|
||||
id: "firewall",
|
||||
title: "Firewall",
|
||||
description: "Цепочки filter / nat",
|
||||
href: "/firewall",
|
||||
icon: <ShieldIcon />,
|
||||
iconClassName: "text-warning",
|
||||
},
|
||||
{
|
||||
id: "backups",
|
||||
title: "Бэкапы",
|
||||
description: "Снапшоты и расписание",
|
||||
href: "/backups",
|
||||
icon: <HardDriveIcon />,
|
||||
iconClassName: "text-muted-foreground",
|
||||
},
|
||||
{
|
||||
id: "bgp",
|
||||
title: "BGP",
|
||||
description: "Сессии и префиксы",
|
||||
href: "/bgp",
|
||||
icon: <GitMergeIcon />,
|
||||
iconClassName: "text-primary",
|
||||
},
|
||||
]}
|
||||
/>
|
||||
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -12,6 +12,8 @@ import { Sheet, SheetContent, SheetDescription, SheetFooter, SheetHeader, SheetT
|
||||
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: "Основной и резервные" },
|
||||
@@ -107,6 +109,14 @@ export function IxClientBonds({ segmentId, segments, backendUrl, nodes, readOnly
|
||||
{ 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 => {
|
||||
|
||||
@@ -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())
|
||||
}
|
||||
@@ -239,11 +239,11 @@ function TunnelTable({ data, columns, busy }: {
|
||||
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, inspect, bondAction, catalog, renderGroups, manualGroup }: {
|
||||
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
|
||||
save: (input: IxLinuxClientRequest) => Promise<boolean>; refresh: () => 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
|
||||
}) {
|
||||
@@ -331,6 +331,8 @@ export function IxLinuxClients({ segment, nodes, backendUrl, applied, readOnly,
|
||||
{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>}
|
||||
@@ -339,7 +341,7 @@ export function IxLinuxClients({ segment, nodes, backendUrl, applied, readOnly,
|
||||
</DropdownMenu>}
|
||||
</div>
|
||||
} },
|
||||
], [nodes, applied, segment, readOnly, busy, view, revoke, inspect, bondAction, catalog.candidates])
|
||||
], [nodes, applied, segment, readOnly, busy, view, copyImport, revoke, inspect, bondAction, catalog.candidates])
|
||||
return <Frame spacing="sm" className="min-w-0">
|
||||
<FrameHeader className="flex-row flex-wrap items-center justify-between gap-2">
|
||||
<FrameTitle>Linux-клиенты</FrameTitle>
|
||||
|
||||
@@ -24,6 +24,7 @@ import { ConfigurationFields, newSite, nodeLabel, RouteGrid, SegmentGrid, Segmen
|
||||
import { IxLinuxClients } from "./ix-linux-clients"
|
||||
import { IxExits } from "./ix-exits"
|
||||
import { IxClientBonds } from "./ix-client-bonds"
|
||||
import { copyIxImportLink } from "./ix-import-link"
|
||||
|
||||
type Tab = "configuration" | "routes" | "linux"
|
||||
|
||||
@@ -281,6 +282,14 @@ export default function IxPage() {
|
||||
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) {
|
||||
if (!selected) return
|
||||
setLinuxPath(null)
|
||||
@@ -474,6 +483,7 @@ export default function IxPage() {
|
||||
applied={linuxBindings} busy={busy} error={error} readOnly={!live || !write || dirty}
|
||||
save={input => perform(() => stageClient(input))} revoke={binding => void perform(() => stageClient(binding))}
|
||||
refresh={() => void perform(loadLinuxBindings)} view={(binding, transportOnly) => void perform(() => exportLinux(binding, transportOnly))}
|
||||
copyImport={binding => void perform(() => copyLinuxImport(binding))}
|
||||
inspect={binding => void perform(() => inspectLinux(binding))} />}
|
||||
</IxClientBonds>
|
||||
: <EmptyState title="Сохраните сегмент" description="После сохранения можно подключать клиентов." />}
|
||||
|
||||
+1508
-1466
File diff suppressed because it is too large.
Load diff
+202
-168
@@ -1,17 +1,22 @@
|
||||
"use client"
|
||||
|
||||
import { Suspense, useCallback, useEffect, useMemo, useState } from "react"
|
||||
import { Suspense, useCallback, useEffect, useMemo, useState, type ReactNode } from "react"
|
||||
import { useSearchParams } from "next/navigation"
|
||||
import {
|
||||
ActivityIcon,
|
||||
ChartColumnIcon,
|
||||
DatabaseIcon,
|
||||
GaugeIcon,
|
||||
GlobeIcon,
|
||||
ServerIcon,
|
||||
UsersIcon,
|
||||
} from "lucide-react"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { PageHeader } from "@/components/page-header"
|
||||
import { PageTitle } from "@/components/page-title"
|
||||
import { KpiStatGrid } from "@/components/reui-kit/kpi-stat-grid"
|
||||
import { CapacityGrid, type CapacityItem } from "@/components/reui-kit/ops-blocks"
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
|
||||
import { DataPageCard } from "@/components/data-page-card"
|
||||
import { DataPageToolbar } from "@/components/data-page-toolbar"
|
||||
import { SegmentedControl } from "@/components/form-kit"
|
||||
@@ -35,6 +40,7 @@ import {
|
||||
} from "@/lib/statistics-dims"
|
||||
import { statisticsContextError, STATISTICS_CONTEXT_KEYS } from "@/lib/statistics-context"
|
||||
import { readStatisticsRange } from "@/lib/statistics-range"
|
||||
import { demoStatistics, demoStatisticsPivot } from "@/lib/statistics-demo"
|
||||
import { useDataSource } from "@/lib/data-source"
|
||||
import { fmtBps, formatBytes } from "@/lib/fmt-rate"
|
||||
import {
|
||||
@@ -102,8 +108,13 @@ function readDim(sp: URLSearchParams): StatisticsSliceKind {
|
||||
return t && isStatisticsSliceKind(t) ? t : "users"
|
||||
}
|
||||
|
||||
function readView(sp: URLSearchParams): "explore" | "pivot" {
|
||||
return sp.get("view") === "pivot" ? "pivot" : "explore"
|
||||
type StatisticsView = "overview" | "explore" | "pivot"
|
||||
|
||||
/** Вкладка макета v3: Обзор, Срезы (explore) или Сводная (pivot); старые ссылки с разрезом открывают Срезы. */
|
||||
function readView(sp: URLSearchParams): StatisticsView {
|
||||
const v = sp.get("view")
|
||||
if (v === "pivot" || v === "explore" || v === "overview") return v
|
||||
return sp.has("dim") || sp.has("tab") || SLICE_KEYS.some((key) => sp.has(key)) ? "explore" : "overview"
|
||||
}
|
||||
|
||||
function readPlanes(sp: URLSearchParams): "unique" | "all" {
|
||||
@@ -241,7 +252,9 @@ function StatisticsPageInner() {
|
||||
const pivotCol = useMemo(() => readPivotDim(searchParams, "pivotCol", "service"), [searchParams])
|
||||
|
||||
const [retry, setRetry] = useState(0)
|
||||
const requestKey = JSON.stringify({ backendUrl, isLive, range, slices, view, pivotRow, pivotCol, planes, retry, rangeError, paramsError })
|
||||
// Обзор и Срезы читают один и тот же куб — смена этих вкладок не перезапрашивает данные.
|
||||
const pivotView = view === "pivot"
|
||||
const requestKey = JSON.stringify({ backendUrl, isLive, range, slices, pivotView, pivotRow, pivotCol, planes, retry, rangeError, paramsError })
|
||||
const [result, setResult] = useState<{
|
||||
key: string; data: StatisticsDto; pivot: StatisticsPivotDto; error: string | null
|
||||
} | null>(null)
|
||||
@@ -249,7 +262,9 @@ function StatisticsPageInner() {
|
||||
const loading = isLive && !rangeError && !paramsError && current === null
|
||||
const error = rangeError ?? paramsError ?? current?.error ?? null
|
||||
const dataReady = isLive && current !== null && !error
|
||||
const pivot = dataReady ? current.pivot : EMPTY_PIVOT
|
||||
// Демо-режим без API: показываем демо-куб, чтобы раздел выглядел как с данными.
|
||||
const demo = useMemo(() => (isLive || rangeError ? null : demoStatistics(range.from, range.to, planes)), [isLive, rangeError, range, planes])
|
||||
const pivot = dataReady ? current.pivot : demo && !paramsError ? demoStatisticsPivot(pivotRow, pivotCol) : EMPTY_PIVOT
|
||||
|
||||
const updateParams = useCallback(
|
||||
(patch: Record<string, string | undefined>) => {
|
||||
@@ -295,7 +310,7 @@ function StatisticsPageInner() {
|
||||
const dto = await getStatistics(backendUrl, query)
|
||||
if (cancelled) return
|
||||
let matrix = EMPTY_PIVOT
|
||||
if (view === "pivot" && pivotRow !== pivotCol) {
|
||||
if (pivotView && pivotRow !== pivotCol) {
|
||||
matrix = await getStatisticsPivot(backendUrl, {
|
||||
...query,
|
||||
row: pivotRow,
|
||||
@@ -313,11 +328,11 @@ function StatisticsPageInner() {
|
||||
return () => {
|
||||
cancelled = true
|
||||
}
|
||||
}, [backendUrl, isLive, prefsHydrated, range, slices, view, pivotRow, pivotCol, planes, requestKey, rangeError, paramsError])
|
||||
}, [backendUrl, isLive, prefsHydrated, range, slices, pivotView, pivotRow, pivotCol, planes, requestKey, rangeError, paramsError])
|
||||
|
||||
const viewData = dataReady ? current.data : EMPTY
|
||||
const viewData = dataReady ? current.data : demo && !paramsError ? demo : EMPTY
|
||||
const sliced = hasAnySlice(slices)
|
||||
const emptyCube = !isLive || (!loading && viewData.kpis.bytes === 0 && viewData.interfaces.length === 0)
|
||||
const emptyCube = !loading && viewData.kpis.bytes === 0 && viewData.interfaces.length === 0
|
||||
|
||||
function handleRowClick(kind: StatisticsSliceKind, row: StatisticsBreakdownRow) {
|
||||
if (kind === "users" && row.id === STATISTICS_UNBOUND_USER_ID) return
|
||||
@@ -348,175 +363,194 @@ function StatisticsPageInner() {
|
||||
: sliced
|
||||
? `${STATISTICS_DIMS.filter((d) => !hiddenKinds(slices).has(d.id)).length} разрезов`
|
||||
: `${rowsForKind(viewData, dim).length} строк`
|
||||
const hasContext = STATISTICS_CONTEXT_KEYS.some((key) => searchParams.has(key))
|
||||
const resetContext = () => updateParams(Object.fromEntries(STATISTICS_CONTEXT_KEYS.map((key) => [key, undefined])))
|
||||
const scope = planes === "all" ? "Все плоскости" : "GRE/WG клиентов, без hops"
|
||||
const bytesOf = (rows: StatisticsBreakdownRow[]) => rows.reduce((total, row) => total + row.bytes, 0)
|
||||
const shareOf = (bytes: number) => (kpis.bytes > 0 ? Math.min(1, bytes / kpis.bytes) : 0)
|
||||
const bytesItem = (id: string, title: string, caption: string, bytes: number, icon: ReactNode): CapacityItem => {
|
||||
const [valueText, ...unit] = formatBytes(bytes).split(" ")
|
||||
return { id, title, caption, value: bytes, total: kpis.bytes, ratio: shareOf(bytes), tone: shareOf(bytes) >= 0.999 ? "wn" : "ok", icon, valueText, unit: unit.join(" ") }
|
||||
}
|
||||
const planesControl = (
|
||||
<SegmentedControl
|
||||
value={planes}
|
||||
onChange={(next) => updateParams({ planes: next === "all" ? "all" : undefined })}
|
||||
options={[
|
||||
{ value: "all", label: "Все плоскости" },
|
||||
{ value: "unique", label: "GRE/WG клиентов" },
|
||||
]}
|
||||
/>
|
||||
)
|
||||
const cubeState = isLive && !dataReady ? (
|
||||
<div role="status" className="p-6 text-sm text-muted-foreground">{loading ? "Загрузка статистики…" : rangeError || paramsError ? "Исправьте параметры отчёта для загрузки статистики." : "Статистика недоступна. Повторите загрузку."}</div>
|
||||
) : emptyCube ? (
|
||||
<EmptyState
|
||||
title="Нет данных куба"
|
||||
description="За выбранный период нет IPFIX-фактов. Куб заполняется с момента деплоя, без бэкфилла за год."
|
||||
/>
|
||||
) : null
|
||||
const sliceChips = (
|
||||
<SliceChips
|
||||
chips={chips}
|
||||
onRemove={(key) => {
|
||||
const next = { ...slices }
|
||||
delete next[key as keyof CubeSlices]
|
||||
setSlices(next)
|
||||
}}
|
||||
/>
|
||||
)
|
||||
const filters = <StatisticsFilters key={JSON.stringify(slices)} slices={slices} onApply={setSlices} />
|
||||
const tabTrigger = "h-auto flex-none px-3 py-2.5 after:bottom-[-1px]"
|
||||
|
||||
return (
|
||||
<div className="flex h-full flex-col">
|
||||
<PageHeader
|
||||
crumbs={[{ label: "Обзор", href: "/dashboard" }, { label: "Статистика" }]}
|
||||
actions={rangeError ? <Button type="button" variant="outline" onClick={() => setRange(rangeForPreset("7d"))}>Выбрать последние 7 дней</Button> : <PeriodSelector range={range} onChange={setRange} />}
|
||||
/>
|
||||
<PageHeader crumbs={[{ label: "Главная", href: "/dashboard" }, { label: "Обзор" }, { label: "Статистика" }]} />
|
||||
|
||||
<div className="flex flex-1 flex-col gap-4 overflow-y-auto px-4 py-4 md:gap-6 md:px-6 md:py-5">
|
||||
{!isLive ? (
|
||||
<Alert>
|
||||
<AlertTitle>Живые данные выключены</AlertTitle>
|
||||
<AlertDescription>
|
||||
Куб статистики строится из IPFIX. Переключитесь на живой источник, чтобы увидеть отчёт.
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
) : null}
|
||||
<div className="flex flex-1 flex-col gap-6 overflow-y-auto px-4 pt-5 pb-10 md:px-7 md:pt-6">
|
||||
<PageTitle
|
||||
icon={<ChartColumnIcon />}
|
||||
title="Статистика"
|
||||
description="Куб NetFlow: измерения, срезы и период · уникальный объём без дублей"
|
||||
actions={
|
||||
<>
|
||||
{rangeError ? <Button type="button" variant="outline" onClick={() => setRange(rangeForPreset("7d"))}>Выбрать последние 7 дней</Button> : <PeriodSelector range={range} onChange={setRange} />}
|
||||
<Button type="button" variant="outline" onClick={resetContext} disabled={!hasContext}>Сбросить параметры отчёта</Button>
|
||||
</>
|
||||
}
|
||||
/>
|
||||
|
||||
{error ? (
|
||||
<Alert variant="destructive" role="alert">
|
||||
<AlertTitle>{rangeError ? "Некорректный период" : paramsError ? "Параметры отчёта требуют внимания" : "Ошибка загрузки"}</AlertTitle>
|
||||
<AlertDescription>{error}{!rangeError && !paramsError && <Button type="button" variant="outline" size="sm" onClick={() => setRetry(n => n + 1)}>Повторить загрузку</Button>}{paramsError && <Button type="button" variant="outline" size="sm" onClick={() => updateParams(Object.fromEntries(STATISTICS_CONTEXT_KEYS.map(key => [key, undefined])))}>Сбросить параметры отчёта</Button>}</AlertDescription>
|
||||
</Alert>
|
||||
) : null}
|
||||
<div className="flex flex-col gap-5">
|
||||
{!isLive ? (
|
||||
<Alert variant="warning">
|
||||
<AlertTitle>Живые данные выключены</AlertTitle>
|
||||
<AlertDescription>
|
||||
Показан демо-куб. Статистика строится из IPFIX — переключитесь на живой источник, чтобы увидеть свой отчёт.
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
) : null}
|
||||
|
||||
{!slices.serverId && dataReady && !emptyCube ? (
|
||||
<Alert>
|
||||
<AlertTitle>Уникальный объём</AlertTitle>
|
||||
<AlertDescription>
|
||||
Объём — трафик клиентов на GRE/WG, без повторного учёта JH↔EN и WAN.
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
) : null}
|
||||
{error ? (
|
||||
<Alert variant={paramsError ? "warning" : "destructive"} role="alert">
|
||||
<AlertTitle>{rangeError ? "Некорректный период" : paramsError ? "Параметры отчёта требуют внимания" : "Ошибка загрузки"}</AlertTitle>
|
||||
<AlertDescription>{error}{!rangeError && !paramsError && <Button type="button" variant="outline" size="sm" onClick={() => setRetry(n => n + 1)}>Повторить загрузку</Button>}</AlertDescription>
|
||||
</Alert>
|
||||
) : null}
|
||||
|
||||
{(dataReady || loading) && <KpiStatGrid
|
||||
aria-label="Сводка трафика"
|
||||
isLoading={loading}
|
||||
skeletonCount={5}
|
||||
items={[
|
||||
{
|
||||
id: "bytes",
|
||||
label: "Объём",
|
||||
value: formatBytes(kpis.bytes),
|
||||
hint: "GRE/WG клиентов, без hops",
|
||||
icon: <DatabaseIcon />,
|
||||
iconClassName: "text-muted-foreground",
|
||||
},
|
||||
{
|
||||
id: "packets",
|
||||
label: "Пакеты",
|
||||
value: kpis.packets.toLocaleString("ru-RU"),
|
||||
hint: kpis.topService ? `топ: ${kpis.topService}` : undefined,
|
||||
icon: <ActivityIcon />,
|
||||
iconClassName: "text-muted-foreground",
|
||||
},
|
||||
{
|
||||
id: "bps",
|
||||
label: "Средний bitrate",
|
||||
value: fmtBps(kpis.avgBps),
|
||||
icon: <GaugeIcon />,
|
||||
iconClassName: "text-muted-foreground",
|
||||
},
|
||||
{
|
||||
id: "users",
|
||||
label: "Пользователи",
|
||||
value: String(kpis.users),
|
||||
icon: <UsersIcon />,
|
||||
iconClassName: "text-muted-foreground",
|
||||
},
|
||||
{
|
||||
id: "servers",
|
||||
label: "Серверы",
|
||||
value: String(kpis.servers),
|
||||
hint: slices.serverId
|
||||
? (kpis.ifaces ? `${kpis.ifaces} iface` : undefined)
|
||||
: planes === "all"
|
||||
? "WAN и дубли в списке"
|
||||
: "без WAN и overlay",
|
||||
icon: <ServerIcon />,
|
||||
iconClassName: "text-muted-foreground",
|
||||
},
|
||||
]}
|
||||
/>}
|
||||
{(dataReady || loading || (demo && !paramsError)) && <KpiStatGrid
|
||||
aria-label="Сводка трафика"
|
||||
isLoading={loading}
|
||||
skeletonCount={4}
|
||||
items={[
|
||||
{
|
||||
id: "bytes",
|
||||
label: planes === "all" ? "Объём" : "Уникальный объём",
|
||||
value: formatBytes(kpis.bytes),
|
||||
hint: slices.serverId ? (kpis.ifaces ? `${kpis.ifaces} iface` : undefined) : planes === "all" ? "WAN и дубли в списке" : "без WAN и overlay",
|
||||
icon: <DatabaseIcon />,
|
||||
iconClassName: planes === "all" ? "text-muted-foreground" : "text-success",
|
||||
},
|
||||
{
|
||||
id: "packets",
|
||||
label: "Пакеты",
|
||||
value: kpis.packets.toLocaleString("ru-RU"),
|
||||
hint: kpis.topService ? `топ: ${kpis.topService}` : undefined,
|
||||
icon: <ActivityIcon />,
|
||||
iconClassName: "text-muted-foreground",
|
||||
},
|
||||
{
|
||||
id: "bps",
|
||||
label: "Средний bitrate",
|
||||
value: fmtBps(kpis.avgBps),
|
||||
icon: <GaugeIcon />,
|
||||
iconClassName: "text-muted-foreground",
|
||||
},
|
||||
{
|
||||
id: "users",
|
||||
label: "Пользователи",
|
||||
value: String(kpis.users),
|
||||
hint: `Серверы: ${kpis.servers}`,
|
||||
icon: <UsersIcon />,
|
||||
iconClassName: "text-muted-foreground",
|
||||
},
|
||||
]}
|
||||
/>}
|
||||
|
||||
{dataReady && <StatisticsVolumeChart series={viewData.series} grain={viewData.grain} />}
|
||||
<Tabs value={view} onValueChange={(next) => updateParams({ view: String(next) })} className="gap-5">
|
||||
<TabsList variant="line" className="h-auto w-full justify-start gap-1 overflow-x-auto border-b p-0">
|
||||
<TabsTrigger value="overview" className={tabTrigger}>Обзор</TabsTrigger>
|
||||
<TabsTrigger value="pivot" className={tabTrigger}>Сводная (куб)</TabsTrigger>
|
||||
<TabsTrigger value="explore" className={tabTrigger}>Срезы</TabsTrigger>
|
||||
</TabsList>
|
||||
|
||||
<DataPageCard>
|
||||
<DataPageToolbar
|
||||
leading={
|
||||
<div className="flex flex-wrap items-center gap-3">
|
||||
<SegmentedControl
|
||||
value={view}
|
||||
onChange={(next) => updateParams({ view: next === "pivot" ? "pivot" : "explore" })}
|
||||
options={[
|
||||
{ value: "explore", label: "Разрез" },
|
||||
{ value: "pivot", label: "Сводка" },
|
||||
]}
|
||||
/>
|
||||
<SegmentedControl
|
||||
value={planes}
|
||||
onChange={(next) => updateParams({ planes: next === "all" ? "all" : undefined })}
|
||||
options={[
|
||||
{ value: "unique", label: "Уникальный" },
|
||||
{ value: "all", label: "Все плоскости" },
|
||||
]}
|
||||
/>
|
||||
{view === "explore" && !sliced ? (
|
||||
<DimensionSelect
|
||||
label="Критерий"
|
||||
value={dim}
|
||||
onChange={(next) => updateParams({ dim: next, tab: undefined })}
|
||||
<TabsContent value="overview" className="flex flex-col gap-5">
|
||||
{cubeState ?? (
|
||||
<>
|
||||
<StatisticsVolumeChart series={viewData.series} grain={viewData.grain} scope={scope} actions={planesControl} />
|
||||
<CapacityGrid
|
||||
label="Доли объёма"
|
||||
items={[
|
||||
bytesItem("users", "Пользователи", "GRE/WG клиентов, без hops", bytesOf(viewData.users), <UsersIcon />),
|
||||
bytesItem("servers", "Серверы", planes === "all" ? "WAN и дубли в списке" : "без WAN и overlay", bytesOf(viewData.servers), <ServerIcon />),
|
||||
bytesItem("countries", "Страны", "Топ-10", bytesOf([...viewData.countries].sort((a, b) => b.bytes - a.bytes).slice(0, 10)), <GlobeIcon />),
|
||||
]}
|
||||
/>
|
||||
) : null}
|
||||
{view === "pivot" ? (
|
||||
<>
|
||||
<PivotDimSelect
|
||||
label="Строки"
|
||||
value={pivotRow}
|
||||
exclude={pivotCol}
|
||||
onChange={(next) => updateParams({ pivotRow: next })}
|
||||
/>
|
||||
<PivotDimSelect
|
||||
label="Колонки"
|
||||
value={pivotCol}
|
||||
exclude={pivotRow}
|
||||
onChange={(next) => updateParams({ pivotCol: next })}
|
||||
/>
|
||||
</>
|
||||
) : null}
|
||||
</div>
|
||||
}
|
||||
filterControl={<StatisticsFilters key={JSON.stringify(slices)} slices={slices} onApply={setSlices} />}
|
||||
countLabel={dataReady ? countLabel : undefined}
|
||||
/>
|
||||
<SliceChips
|
||||
chips={chips}
|
||||
onRemove={(key) => {
|
||||
const next = { ...slices }
|
||||
delete next[key as keyof CubeSlices]
|
||||
setSlices(next)
|
||||
}}
|
||||
/>
|
||||
{isLive && !dataReady ? (
|
||||
<div role="status" className="p-6 text-sm text-muted-foreground">{loading ? "Загрузка статистики…" : rangeError || paramsError ? "Исправьте параметры отчёта для загрузки статистики." : "Статистика недоступна. Повторите загрузку."}</div>
|
||||
) : emptyCube ? (
|
||||
<EmptyState
|
||||
title="Нет данных куба"
|
||||
description="За выбранный период нет IPFIX-фактов. Куб заполняется с момента деплоя, без бэкфилла за год."
|
||||
/>
|
||||
) : view === "pivot" ? (
|
||||
<StatisticsPivotGrid data={isLive ? pivot : EMPTY_PIVOT} onCellClick={handlePivotCell} isLoading={loading} />
|
||||
) : sliced ? (
|
||||
<BreakdownDashboard
|
||||
data={viewData}
|
||||
hidden={hiddenKinds(slices)}
|
||||
selectedIdFor={(kind) => selectedIdForKind(kind, slices)}
|
||||
onRowClick={handleRowClick}
|
||||
isLoading={loading}
|
||||
/>
|
||||
) : (
|
||||
<StatisticsBreakdownDataGrid
|
||||
rows={rowsForKind(viewData, dim)}
|
||||
kind={dim}
|
||||
selectedId={selectedIdForKind(dim, slices)}
|
||||
onRowClick={(row) => handleRowClick(dim, row)}
|
||||
isLoading={loading}
|
||||
/>
|
||||
)}
|
||||
</DataPageCard>
|
||||
</>
|
||||
)}
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="pivot">
|
||||
<DataPageCard>
|
||||
<DataPageToolbar
|
||||
leading={
|
||||
<div className="flex flex-wrap items-center gap-3">
|
||||
{planesControl}
|
||||
<PivotDimSelect label="Строки" value={pivotRow} exclude={pivotCol} onChange={(next) => updateParams({ pivotRow: next })} />
|
||||
<PivotDimSelect label="Колонки" value={pivotCol} exclude={pivotRow} onChange={(next) => updateParams({ pivotCol: next })} />
|
||||
</div>
|
||||
}
|
||||
filterControl={filters}
|
||||
countLabel={dataReady ? countLabel : undefined}
|
||||
/>
|
||||
{sliceChips}
|
||||
{cubeState ?? <StatisticsPivotGrid data={pivot} onCellClick={handlePivotCell} isLoading={loading} />}
|
||||
</DataPageCard>
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="explore">
|
||||
<DataPageCard>
|
||||
<DataPageToolbar
|
||||
leading={
|
||||
<div className="flex flex-wrap items-center gap-3">
|
||||
{planesControl}
|
||||
{!sliced ? <DimensionSelect label="Критерий" value={dim} onChange={(next) => updateParams({ dim: next, tab: undefined })} /> : null}
|
||||
</div>
|
||||
}
|
||||
filterControl={filters}
|
||||
countLabel={dataReady ? countLabel : undefined}
|
||||
/>
|
||||
{sliceChips}
|
||||
{cubeState ?? (sliced ? (
|
||||
<BreakdownDashboard
|
||||
data={viewData}
|
||||
hidden={hiddenKinds(slices)}
|
||||
selectedIdFor={(kind) => selectedIdForKind(kind, slices)}
|
||||
onRowClick={handleRowClick}
|
||||
isLoading={loading}
|
||||
/>
|
||||
) : (
|
||||
<StatisticsBreakdownDataGrid
|
||||
rows={rowsForKind(viewData, dim)}
|
||||
kind={dim}
|
||||
selectedId={selectedIdForKind(dim, slices)}
|
||||
onRowClick={(row) => handleRowClick(dim, row)}
|
||||
isLoading={loading}
|
||||
/>
|
||||
))}
|
||||
</DataPageCard>
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
|
||||
+364
-230
File diff suppressed because it is too large.
Load diff
@@ -464,6 +464,13 @@
|
||||
],
|
||||
"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",
|
||||
|
||||
@@ -7,6 +7,8 @@
|
||||
"test:mcp:module-completion": "tsx src/services/ipsec-server-init-model.test.ts && tsx src/modules/mcp/ipsec-server-init-actions.test.ts && tsx src/services/wireguard-revision-restore.test.ts && tsx src/modules/mcp/vrf-ticket-runtime.test.ts && tsx src/services/ipsec-restore.test.ts && tsx src/services/ipsec-pool-dependencies.test.ts && tsx src/services/vrf-production-transition.test.ts && tsx src/services/vrf-production-action-binding.test.ts && tsx src/services/ipsec-revision-restore-model.test.ts && tsx src/modules/mcp/ipsec-revision-actions.test.ts && tsx src/modules/mcp/service-native-progress.test.ts && tsx src/services/ipsec-revision-restore.test.ts && tsx src/services/ipsec-revision-secret.test.ts",
|
||||
"test:mcp:module-completion:pg": "node scripts/test-mcp-postgres.mjs --module-completion --restore",
|
||||
"test:mcp:pg": "node scripts/test-mcp-postgres.mjs",
|
||||
"test:mcp:network-diagnostics": "node --experimental-test-module-mocks --import tsx --test src/modules/mcp/incident-actions.test.ts src/modules/mcp/network-diagnostic-actions.test.ts src/modules/mcp/resilience-actions.test.ts",
|
||||
"test:mcp:network-diagnostics:pg": "node scripts/test-mcp-postgres.mjs --network-diagnostics",
|
||||
"test:mcp:pg:sharded": "node scripts/test-mcp-postgres-sharded.mjs",
|
||||
"test:mcp:users-bindings:pg": "node scripts/test-mcp-postgres.mjs --users-bindings",
|
||||
"test:mcp:bridge-vlan:pg": "node scripts/test-mcp-postgres.mjs --bridge-vlan-configuration",
|
||||
@@ -46,7 +48,7 @@
|
||||
"test:probes": "npm run test:speed-workflow && tsx src/services/manual-data-collection-execution.test.ts && tsx src/routes/manual-data-collection.test.ts && tsx src/services/network-host-resolution.test.ts && tsx src/routes/probes.test.ts && tsx src/routes/probes.cancel.test.ts && tsx src/services/ping-measurement.test.ts && tsx src/services/uptime-probe-observations.test.ts && tsx src/services/ping-measurement-sql.test.ts",
|
||||
"test:exec": "tsx src/services/mikrotik-logs.test.ts && tsx src/services/terminal-diagnostics.test.ts && tsx src/routes/exec.test.ts && tsx src/plugins/auth.exec.test.ts",
|
||||
"test:auth": "tsx --test src/modules/mcp/routing-manual-inverse-history.test.ts && tsx src/db/application-writer-profile-registry-structure.test.ts && tsx src/db/application-writer-profile-registry-read.test.ts && tsx src/db/application-writer-profile-registry-read-parity.test.ts && tsx src/db/application-writer-profile-format.test.ts && tsx src/plugins/auth-path.test.ts && tsx src/lib/permissions.test.ts && tsx src/plugins/auth-provenance.test.ts && tsx src/services/bandwidth-rest-speed-original.test.ts && tsx src/plugins/auth.smoke.test.ts && tsx src/plugins/auth.ospf-optimizer.test.ts && npm run test:mcp",
|
||||
"test:mcp": "node scripts/vrf-production-profile.test.mjs && node src/services/vrf-production-peer-telemetry.test.mjs && node src/services/vrf-execution-diagnostic.test.mjs && node src/services/vrf-transition-refusal.test.mjs && node src/services/vrf-production-gre-cycle.test.mjs && tsx src/services/vrf-production-gre-link-local.test.ts && tsx src/services/vrf-production-bridge-delete.test.ts && tsx src/services/vrf-production-transition.test.ts && tsx --test src/services/routeros-snapshot-read.test.ts src/services/bridge-vlan-configuration.test.ts src/modules/mcp/bridge-vlan-projection.test.ts src/modules/mcp/vrf-preparation-diagnostic.test.ts && tsx --test src/services/server-poll-error-provenance.test.ts && tsx --test src/modules/mcp/plan-expiry.test.ts src/modules/mcp/result-budget.test.ts src/modules/mcp/result-delivery.test.ts src/modules/mcp/wire-admission.test.ts src/modules/mcp/flow-envelope-allowance.test.ts src/modules/mcp/sdk-terminal-budget.test.ts src/modules/mcp/inflight-owner.test.ts && npm run test:database-source-binding && tsx --test src/modules/mcp/integration-fixture-expiry.test.ts && npm run test:mcp:operation-origin && npm run test:mcp:service-context && npm run test:mcp:operation-locks && tsx --test src/modules/mcp/routing-community-public.test.ts src/modules/mcp/management-transport.test.ts src/modules/mcp/routing-community-context-model.test.ts src/modules/mcp/routing-community-context-native.test.ts ../packages/contracts/src/mcp-routing.test.ts && tsx src/modules/mcp/human-artifact-receipts.test.ts && tsx src/modules/mcp/chr-overlay-readiness.test.ts && tsx src/modules/mcp/chr-recovery-source.test.ts && tsx src/modules/mcp/chr-native-failure.test.ts && tsx src/modules/mcp/ospf-owner-graph.test.ts && tsx src/modules/mcp/routing-measurement-address.test.ts && tsx src/modules/mcp/routing-observation-source.test.ts && tsx src/services/traffic-flow-talkers-model.test.ts && tsx src/services/bgp-prefix-model.test.ts && tsx src/services/vrf-members.test.ts && tsx src/services/routing-gateway-reference.test.ts && tsx src/services/bgp-export-model.test.ts && tsx src/services/traffic-history-model.test.ts && tsx src/services/internet-path-snapshot.test.ts && tsx src/services/internet-path-observation.test.ts && tsx src/modules/mcp/coverage.test.ts && tsx src/modules/mcp/policy.test.ts && tsx src/modules/mcp/events-batch-model.test.ts && tsx src/modules/mcp/operation-revisions.test.ts && tsx src/modules/mcp/native-create-identity.test.ts && tsx src/modules/mcp/ros-step-verification.test.ts && tsx src/modules/mcp/ros-prefix.test.ts && tsx src/modules/mcp/native-conservation-http.test.ts && tsx src/modules/mcp/security.test.ts && tsx src/modules/mcp/state-file-publish.test.ts && tsx src/modules/mcp/routing-model.test.ts && tsx src/modules/mcp/routing-observations-model.test.ts && tsx src/modules/mcp/ospf-health.test.ts && tsx src/modules/mcp/ecmp-preflight.test.ts && tsx src/modules/mcp/recursive-recovery.test.ts && tsx src/modules/mcp/control-path-model.test.ts && tsx src/modules/mcp/routing-community-scoped-model.test.ts && tsx src/modules/mcp/routing-community-scoped-native.test.ts && tsx src/modules/mcp/path-verification.test.ts && tsx src/modules/mcp/database-maintenance.test.ts && tsx src/routes/mcp.test.ts && tsx ../lib/auth-mcp.test.ts && tsx --test src/modules/mcp/routing-controller-fence.test.ts && tsx src/test/chr-vrf-companion-proof.test.ts && tsx src/test/chr-vrf-companion-telemetry.test.ts && tsx src/test/chr-vrf-companion-address-space.test.ts && tsx src/modules/mcp/flow-facts-rebuild-actions.test.ts && tsx src/modules/mcp/ipsec-peer-create-dependencies.test.ts && tsx src/services/ipsec-certificate-update-model.test.ts && tsx src/modules/mcp/ipsec-native-dispatch.test.ts && tsx src/modules/mcp/ipsec-user-update-actions.test.ts && tsx src/modules/mcp/ipsec-server-delete-actions.test.ts && tsx src/services/ipsec-proof-telemetry.test.ts && tsx src/services/vrf-production-admission.test.ts && tsx src/modules/mcp/flow-host-keys-actions.test.ts && tsx src/services/vrf-production-read.test.ts && tsx --test src/services/vrf-production-wireguard-alias.test.ts && tsx src/modules/mcp/ipsec-user-create-actions.test.ts && tsx src/modules/mcp/flow-settings-actions.test.ts && tsx src/services/vrf-production-ticket-store.test.ts && npm run test:mcp:routing-baseline",
|
||||
"test:mcp": "node scripts/vrf-production-profile.test.mjs && node src/services/vrf-production-peer-telemetry.test.mjs && node src/services/vrf-execution-diagnostic.test.mjs && node src/services/vrf-transition-refusal.test.mjs && node src/services/vrf-production-gre-cycle.test.mjs && tsx src/services/vrf-production-gre-link-local.test.ts && tsx src/services/vrf-production-bridge-delete.test.ts && tsx src/services/vrf-production-transition.test.ts && tsx --test src/services/routeros-snapshot-read.test.ts src/services/bridge-vlan-configuration.test.ts src/modules/mcp/bridge-vlan-projection.test.ts src/modules/mcp/vrf-preparation-diagnostic.test.ts && tsx --test src/services/server-poll-error-provenance.test.ts && tsx --test src/modules/mcp/plan-expiry.test.ts src/modules/mcp/result-budget.test.ts src/modules/mcp/result-delivery.test.ts src/modules/mcp/wire-admission.test.ts src/modules/mcp/flow-envelope-allowance.test.ts src/modules/mcp/sdk-terminal-budget.test.ts src/modules/mcp/inflight-owner.test.ts && npm run test:database-source-binding && tsx --test src/modules/mcp/integration-fixture-expiry.test.ts && npm run test:mcp:operation-origin && npm run test:mcp:service-context && npm run test:mcp:operation-locks && tsx --test src/modules/mcp/routing-community-public.test.ts src/modules/mcp/management-transport.test.ts src/modules/mcp/routing-community-context-model.test.ts src/modules/mcp/routing-community-context-native.test.ts ../packages/contracts/src/mcp-routing.test.ts && tsx src/modules/mcp/human-artifact-receipts.test.ts && tsx src/modules/mcp/chr-overlay-readiness.test.ts && tsx src/modules/mcp/chr-recovery-source.test.ts && tsx src/modules/mcp/chr-native-failure.test.ts && tsx src/modules/mcp/ospf-owner-graph.test.ts && tsx src/modules/mcp/routing-measurement-address.test.ts && tsx src/modules/mcp/routing-observation-source.test.ts && tsx src/services/traffic-flow-talkers-model.test.ts && tsx src/services/bgp-prefix-model.test.ts && tsx src/services/vrf-members.test.ts && tsx src/services/routing-gateway-reference.test.ts && tsx src/services/bgp-export-model.test.ts && tsx src/services/traffic-history-model.test.ts && tsx src/services/internet-path-snapshot.test.ts && tsx src/services/internet-path-observation.test.ts && tsx src/modules/mcp/coverage.test.ts && tsx src/modules/mcp/policy.test.ts && tsx src/modules/mcp/events-batch-model.test.ts && tsx src/modules/mcp/operation-revisions.test.ts && tsx src/modules/mcp/native-create-identity.test.ts && tsx src/modules/mcp/ros-step-verification.test.ts && tsx src/modules/mcp/ros-prefix.test.ts && tsx src/modules/mcp/native-conservation-http.test.ts && tsx src/modules/mcp/security.test.ts && tsx src/modules/mcp/state-file-publish.test.ts && tsx src/modules/mcp/routing-model.test.ts && tsx src/modules/mcp/routing-observations-model.test.ts && tsx src/modules/mcp/ospf-health.test.ts && tsx src/modules/mcp/ecmp-preflight.test.ts && tsx src/modules/mcp/recursive-recovery.test.ts && tsx src/modules/mcp/control-path-model.test.ts && tsx src/modules/mcp/routing-community-scoped-model.test.ts && tsx src/modules/mcp/routing-community-scoped-native.test.ts && tsx src/modules/mcp/path-verification.test.ts && tsx src/modules/mcp/database-maintenance.test.ts && tsx src/routes/mcp.test.ts && tsx ../lib/auth-mcp.test.ts && tsx --test src/modules/mcp/routing-controller-fence.test.ts && tsx src/test/chr-vrf-companion-proof.test.ts && tsx src/test/chr-vrf-companion-telemetry.test.ts && tsx src/test/chr-vrf-companion-address-space.test.ts && tsx src/modules/mcp/flow-facts-rebuild-actions.test.ts && tsx src/modules/mcp/ipsec-peer-create-dependencies.test.ts && tsx src/services/ipsec-certificate-update-model.test.ts && tsx src/modules/mcp/ipsec-native-dispatch.test.ts && tsx src/modules/mcp/ipsec-user-update-actions.test.ts && tsx src/modules/mcp/ipsec-server-delete-actions.test.ts && tsx src/services/ipsec-proof-telemetry.test.ts && tsx src/services/vrf-production-admission.test.ts && tsx src/modules/mcp/flow-host-keys-actions.test.ts && tsx src/services/vrf-production-read.test.ts && tsx --test src/services/vrf-production-wireguard-alias.test.ts && tsx src/modules/mcp/ipsec-user-create-actions.test.ts && tsx src/modules/mcp/flow-settings-actions.test.ts && tsx src/services/vrf-production-ticket-store.test.ts && npm run test:mcp:routing-baseline && npm run test:mcp:network-diagnostics",
|
||||
"test:wireguard": "tsx src/services/mikrotik-response-bounds.test.ts && tsx --test src/services/wireguard-dependency-read.test.ts && tsx src/services/wireguard-interface-update.test.ts && tsx src/services/wireguard-peer-update.test.ts && npx tsx src/services/wireguard-config.test.ts && npx tsx src/services/wireguard-ipv6.test.ts && npx tsx --test src/services/wireguard-import.test.ts src/services/wireguard-import-apply.test.ts src/services/wireguard-import-revision.test.ts src/services/wireguard-delete.test.ts && npx tsx src/routes/wireguard-import.test.ts && tsx src/services/wireguard-interface-create.test.ts && tsx src/services/wireguard-peer-create.test.ts && tsx src/services/wireguard-import-plan.test.ts && tsx src/services/wireguard-import-execution.test.ts && tsx src/modules/mcp/wireguard-import-actions.test.ts && tsx --test src/services/wireguard-export.test.ts",
|
||||
"test:traffic-rate": "tsx src/services/traffic-rate.test.ts && tsx src/services/traffic-observation.test.ts && tsx src/services/traffic-freshness.test.ts && tsx src/services/traffic-live.test.ts && tsx src/services/traffic-observation-sql.test.ts && tsx src/services/traffic-history-sql.test.ts && tsx src/services/traffic-live-sql.test.ts && tsx src/services/traffic-volume-sql.test.ts && tsx src/services/traffic-binding-status.test.ts && tsx src/services/traffic-status-sql.test.ts && tsx src/services/traffic-gap.test.ts && tsx src/services/traffic-identity.test.ts && tsx src/services/traffic-membership.test.ts && tsx src/services/traffic-aggregate-peak.test.ts && tsx src/services/traffic-users-cache.test.ts && tsx src/services/traffic-collection-lock.test.ts && tsx src/services/traffic-concurrency-sql.test.ts",
|
||||
"test:traffic-flow": "tsx --test src/services/traffic-flow-heartbeat.test.ts src/services/traffic-flow-heartbeat-wiring.test.ts src/services/traffic-flow-heartbeat-receiver.test.ts src/services/traffic-flow-ingest-quality.test.ts src/services/traffic-flow-quality-contract.test.ts && tsx src/services/traffic-flow-catalog-read.test.ts && tsx src/routes/traffic-flow-query.test.ts && tsx src/services/traffic-flow-month.test.ts && tsx src/services/traffic-flow-parse.test.ts && tsx src/services/traffic-flow-ipv6-pipeline.test.ts && tsx src/services/traffic-flow-map-exporter.test.ts && tsx src/services/traffic-flow-ifaces.test.ts && tsx src/services/traffic-flow-ifindex.test.ts && tsx src/services/traffic-flow-dedup.test.ts && tsx src/services/traffic-flow-planes.test.ts && tsx src/services/traffic-flow-ip.test.ts && tsx src/services/traffic-flow-dest.test.ts && tsx src/services/traffic-flow-classify.test.ts && tsx src/services/traffic-flow-ripe.test.ts && tsx src/services/traffic-flow-brands.test.ts && tsx src/services/traffic-flow-ingest.test.ts && tsx src/services/traffic-flow-analytics.test.ts && tsx src/services/traffic-flow-map-hops.test.ts && tsx src/services/traffic-flow-purge.test.ts && tsx src/services/geoip-download.test.ts && tsx src/services/traffic-flow-geoip.test.ts && tsx src/services/traffic-flow-fact-accumulator.test.ts && tsx src/services/traffic-flow-facts.test.ts && tsx src/services/traffic-flow-facts-filter.test.ts && tsx src/services/traffic-flow-facts-rebuild.test.ts && tsx src/services/statistics-aggregate.test.ts && tsx src/services/geoip-manual-update.test.ts && tsx src/services/traffic-flow-overlay-model.test.ts && npm run test:traffic-flow:ownership && tsx src/services/traffic-flow-worker-platform.test.ts && tsx src/services/traffic-flow-template-cache.test.ts && tsx --test src/services/traffic-flow-template-lifetime.test.ts && tsx src/services/traffic-flow-protocol-scope.test.ts && npm run test:traffic-flow:read-budget && npm run test:traffic-flow:resource-profile",
|
||||
@@ -60,7 +62,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: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: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",
|
||||
"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: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",
|
||||
|
||||
@@ -178,6 +178,8 @@ if (usersBindings && (process.argv.length !== 3 || process.argv[2] !== '--users-
|
||||
const bridgeVlanConfiguration = process.argv.includes('--bridge-vlan-configuration')
|
||||
if (bridgeVlanConfiguration && process.argv.slice(2).some(arg => arg !== '--bridge-vlan-configuration')) throw new Error('Bridge VLAN acceptance requires its own disposable cluster')
|
||||
const applicationAdapters = process.argv.includes('--application-adapters')
|
||||
const networkDiagnostics = process.argv.includes('--network-diagnostics')
|
||||
if (networkDiagnostics && process.argv.length !== 3) throw new Error('Network diagnostics require their own disposable cluster')
|
||||
const scopedRoutingDiagnostics = process.argv.includes('--scoped-routing-diagnostics')
|
||||
const interfaceEventsCompatibility = process.argv.includes('--interface-events-compatibility')
|
||||
const eventsOnly = process.argv.includes('--events-only')
|
||||
@@ -262,7 +264,7 @@ try {
|
||||
await postgres.start()
|
||||
const binaries = await import(`@embedded-postgres/${process.platform === 'win32' ? 'windows' : process.platform}-${process.arch}`)
|
||||
const testPath = [process.env.MMAPP_PG_CLIENT_BIN, dirname(binaries.postgres), process.env.PATH ?? process.env.Path ?? ''].filter(Boolean).join(delimiter)
|
||||
if (!profilesOnly && (restoreQuarantineOnly || process.argv.includes('--restore') || process.env.MMAPP_PG_CLIENT_BIN)) {
|
||||
if (!profilesOnly && !networkDiagnostics && (restoreQuarantineOnly || process.argv.includes('--restore') || process.env.MMAPP_PG_CLIENT_BIN)) {
|
||||
for (const command of ['pg_dump', 'pg_restore']) await new Promise((resolve, reject) => {
|
||||
execFile(command, ['--version'], { env: { ...process.env, PATH: testPath }, windowsHide: true, timeout: 5000, maxBuffer: 4096 }, error => {
|
||||
if (error) reject(new Error(`Restore acceptance requires working ${command}; set MMAPP_PG_CLIENT_BIN to the PostgreSQL client bin directory`))
|
||||
@@ -274,8 +276,9 @@ try {
|
||||
if (regressionOnly) console.log('Selected regression only: primary integration and terminal restore are not run')
|
||||
if (profilesOnly) console.log('Profiles-only regression matrix: primary integration NOT RUN; terminal restore NOT RUN; full acceptance is not claimed')
|
||||
const result = regressionOnly || profilesOnly ? 0 : await new Promise((resolve, reject) => {
|
||||
const child = spawn(process.execPath, pollMemory ? ['--max-old-space-size=192', '--max-semi-space-size=16', fileURLToPath(new URL('../dist-mcp-memory/services/server-poll-memory.owned.test.js', import.meta.url))] : ['--import', 'tsx', ...(flowActiveRebuild ? ['--import', new URL('../src/services/traffic-flow-active-rebuild-preload.mjs', import.meta.url).href] : []), acceptanceShard ? 'src/modules/mcp/acceptance-shard.test.ts' : usersBindings ? 'src/modules/mcp/users-bindings-owned.test.ts' : bridgeVlanConfiguration ? 'src/modules/mcp/bridge-vlan-configuration-http.test.ts' : protocolLimits ? 'src/modules/mcp/protocol-limits.owned.test.ts' : principalSecuritySource ? 'src/modules/mcp/principal-security-source.owned.test.ts' : pollJournalSnapshot ? 'src/services/server-poll-journal-snapshot.owned.test.ts' : pollTerminalArchive ? 'src/services/server-poll-terminal-archive.owned.test.ts' : pollArchiveSchema ? 'src/db/server-poll-terminal-archives.sql.test.ts' : telemetrySettingsConfiguration ? 'src/modules/mcp/telemetry-settings-configuration.owned.test.ts' : routingReservationSchema ? 'src/db/routing-reservation-schema.owned.test.ts' : routingForwardRounds ? 'src/modules/mcp/routing-network-forward-rounds.owned.test.ts' : flowActiveServices ? 'src/services/traffic-flow-active-services.owned.test.ts' : flowActiveRebuild ? 'src/services/traffic-flow-active-rebuild.owned.test.ts' : flowQuality ? 'src/services/traffic-flow-quality.owned.test.ts' : flowWorkerIpc ? 'src/services/traffic-flow-worker-ipc.owned.test.ts' : manualUptime ? 'src/modules/mcp/manual-uptime-http.test.ts' : manualPingGroup ? 'src/modules/mcp/manual-ping-group-http.test.ts' : manualTraffic ? 'src/modules/mcp/manual-traffic-http.test.ts' : manualApiPing ? 'src/modules/mcp/manual-api-ping-http.test.ts' : simpleSpeedChr ? 'src/modules/mcp/simple-speed-chr.test.ts' : simpleSpeed ? 'src/modules/mcp/simple-speed-http.test.ts' : externalPeerMetadata ? 'src/services/bandwidth-external-peer-metadata.sql.test.ts' : operatorPeerMetadata ? 'src/services/bandwidth-operator-metadata.sql.test.ts' : publicRegistryMetadata ? 'src/services/bandwidth-public-registry.sql.test.ts' : operatorDockerSql ? 'src/services/bandwidth-operator-docker-stop.sql.test.ts' : probeOperationRetirement ? 'src/services/server-probe-operation-retirement.owned.test.ts' : ordinaryOperationRetirement ? 'src/modules/mcp/ordinary-operation-retirement.owned.test.ts' : pollOperationRetirement ? 'src/services/server-poll-operation-retirement.owned.test.ts' : mcpOperationOrigin ? 'src/modules/mcp/operation-execution-origin.sql.test.ts' : mcpSpeedOriginal ? 'src/modules/mcp/speed-bandwidth-original.sql.test.ts' : routerConfigurationGuard ? 'src/services/router-configuration-guard.sql.test.ts' : scheduledSpeedOriginal ? 'src/services/bandwidth-scheduled-speed-original.sql.test.ts' : bandwidthSpeedWorkflow ? 'src/services/bandwidth-speed-workflow.sql.test.ts' : restSpeedOriginal ? 'src/services/bandwidth-rest-speed-original.sql.test.ts' : operationLocks ? 'src/services/operation-config-lock-lease.sql.test.ts' : serviceExecutionOrigin ? 'src/modules/mcp/service-execution-origin.sql.test.ts' : bandwidthNodeSource ? 'src/services/bandwidth-node-source.sql.test.ts' : bandwidthExternalRegistry ? 'src/services/bandwidth-external-node-registry.sql.test.ts' : bandwidthNodeRegistry ? 'src/services/bandwidth-node-registry.sql.test.ts' : bandwidthControlSource ? 'src/services/bandwidth-control-source.sql.test.ts' : bandwidthAdmission ? 'src/services/bandwidth-admission.sql.test.ts' : serverPollStorageFresh ? 'src/services/server-poll-storage-fresh.sql.test.ts' : serverPollStorage ? 'src/services/server-poll-storage.sql.test.ts' : probeStorageFresh ? 'src/services/server-probe-storage-fresh.sql.test.ts' : probeLegacyOrphans ? 'src/services/server-probe-legacy-orphans.sql.test.ts' : diagnosticCancelHost ? 'src/modules/mcp/diagnostic-cancellation-storage.sql.test.ts' : ipsecExportHttp ? 'src/modules/mcp/ipsec-existing-certificate-export-http.sql.test.ts' : ipsecExportJournal ? 'src/services/ipsec-existing-certificate-export-rest-journal.sql.test.ts' : migrationDataInventory ? 'src/db/migration-data-inventory.sql.test.ts' : probeStorageHistory ? 'src/services/server-probe-storage-history.sql.test.ts' : probeStorageJournal ? 'src/services/server-probe-storage-journal.sql.test.ts' : controlledSchemaReference ? 'src/db/controlled-schema-reference.sql.test.ts' : controlledMigrations ? 'src/db/controlled-migrations.sql.test.ts' : databaseSchemaControl ? 'src/db/database-schema-control.sql.test.ts' : migrationSchemaInventory ? 'src/db/migration-schema-inventory.sql.test.ts' : routingNetworkNative ? 'src/modules/mcp/routing-network-native.sql.test.ts' : routingReservationRuntime ? 'src/modules/mcp/routing-reservation-runtime.sql.test.ts' : routingReservations ? 'src/modules/mcp/routing-reservation.sql.test.ts' : collectorPartitionWriters ? 'src/services/collector-partition-writes.sql.test.ts' : serverPollDurableLine truncated
|
||||
const child = spawn(process.execPath, pollMemory ? ['--max-old-space-size=192', '--max-semi-space-size=16', fileURLToPath(new URL('../dist-mcp-memory/services/server-poll-memory.owned.test.js', import.meta.url))] : ['--import', 'tsx', ...(flowActiveRebuild ? ['--import', new URL('../src/services/traffic-flow-active-rebuild-preload.mjs', import.meta.url).href] : []), networkDiagnostics ? 'src/modules/mcp/network-diagnostics.owned.test.ts' : acceptanceShard ? 'src/modules/mcp/acceptance-shard.test.ts' : usersBindings ? 'src/modules/mcp/users-bindings-owned.test.ts' : bridgeVlanConfiguration ? 'src/modules/mcp/bridge-vlan-configuration-http.test.ts' : protocolLimits ? 'src/modules/mcp/protocol-limits.owned.test.ts' : principalSecuritySource ? 'src/modules/mcp/principal-security-source.owned.test.ts' : pollJournalSnapshot ? 'src/services/server-poll-journal-snapshot.owned.test.ts' : pollTerminalArchive ? 'src/services/server-poll-terminal-archive.owned.test.ts' : pollArchiveSchema ? 'src/db/server-poll-terminal-archives.sql.test.ts' : telemetrySettingsConfiguration ? 'src/modules/mcp/telemetry-settings-configuration.owned.test.ts' : routingReservationSchema ? 'src/db/routing-reservation-schema.owned.test.ts' : routingForwardRounds ? 'src/modules/mcp/routing-network-forward-rounds.owned.test.ts' : flowActiveServices ? 'src/services/traffic-flow-active-services.owned.test.ts' : flowActiveRebuild ? 'src/services/traffic-flow-active-rebuild.owned.test.ts' : flowQuality ? 'src/services/traffic-flow-quality.owned.test.ts' : flowWorkerIpc ? 'src/services/traffic-flow-worker-ipc.owned.test.ts' : manualUptime ? 'src/modules/mcp/manual-uptime-http.test.ts' : manualPingGroup ? 'src/modules/mcp/manual-ping-group-http.test.ts' : manualTraffic ? 'src/modules/mcp/manual-traffic-http.test.ts' : manualApiPing ? 'src/modules/mcp/manual-api-ping-http.test.ts' : simpleSpeedChr ? 'src/modules/mcp/simple-speed-chr.test.ts' : simpleSpeed ? 'src/modules/mcp/simple-speed-http.test.ts' : externalPeerMetadata ? 'src/services/bandwidth-external-peer-metadata.sql.test.ts' : operatorPeerMetadata ? 'src/services/bandwidth-operator-metadata.sql.test.ts' : publicRegistryMetadata ? 'src/services/bandwidth-public-registry.sql.test.ts' : operatorDockerSql ? 'src/services/bandwidth-operator-docker-stop.sql.test.ts' : probeOperationRetirement ? 'src/services/server-probe-operation-retirement.owned.test.ts' : ordinaryOperationRetirement ? 'src/modules/mcp/ordinary-operation-retirement.owned.test.ts' : pollOperationRetirement ? 'src/services/server-poll-operation-retirement.owned.test.ts' : mcpOperationOrigin ? 'src/modules/mcp/operation-execution-origin.sql.test.ts' : mcpSpeedOriginal ? 'src/modules/mcp/speed-bandwidth-original.sql.test.ts' : routerConfigurationGuard ? 'src/services/router-configuration-guard.sql.test.ts' : scheduledSpeedOriginal ? 'src/services/bandwidth-scheduled-speed-original.sql.test.ts' : bandwidthSpeedWorkflow ? 'src/services/bandwidth-speed-workflow.sql.test.ts' : restSpeedOriginal ? 'src/services/bandwidth-rest-speed-original.sql.test.ts' : operationLocks ? 'src/services/operation-config-lock-lease.sql.test.ts' : serviceExecutionOrigin ? 'src/modules/mcp/service-execution-origin.sql.test.ts' : bandwidthNodeSource ? 'src/services/bandwidth-node-source.sql.test.ts' : bandwidthExternalRegistry ? 'src/services/bandwidth-external-node-registry.sql.test.ts' : bandwidthNodeRegistry ? 'src/services/bandwidth-node-registry.sql.test.ts' : bandwidthControlSource ? 'src/services/bandwidth-control-source.sql.test.ts' : bandwidthAdmission ? 'src/services/bandwidth-admission.sql.test.ts' : serverPollStorageFresh ? 'src/services/server-poll-storage-fresh.sql.test.ts' : serverPollStorage ? 'src/services/server-poll-storage.sql.test.ts' : probeStorageFresh ? 'src/services/server-probe-storage-fresh.sql.test.ts' : probeLegacyOrphans ? 'src/services/server-probe-legacy-orphans.sql.test.ts' : diagnosticCancelHost ? 'src/modules/mcp/diagnostic-cancellation-storage.sql.test.ts' : ipsecExportHttp ? 'src/modules/mcp/ipsec-existing-certificate-export-http.sql.test.ts' : ipsecExportJournal ? 'src/services/ipsec-existing-certificate-export-rest-journal.sql.test.ts' : migrationDataInventory ? 'src/db/migration-data-inventory.sql.test.ts' : probeStorageHistory ? 'src/services/server-probe-storage-history.sql.test.ts' : probeStorageJournal ? 'src/services/server-probe-storage-journal.sql.test.ts' : controlledSchemaReference ? 'src/db/controlled-schema-reference.sql.test.ts' : controlledMigrations ? 'src/db/controlled-migrations.sql.test.ts' : databaseSchemaControl ? 'src/db/database-schema-control.sql.test.ts' : migrationSchemaInventory ? 'src/db/migration-schema-inventory.sql.test.ts' : routingNetworkNative ? 'src/modules/mcp/routing-network-native.sql.test.ts' : routingReservationRuntime ? 'src/modules/mcp/routing-reservation-runtime.sql.test.ts' : routingReservations ? 'src/modules/mcp/routing-reservation.sql.test.ts' : collectorPartitionWriters
Line truncated
|
||||
cwd: pollMemory ? directory : new URL('../', import.meta.url), stdio: 'inherit', env: { ...(pollMemory ? pollMemoryEnvironment : process.env),
|
||||
MMAPP_OWN_NETWORK_DIAGNOSTICS: String(networkDiagnostics),
|
||||
MMAPP_OWN_SKIP_POLL_CAPACITY: String(pollRetirementFocused),
|
||||
MMAPP_OWN_PROTOCOL_LIMITS: String(protocolLimits),
|
||||
MMAPP_OWN_EVENTS_ONLY: String(eventsOnly),
|
||||
@@ -300,7 +303,7 @@ try {
|
||||
})
|
||||
exitCode = result
|
||||
if (result === 0 && restoreQuarantineOnly) console.log('Restore quarantine: focused real PostgreSQL restore scenario complete')
|
||||
else if (result === 0 && !acceptanceShard && !regressionOnly && !profilesOnly && !usersBindings && !bridgeVlanConfiguration && !protocolLimits && !pollMemory && !principalSecuritySource && !pollJournalSnapshot && !pollArchiveSchema && !telemetrySettingsConfiguration && !routingReservationSchema && !routingForwardRounds && !flowActiveServices && !flowActiveRebuild && !flowQuality && !flowWorkerIpc && !manualUptime && !manualPingGroup && !manualTraffic && !manualApiPing && !simpleSpeed && !simpleSpeedChr && !externalPeerMetadata && !operatorPeerMetadata && !publicRegistryMetadata && !operatorDockerSql && !mcpOperationOrigin && !mcpSpeedOriginal && !routerConfigurationGuard && !scheduledSpeedOriginal && !bandwidthSpeedWorkflow && !restSpeedOriginal && !operationLocks && !serviceExecutionOrigin && !bandwidthNodeSource && !bandwidthNodeRegistry && !bandwidthExternalRegistry && !bandwidthControlSource && !bandwidthAdmission && !probeLegacyOrphans && !probeStorageJournal && !probeStorageHistory && !probeJournal && !chr && !flowWrites && !flowRebuild && !flowRebuildMcp && (process.argv.includes('--restore') || process.env.MMAPP_PG_CLIENT_BIN)) {
|
||||
else if (result === 0 && !networkDiagnostics && !acceptanceShard && !regressionOnly && !profilesOnly && !usersBindings && !bridgeVlanConfiguration && !protocolLimits && !pollMemory && !principalSecuritySource && !pollJournalSnapshot && !pollArchiveSchema && !telemetrySettingsConfiguration && !routingReservationSchema && !routingForwardRounds && !flowActiveServices && !flowActiveRebuild && !flowQuality && !flowWorkerIpc && !manualUptime && !manualPingGroup && !manualTraffic && !manualApiPing && !simpleSpeed && !simpleSpeedChr && !externalPeerMetadata && !operatorPeerMetadata && !publicRegistryMetadata && !operatorDockerSql && !mcpOperationOrigin && !mcpSpeedOriginal && !routerConfigurationGuard && !scheduledSpeedOriginal && !bandwidthSpeedWorkflow && !restSpeedOriginal && !operationLocks && !serviceExecutionOrigin && !bandwidthNodeSource && !bandwidthNodeRegistry && !bandwidthExternalRegistry && !bandwidthControlSource && !bandwidthAdmission && !probeLegacyOrphans && !probeStorageJournal && !probeStorageHistory && !probeJournal && !chr && !flowWrites && !flowRebuild && !flowRebuildMcp && (process.argv.includes('--restore') || process.env.MMAPP_PG_CLIENT_BIN)) {
|
||||
exitCode = await new Promise((resolve, reject) => {
|
||||
const child = spawn(process.execPath, ['--import', 'tsx', 'src/modules/mcp/database-restore.test.ts'], {
|
||||
cwd: new URL('../', import.meta.url), stdio: 'inherit', env: { ...process.env,
|
||||
@@ -313,6 +316,7 @@ try {
|
||||
child.once('error', reject); child.once('exit', code => resolve(code ?? 1))
|
||||
})
|
||||
}
|
||||
else if (result === 0 && networkDiagnostics) console.log('Network diagnostics: scoped MCP SDK and disposable PostgreSQL')
|
||||
else if (result === 0 && pollArchiveSchema) console.log('Poll archive schema: owned nonempty40 preservation, numbered41 and structural refusal guards; no positive MCP archive claim')
|
||||
else if (result === 0 && telemetrySettingsConfiguration) console.log('Telemetry settings: genuine MCP/SQL configuration binding, collector metadata tolerated; no native or external sources')
|
||||
else if (result === 0 && routingReservationSchema) console.log('Routing reservation numbered0040: ownSQL fresh/legacy/manual preservation; no READY, backfill, capabilities or public native activation')
|
||||
|
||||
@@ -27,6 +27,7 @@ import internetPathRoutes from "./routes/internet-path.js"
|
||||
import evobgpRoutes from "./routes/evobgp.js"
|
||||
import { createStorageProbeRoutes } from "./routes/probe-storage-handler.js"
|
||||
import schedulerRoutes from "./routes/scheduler.js"
|
||||
import { ConfigurationBusyError } from "./services/config-mutation-lock.js"
|
||||
import sidebarCountsRoutes from "./routes/sidebar-counts.js"
|
||||
import alertsRoutes from "./routes/alerts.js"
|
||||
import backupsRoutes from "./routes/backups.js"
|
||||
@@ -105,6 +106,7 @@ export async function buildApp(opts?: {
|
||||
return reply.status(status).send({ error: "Внутренняя ошибка сервера" })
|
||||
}
|
||||
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 })
|
||||
})
|
||||
|
||||
|
||||
@@ -1,4 +1,8 @@
|
||||
import { registerIpsecServerDeleteActions } from "./ipsec-server-delete-actions.js"
|
||||
import { registerCapabilityActions } from "./capability-actions.js"
|
||||
import { registerIncidentActions } from "./incident-actions.js"
|
||||
import { registerNetworkDiagnosticActions } from "./network-diagnostic-actions.js"
|
||||
import { registerResilienceActions } from "./resilience-actions.js"
|
||||
import { registerIpsecServerInitActions } from "./ipsec-server-init-actions.js"
|
||||
import { registerIpsecRevisionActions } from "./ipsec-revision-actions.js"
|
||||
import { registerWireguardRevisionActions } from "./wireguard-revision-actions.js"
|
||||
@@ -30,7 +34,7 @@ import { gatewayReferencesTable, isDynamicRouteInsideTable } from "../../service
|
||||
import { readLogStream } from "../../services/router-logs-query.js"
|
||||
import { subscribeLogDevice } from "../../services/router-logs-collector.js"
|
||||
import { ospfFilterFields, rosResources, readRosSnapshot, resourceById, routerClient, validateRosStep, splitOspfUnsetUpdate } from "./resources.js"
|
||||
import { registerMcpOperation, listMcpOperations } from "./registry.js"
|
||||
import { registerMcpOperation } from "./registry.js"
|
||||
import { accessGeneration, decryptSecret, encryptSecret, fingerprint, MAX_MCP_PUBLIC_ARRAY_ITEMS, MAX_MCP_PUBLIC_STRING_LENGTH, McpError, redact } from "./security.js"
|
||||
import { hasUnattendedPlanAuthority } from "./policy.js"
|
||||
import { effectiveMcpConnection } from "./store.js"
|
||||
@@ -386,9 +390,8 @@ for (const definition of [
|
||||
})
|
||||
}
|
||||
|
||||
add("capabilities.read", "mm_capabilities_get", "Доступные возможности", "mcp", null, "read", "connection", z.object({}).strict(), {
|
||||
read: async (_input, context) => ({ operations: listMcpOperations().filter(operation => operation.implementation === "available" && context.connection.policy.scope.operationIds.includes(operation.id)), schemaVersion: 1 }),
|
||||
})
|
||||
registerCapabilityActions(add)
|
||||
registerIncidentActions(add)
|
||||
add("servers.list", "mm_servers_list", "Серверы", "servers", "mm:servers:read", "read", "servers", z.object({ serverId: serverId.optional(), ...paging }).strict(), {
|
||||
read: async (input, context) => {
|
||||
const ids = typeof input.serverId === "number" ? [input.serverId] : context.connection.policy.scope.serverIds
|
||||
@@ -664,6 +667,8 @@ add("operations.read", "mm_operation_get", "Результат своей опе
|
||||
})
|
||||
|
||||
registerRoutingActions(add)
|
||||
registerNetworkDiagnosticActions(add)
|
||||
registerResilienceActions(add)
|
||||
registerRoutingProfileActions(add)
|
||||
registerRoutingControls(add)
|
||||
registerLifecycleActions(add)
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
import { z } from "zod"
|
||||
import type { McpPolicyPreviewRequest } from "@mmapp/contracts/mcp"
|
||||
import type { ActionContext } from "./action-types.js"
|
||||
import type { add } from "./actions.js"
|
||||
import { evaluateMcpPolicy } from "./policy.js"
|
||||
import { listMcpOperations } from "./registry.js"
|
||||
|
||||
const identifier = z.string().trim().min(1).max(200).optional()
|
||||
const capabilityInput = z.object({
|
||||
operationId: identifier,
|
||||
toolName: identifier,
|
||||
section: identifier,
|
||||
effect: z.enum(["read", "write", "diagnostic"]).optional(),
|
||||
scope: z.enum(["servers", "global", "connection"]).optional(),
|
||||
serverId: z.number().int().positive().safe().optional(),
|
||||
includeApplicability: z.boolean().optional(),
|
||||
applicable: z.boolean().optional(),
|
||||
}).strict()
|
||||
|
||||
export function readCapabilities(input: z.infer<typeof capabilityInput>, connection: ActionContext["connection"], now = new Date()) {
|
||||
const { policy, owner_permissions: ownerPermissions } = connection
|
||||
const granted = new Set(policy.scope.operationIds)
|
||||
const operations = listMcpOperations().filter(operation =>
|
||||
operation.implementation === "available" && granted.has(operation.id) &&
|
||||
(input.operationId === undefined || operation.id === input.operationId) &&
|
||||
(input.toolName === undefined || operation.toolName === input.toolName) &&
|
||||
(input.section === undefined || operation.section === input.section) &&
|
||||
(input.effect === undefined || operation.effect === input.effect) &&
|
||||
(input.scope === undefined || operation.scope === input.scope) &&
|
||||
(input.serverId === undefined || operation.scope === "servers"))
|
||||
if (!input.includeApplicability && input.serverId === undefined && input.applicable === undefined) return { operations, schemaVersion: 1 }
|
||||
|
||||
const assessed = operations.map(operation => {
|
||||
const serverId = input.serverId ?? policy.scope.serverIds[0]
|
||||
const target: McpPolicyPreviewRequest["target"] | null = operation.scope === "servers"
|
||||
? serverId === undefined ? null : { scope: "servers", serverIds: [serverId] }
|
||||
: { scope: operation.scope }
|
||||
const assessment = target
|
||||
? evaluateMcpPolicy({ operationId: operation.id, policy, ownerPermissions, target, objects: [], protections: [], objectCount: 0,
|
||||
usage: { callsInMinute: 0, concurrentReads: 0, mutationsInHour: 0 }, auditAvailable: true }, now)
|
||||
: { decision: "denied" as const, reasons: [{ code: "SERVER_DENIED", message: "Подключению не выдан доступ к серверам" }] }
|
||||
return { ...operation, applicability: { decision: assessment.decision, reasons: assessment.reasons,
|
||||
serverId: operation.scope === "servers" ? serverId ?? null : null } }
|
||||
})
|
||||
return { operations: assessed.filter(operation => input.applicable === undefined || input.applicable === (operation.applicability.decision !== "denied")),
|
||||
schemaVersion: 1, applicabilityBasis: "effective-policy-before-arguments-and-runtime-checks", observedAt: now.toISOString() }
|
||||
}
|
||||
|
||||
export function registerCapabilityActions(register: typeof add) {
|
||||
register("capabilities.read", "mm_capabilities_get", "Доступные возможности", "mcp", null, "read", "connection", capabilityInput, {
|
||||
read: async (input, context) => readCapabilities(capabilityInput.parse(input), context.connection),
|
||||
})
|
||||
}
|
||||
@@ -9,6 +9,7 @@ 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")
|
||||
const implemented = new Set(listActions().map(action => action.operation.id))
|
||||
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",
|
||||
|
||||
@@ -10,6 +10,8 @@ const leases = createPool(limit, true)
|
||||
leases.on("error", () => console.error("MCP database request lease lost on idle connection"))
|
||||
const apiLeases = createPool(limit, true)
|
||||
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)
|
||||
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 }>()
|
||||
@@ -28,19 +30,24 @@ export function withActiveDatabaseRequest<T>(run: (signal: AbortSignal) => Promi
|
||||
return child
|
||||
}
|
||||
|
||||
export function withMcpDatabaseRequest<T>(run: () => Promise<T>): Promise<T> { return withDatabaseRequest(run, true) }
|
||||
export function withDatabaseApiRequest<T>(run: () => Promise<T>): Promise<T> { return withDatabaseRequest(run, false) }
|
||||
export function withMcpDatabaseRequest<T>(run: () => Promise<T>): Promise<T> { return withDatabaseRequest(run, leases) }
|
||||
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> {
|
||||
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)
|
||||
if (nested) return nested
|
||||
const mcp = pool === leases
|
||||
if (mcp && active >= limit) throw new McpError("RATE_LIMITED", "Лимит одновременно выполняемых запросов MCP", 429)
|
||||
if (mcp) active++
|
||||
try {
|
||||
const client = await (detached ? detachedApiLeases : mcp ? leases : apiLeases).connect()
|
||||
const client = await pool.connect()
|
||||
let destroy = true, acquired = false
|
||||
const lifetime = new AbortController()
|
||||
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. */
|
||||
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)))
|
||||
}
|
||||
@@ -42,11 +42,21 @@ export function registerLegacyFlowAnalyticsAction(register: typeof add) {
|
||||
})
|
||||
}
|
||||
|
||||
const flowTupleSchema = z.object({
|
||||
srcIp: z.union([z.ipv4(), z.ipv6()]).optional().describe("Точный IP источника в экспортированной записи"),
|
||||
dstIp: z.union([z.ipv4(), z.ipv6()]).optional().describe("Точный IP назначения в экспортированной записи"),
|
||||
srcPort: z.number().int().min(0).max(65535).optional(),
|
||||
dstPort: z.number().int().min(0).max(65535).optional(),
|
||||
protocol: z.number().int().min(0).max(255).optional().describe("Номер IP-протокола IANA"),
|
||||
})
|
||||
const REPORT_ROW_LIMIT = 20000
|
||||
|
||||
export function registerFlowAnalyticsActions(register: typeof add) {
|
||||
register("traffic.flow.analytics.read", "mm_netflow_analytics_report_get", "NetFlow: нагрузка, приложения и разговоры выбранного сервера", "traffic", "mm:traffic:read", "read", "servers", z.object({
|
||||
register("traffic.flow.analytics.read", "mm_netflow_analytics_report_get", "NetFlow: нагрузка, приложения и разговоры выбранного сервера по сохранённым top-N данным", "traffic", "mm:traffic:read", "read", "servers", z.object({
|
||||
serverId: z.number().int().positive().safe(), minutes: z.number().int().min(1).max(1440).default(15),
|
||||
userId: z.string().min(1).max(100).optional(),
|
||||
interface: z.string().trim().min(1).max(200).refine(value => !/[\u0000-\u001f\u007f]/.test(value) && value !== "__all__").optional(),
|
||||
...flowTupleSchema.shape,
|
||||
dedup: z.boolean().default(true), excludeMesh: z.boolean().default(true), excludeOverlay: z.boolean().default(true),
|
||||
offset: z.number().int().min(0).max(100000).default(0), limit: z.number().int().min(1).max(100).default(50),
|
||||
}).strict(), {
|
||||
@@ -57,11 +67,15 @@ export function registerFlowAnalyticsActions(register: typeof add) {
|
||||
const authorize = () => assertTrafficHistorySource(context, server)
|
||||
const startedAt = new Date().toISOString()
|
||||
try {
|
||||
const filters = flowTupleSchema.parse(input)
|
||||
const tuple = Object.values(filters).some(value => value !== undefined) ? filters : undefined
|
||||
const requestedMinutes = Number(input.minutes)
|
||||
const limits = await readFlowSourceLimits()
|
||||
await authorize()
|
||||
const { sourceWindow, ...raw } = await readFlowWindow(Number(input.minutes), minutes => buildFlowAnalytics({ serverId: server.id, minutes, userId: input.userId as string | undefined,
|
||||
iface: input.interface as string | undefined, dedup: input.dedup === true, excludeMesh: input.excludeMesh === true, excludeOverlay: input.excludeOverlay === true },
|
||||
{ serverIds: context.connection.policy.scope.serverIds, maxRows: 20000, authorize }), context.signal)
|
||||
const { sourceWindow: reducedWindow, ...raw } = await readFlowWindow(requestedMinutes, minutes => buildFlowAnalytics({ serverId: server.id, minutes, userId: input.userId as string | undefined,
|
||||
iface: input.interface as string | undefined, tuple, dedup: input.dedup === true, excludeMesh: input.excludeMesh === true, excludeOverlay: input.excludeOverlay === true },
|
||||
{ serverIds: context.connection.policy.scope.serverIds, maxRows: REPORT_ROW_LIMIT, authorize }), context.signal)
|
||||
const sourceWindow = { requestedMinutes, effectiveMinutes: reducedWindow?.effectiveMinutes ?? requestedMinutes, incomplete: reducedWindow !== undefined }
|
||||
const result = flowAnalyticsDtoSchema.parse(raw)
|
||||
const offset = Number(input.offset), limit = Number(input.limit), pages: Record<string, { total: number; nextOffset: number | null }> = {}
|
||||
const analytics: Record<string, unknown> = { ...result }
|
||||
@@ -74,14 +88,16 @@ export function registerFlowAnalyticsActions(register: typeof add) {
|
||||
await authorize()
|
||||
if ((await readFlowSourceLimits()).topN !== limits.topN) throw new McpError("STATE_CONFLICT", "Предел источника NetFlow изменился во время чтения", 409)
|
||||
await authorize()
|
||||
const output = { serverId: server.id, minutes: sourceWindow?.effectiveMinutes ?? Number(input.minutes), sourceWindow, interface: input.interface ?? null, userId: input.userId ?? null,
|
||||
const output = { serverId: server.id, minutes: sourceWindow.effectiveMinutes, sourceWindow, interface: input.interface ?? null, userId: input.userId ?? null, filters,
|
||||
analytics: retained, pages, contextRates: { bpsNowEstimate: _bpsNow, bpsWireEstimate: _bpsWire, bpsOverlayEstimate: _bpsOverlay, bytesWireEstimate: _bytesWire,
|
||||
listenerBound: _live, userAttributionVerified: false, semantics: "REST estimates: filtered or overlay-inclusive rates use the latest complete retained minute with a window-average fallback; wire uses current interface snapshots" },
|
||||
listenerBound: _live, userAttributionVerified: false, semantics: "REST estimates: filtered or overlay-inclusive rates use the latest complete retained minute with a window-average fallback; wire uses unfiltered current interface snapshots" },
|
||||
readStartedAt: startedAt, observedAt: new Date().toISOString(), live: false,
|
||||
source: "retained flow_buckets plus pending; same REST analytics engine with scoped topology",
|
||||
rowLimit: 20000, topRowsPerBucketLimit: Math.max(20, limits.topN), engineTopListLimit: Math.min(50, Math.max(10, limits.topN)),
|
||||
rowLimit: REPORT_ROW_LIMIT, topRowsPerBucketLimit: Math.max(20, limits.topN), engineTopListLimit: Math.min(50, Math.max(10, limits.topN)),
|
||||
historicalDetail: { filtersAppliedTo: "retained rows before aggregation and pagination", rowLimitAppliedBeforeFilters: true,
|
||||
discardedRowsRecoverable: false, exactTupleTotalsVerified: false },
|
||||
incomplete: true, coverageVerified: false, rowSumIsNetworkTotal: false, forwardingVerified: false,
|
||||
inferredPathsVerified: false, historicalOwnershipVerified: false, attribution: "current named whole-interface bindings; users with hidden bindings excluded",
|
||||
inferredPathsVerified: false, historicalOwnershipVerified: false, attribution: "current exclusive interface bindings, including confirmed single-peer WireGuard; users with hidden bindings excluded",
|
||||
backgroundEnrichmentStarted: false, collectorStarted: false }
|
||||
if (Buffer.byteLength(JSON.stringify(output)) > 1048576) throw new McpError("STATE_UNAVAILABLE", "Ответ аналитики превышает 1 МиБ; уменьшите страницу", 409)
|
||||
return withCurrentFlowReadQuality(output,context)
|
||||
|
||||
@@ -72,7 +72,7 @@ export function registerFlowCatalogActions(register: typeof add) {
|
||||
for (const server of selected) await assertTrafficHistorySource(context, server)
|
||||
return withCurrentFlowReadQuality({ ...page, clients, total: data.total, nextOffset: offset + clients.length < data.total ? offset + clients.length : null,
|
||||
incomplete: !!data.sourceWindow || page.incomplete || clients.length < data.total || clients.some(row => !row.completeSourceSet || !row.completeAttribution),
|
||||
source: "retained ingress rows and current named whole-interface bindings", topRowsPerBucketLimit: data.window.topRowsPerBucketLimit,
|
||||
source: "retained ingress rows and current exclusive interface bindings, including confirmed single-peer WireGuard", topRowsPerBucketLimit: data.window.topRowsPerBucketLimit,
|
||||
from: data.window.since, to: data.window.until, sourceWindow: data.sourceWindow, ...sourceSemantics },context)
|
||||
},
|
||||
})
|
||||
|
||||
@@ -59,7 +59,7 @@ export function registerFlowLiveActions(register: typeof add) {
|
||||
historicalOwnershipVerified: false, currentTrafficVerified: false,
|
||||
rateSemantics: "REST live rates: filtered or overlay-inclusive rates use the latest complete retained minute with a window-average fallback",
|
||||
liveMeaning: "events[].data.live means listener bound; it does not prove exporter freshness or forwarding",
|
||||
attribution: "current named whole-interface bindings; users with hidden bindings excluded",
|
||||
attribution: "current exclusive interface bindings, including confirmed single-peer WireGuard; users with hidden bindings excluded",
|
||||
collectorStarted: false, backgroundEnrichmentStarted: false }
|
||||
if (Buffer.byteLength(JSON.stringify(output)) > 1048576) throw new McpError("STATE_UNAVAILABLE", "Ответ live превышает 1 МиБ; уменьшите страницу или число samples", 409)
|
||||
await authorize()
|
||||
|
||||
@@ -49,11 +49,11 @@ export function registerFlowMapActions(register: typeof add) {
|
||||
await authorize()
|
||||
const output = { serverId: server.id, userId: input.userId ?? null, interface: input.interface ?? null, map: projected, pages, sourceWindow,
|
||||
readStartedAt: startedAt, observedAt: new Date().toISOString(), live: false, listenerBound,
|
||||
source: "retained flow_buckets plus pending; same REST map engine with scoped topology",
|
||||
source: "closed minutes for all rates; retained flows for services and user breakdowns; paths use an exit exporter or observed GRE peer/next hop, otherwise identify the observing exporter; interfaceTraffic includes private routed traffic before top-N",
|
||||
topRowsPerBucketLimit: Math.max(20, limits.topN), rowLimit: 20000, incomplete: true, graphComplete: false,
|
||||
referencedNodesMayBeOutsidePage: true, inferredPathsVerified: false, forwardingVerified: false, coverageVerified: false,
|
||||
rowSumIsNetworkTotal: false, historicalOwnershipVerified: false,
|
||||
attribution: "current named whole-interface bindings; users with hidden bindings excluded",
|
||||
attribution: "current exclusive interface bindings, including confirmed single-peer WireGuard; users with hidden bindings excluded",
|
||||
collectorStarted: false, backgroundEnrichmentStarted: false, tracerouteExecuted: false }
|
||||
if (Buffer.byteLength(JSON.stringify(output)) > 1048576) throw new McpError("STATE_UNAVAILABLE", "Ответ карты превышает 1 МиБ; уменьшите страницы", 409)
|
||||
return withCurrentFlowReadQuality(output,context)
|
||||
|
||||
@@ -0,0 +1,208 @@
|
||||
import assert from "node:assert/strict"
|
||||
import { mkdtemp, rm } from "node:fs/promises"
|
||||
import { tmpdir } from "node:os"
|
||||
import { join } from "node:path"
|
||||
import { after, mock, test } from "node:test"
|
||||
import { mcpConnectionPolicySchema, mcpOperationDescriptorSchema } from "@mmapp/contracts/mcp"
|
||||
import type { ActionContext } from "./action-types.js"
|
||||
import type { add } from "./actions.js"
|
||||
import { registerMcpOperation } from "./registry.js"
|
||||
|
||||
const queries: Array<{ sql: string; values: unknown[] }> = []
|
||||
const from = "2026-11-27T00:00:00Z"
|
||||
const to = "2026-11-27T01:00:00Z"
|
||||
const observed = new Date("2026-11-27T00:15:00Z")
|
||||
const newer = new Date("2026-11-27T00:30:00Z")
|
||||
const observedPrecise = "2026-11-27T00:15:00.000000Z", newerPrecise = "2026-11-27T00:30:00.000002Z"
|
||||
const fixtures = await mkdtemp(join(tmpdir(), "mcp-incident-test-"))
|
||||
process.env.MCP_STATE_DIR = fixtures
|
||||
after(() => rm(fixtures, { recursive: true, force: true }))
|
||||
let paginate = false
|
||||
mock.module("../../db/index.js", { namedExports: { pool: { async query(sql: string, values: unknown[]) {
|
||||
queries.push({ sql, values })
|
||||
if (sql === "SELECT enabled FROM servers WHERE id=$1") return { rows: [{ enabled: true }] }
|
||||
if (sql.startsWith("SELECT id,enabled FROM servers")) {
|
||||
assert.match(sql, /id=ANY\(\$1::bigint\[\]\) AND id>\$2/)
|
||||
assert.deepEqual(values[0], [7, 9])
|
||||
return { rows: values[1] === 0 ? [{ id: 7, enabled: true }, { id: 9, enabled: false }] : [{ id: 9, enabled: false }] }
|
||||
}
|
||||
if (sql.includes("FROM mcp_requests")) {
|
||||
assert.match(sql, /server_ids=ARRAY\[\$1\]::bigint\[\]/)
|
||||
assert.match(sql, /connection_id=\$5 AND actor_id=\$6 AND tool=ANY\(\$7::text\[\]\)/)
|
||||
assert.deepEqual(values, [7, from, to, 51, "fixture-connection", "fixture-owner", ["mm_fixture_server"]])
|
||||
return { rows: [{ at: newerPrecise, key: "request-id", id: "request-id", status: "completed", timestampKind: "request-created", toolName: "mm_fixture_server" }] }
|
||||
}
|
||||
assert.match(sql, /server_id=\$1/)
|
||||
assert.ok(values[0] === 7 || values[0] === 9)
|
||||
if (sql.includes("servers_rest_ping_samples")) {
|
||||
if (values.length === 3) return { rows: [{ enabled: true, intervalSec: 60, observedAt: null, status: null }] }
|
||||
return { rows: [{ at: observedPrecise, key: "", id: "poll", status: "ok", timestampKind: "backend-sample" }] }
|
||||
}
|
||||
if (sql.includes("router_log_entries")) {
|
||||
const make = (at: string, id: string) => ({ at, id, key: id.padStart(20, "0"), status: "warning", timestampKind: "router", receivedAt: newer })
|
||||
if (!paginate) return { rows: [make(newerPrecise, "41")] }
|
||||
const rows = [make(newerPrecise, "100"), make(newerPrecise, "9"), make("2026-11-27T00:30:00.000001Z", "99")]
|
||||
if (values.length === 4) return { rows: rows.slice(0, Number(values[3])) }
|
||||
assert.match(sql, /\(effective_at,\(lpad\(id::text,20,'0'\)\) COLLATE "C"\) < \(\$5::timestamptz,\$6::text COLLATE "C"\)/)
|
||||
assert.equal(values[4], newerPrecise)
|
||||
return { rows: rows.filter(row => row.at < String(values[4]) || row.at === values[4] && row.key < String(values[5])).slice(0, Number(values[3])) }
|
||||
}
|
||||
if (sql.includes("router_log_collection_state")) throw Error("Sample source unavailable")
|
||||
if (sql.includes("uptime_probe_samples")) {
|
||||
assert.match(sql, /p\.src_server_id=\$1/)
|
||||
assert.match(sql, /sampled_at>=p\.updated_at/)
|
||||
assert.doesNotMatch(sql, /\bp\.(target|name|src_interface)\b/)
|
||||
if (values.length === 3) return { rows: [{ enabled: true, intervalSec: 60, observedAt: observed, status: "warn" }] }
|
||||
return { rows: [{ at: observedPrecise, key: "probe-1", id: "probe-1", status: "warn",
|
||||
timestampKind: "backend-sample", rttMs: 50, lossPct: 25 }] }
|
||||
}
|
||||
if (sql.includes("uptime_resource_samples")) return { rows: [] }
|
||||
throw Error("Unexpected source")
|
||||
} } } })
|
||||
|
||||
const { registerIncidentActions, telemetryFreshness } = await import("./incident-actions.js")
|
||||
const { readCapabilities } = await import("./capability-actions.js")
|
||||
const registered = new Map<string, Parameters<typeof add>>()
|
||||
registerIncidentActions((...args) => registered.set(args[1], args))
|
||||
const connection = {
|
||||
policy: mcpConnectionPolicySchema.parse({
|
||||
id: "fixture", version: 1, status: "active", expiresAt: "2027-01-01T00:00:00Z", mode: "observer",
|
||||
permissions: ["mm:servers:read", "mm:traffic:read"],
|
||||
scope: { serverIds: [7], operationIds: ["catalog.global.read", "catalog.server.read", "catalog.server.write"] },
|
||||
}), owner_permissions: ["mm:servers:read", "mm:uptime:read"],
|
||||
} as ActionContext["connection"]
|
||||
const context = { connection } as ActionContext
|
||||
|
||||
test("timeline limits interval and evidence, keeps order and timestamps, checks both source permission grants", async () => {
|
||||
const registration = registered.get("mm_incident_timeline_get")!
|
||||
const schema = registration[7], read = registration[8].read!
|
||||
const input = { serverId: 7, from, to, limit: 1 }
|
||||
assert.equal(schema.safeParse({ ...input, to: from }).success, false)
|
||||
assert.equal(schema.safeParse({ ...input, to: "2026-11-29T00:00:00Z" }).success, false)
|
||||
assert.equal(schema.safeParse({ ...input, to: "2026-11-27T01:00:00" }).success, false)
|
||||
for (const source of ["uptime", "netflow"]) {
|
||||
await assert.rejects(read(schema.parse({ ...input, sources: [source] }), context),
|
||||
{ code: "PERMISSION_DENIED" })
|
||||
}
|
||||
assert.equal(queries.length, 0)
|
||||
const result = await read(schema.parse(input), context)
|
||||
assert.deepEqual(result, {
|
||||
serverId: 7, from: new Date(from).toISOString(), to: new Date(to).toISOString(),
|
||||
observedAt: (result as { observedAt: string }).observedAt,
|
||||
order: "newest-first", sources: ["routeros-poll", "logs"],
|
||||
items: [{ id: "41", status: "warning", timestampKind: "router", source: "logs", at: newerPrecise, receivedAt: newer.toISOString() }],
|
||||
nextCursor: (result as { nextCursor: string }).nextCursor,
|
||||
truncated: true, coverageVerified: false, managerEventsIncluded: false,
|
||||
})
|
||||
assert.deepEqual(queries.map(query => query.values), [[7], [7, from, to, 2], [7, from, to, 2]])
|
||||
})
|
||||
|
||||
test("health separates disabled, absent, stale and unknown freshness from observed status", async () => {
|
||||
const row = { enabled: true, intervalSec: 30, observedAt: observed, status: "error" }
|
||||
assert.equal(telemetryFreshness(row, observed.getTime() + 90_000, true).freshness, "fresh")
|
||||
assert.equal(telemetryFreshness(row, observed.getTime() + 90_001, true).freshness, "stale")
|
||||
assert.equal(telemetryFreshness(row, observed.getTime(), false).freshness, "disabled")
|
||||
assert.equal(telemetryFreshness({ ...row, intervalSec: null }, observed.getTime(), true).freshness, "unknown")
|
||||
const registration = registered.get("mm_telemetry_health_get")!
|
||||
const result = await registration[8].read!(registration[7].parse({ serverId: 7, sources: ["routeros-poll", "logs"] }), context)
|
||||
assert.deepEqual((result as { observations: unknown[] }).observations, [{
|
||||
source: "routeros-poll", freshness: "unobserved", observedAt: null, ageMs: null,
|
||||
lastStatus: null,
|
||||
}, {
|
||||
source: "logs", freshness: "unavailable", observedAt: null, ageMs: null,
|
||||
lastStatus: null,
|
||||
}])
|
||||
})
|
||||
|
||||
test("capabilities keeps legacy shape and assesses filtered candidates under effective policy", () => {
|
||||
for (const [id, toolName, scope, effect, requiredPermissions] of [
|
||||
["catalog.global.read", "mm_fixture_global", "global", "read", []],
|
||||
["catalog.server.read", "mm_fixture_server", "servers", "read", ["mm:servers:read"]],
|
||||
["catalog.server.write", "mm_fixture_server_plan", "servers", "write", ["mm:traffic:read"]],
|
||||
["catalog.hidden.read", "mm_fixture_hidden", "global", "read", []],
|
||||
]) registerMcpOperation(mcpOperationDescriptorSchema.parse({ id, toolName, scope, effect, requiredPermissions, version: 1,
|
||||
title: "Fixture", section: "fixture", risk: "ordinary", implementation: "available",
|
||||
annotations: { readOnlyHint: effect === "read", destructiveHint: effect === "write", idempotentHint: true, openWorldHint: true } }))
|
||||
const baseline = readCapabilities({}, connection, observed)
|
||||
assert.deepEqual(Object.keys(baseline).sort(), ["operations", "schemaVersion"])
|
||||
assert.equal(baseline.operations.length, 3)
|
||||
assert.ok(baseline.operations.every(operation => !("applicability" in operation)))
|
||||
const applicability = (input: Parameters<typeof readCapabilities>[0]) => readCapabilities({ includeApplicability: true, ...input }, connection, observed)
|
||||
.operations.flatMap(operation => "applicability" in operation ? [operation.applicability] : [])
|
||||
assert.equal(applicability({ toolName: "mm_fixture_global" })[0]?.reasons[0]?.code, "GLOBAL_DENIED")
|
||||
assert.equal(applicability({ serverId: 7, effect: "read" })[0]?.decision, "allowed")
|
||||
assert.equal(applicability({ serverId: 8, effect: "read" })[0]?.reasons[0]?.code, "SERVER_DENIED")
|
||||
assert.deepEqual(applicability({ effect: "write" })[0]?.reasons.map(reason => reason.code), ["OWNER_PERMISSION_MISSING", "OBSERVER_WRITE_DENIED"])
|
||||
assert.equal(applicability({ section: "fixture", applicable: true }).length, 1)
|
||||
})
|
||||
|
||||
test("optional manager evidence requires both audit grants and selects current single-server tool metadata", async () => {
|
||||
const registration = registered.get("mm_incident_timeline_get")!
|
||||
const raw = registration[7].parse({ serverId: 7, from, to, sources: ["routeros-poll"], includeManagerEvents: true })
|
||||
const read = registration[8].read!
|
||||
const before = queries.length
|
||||
const audit = {
|
||||
...connection, id: "fixture-connection", owner_id: "fixture-owner",
|
||||
policy: { ...connection.policy, permissions: [...connection.policy.permissions, "mm:mcp:read"] },
|
||||
}
|
||||
await assert.rejects(read(raw, { ...context, connection: audit }), { code: "PERMISSION_DENIED" })
|
||||
assert.equal(queries.length, before)
|
||||
audit.owner_permissions = [...audit.owner_permissions, "mm:mcp:read"]
|
||||
const result = await read(raw, { ...context, connection: audit })
|
||||
assert.deepEqual((result as { sources: string[] }).sources, ["routeros-poll", "mcp-request"])
|
||||
assert.deepEqual((result as { items: unknown[] }).items[0], {
|
||||
id: "request-id", status: "completed", timestampKind: "request-created", toolName: "mm_fixture_server",
|
||||
source: "mcp-request", at: newerPrecise,
|
||||
})
|
||||
})
|
||||
|
||||
test("timeline paginates equal timestamps and microseconds with a bound opaque cursor", async () => {
|
||||
const registration = registered.get("mm_incident_timeline_get")!
|
||||
const base = { serverId: 7, from, to, sources: ["logs"], limit: 1 }
|
||||
const read = async (raw: typeof base & { cursor?: string }) => await registration[8].read!(registration[7].parse(raw), context) as {
|
||||
nextCursor: string | null; items: Array<{ id: string; at: string }>
|
||||
}
|
||||
paginate = true
|
||||
try {
|
||||
const one = await read(base)
|
||||
assert.ok(one.nextCursor)
|
||||
const two = await read({ ...base, cursor: one.nextCursor })
|
||||
assert.ok(two.nextCursor)
|
||||
const three = await read({ ...base, cursor: two.nextCursor })
|
||||
assert.equal(three.nextCursor, null)
|
||||
assert.deepEqual([one, two, three].flatMap(page => page.items.map(({ id, at }) => [id, at])), [
|
||||
["100", newerPrecise], ["9", newerPrecise], ["99", "2026-11-27T00:30:00.000001Z"],
|
||||
])
|
||||
await assert.rejects(read({ ...base, serverId: 9, cursor: one.nextCursor }), { code: "RESET_REQUIRED" })
|
||||
await assert.rejects(read({ ...base, cursor: "bogus" }), { code: "RESET_REQUIRED" })
|
||||
} finally { paginate = false }
|
||||
})
|
||||
|
||||
test("fleet health pages over the effective server allowlist only", async () => {
|
||||
const registration = registered.get("mm_telemetry_health_get")!
|
||||
const scoped = { ...context, connection: { ...connection, policy: { ...connection.policy,
|
||||
scope: { ...connection.policy.scope, serverIds: [7, 9] } } } }
|
||||
const raw = { sources: ["routeros-poll"], limit: 1 }
|
||||
const read = async (input: typeof raw & { afterServerId?: number }) => await registration[8].read!(registration[7].parse(input), scoped) as {
|
||||
nextAfterServerId: number | null; items: Array<{ serverId: number }>
|
||||
}
|
||||
assert.deepEqual(registration[8].target!(raw, scoped), { scope: "servers", serverIds: [7, 9] })
|
||||
const one = await read(raw), two = await read({ ...raw, afterServerId: 7 })
|
||||
assert.deepEqual([one.nextAfterServerId, two.nextAfterServerId], [7, null])
|
||||
assert.deepEqual([one, two].flatMap(page => page.items.map(item => item.serverId)), [7, 9])
|
||||
})
|
||||
|
||||
test("uptime combines scoped resource and retained probe evidence without target details", async () => {
|
||||
const scoped = { ...context, connection: { ...connection, policy: { ...connection.policy,
|
||||
permissions: [...connection.policy.permissions, "mm:uptime:read"] } } }
|
||||
const health = registered.get("mm_telemetry_health_get")!
|
||||
const sources = ["uptime"]
|
||||
const state = await health[8].read!(health[7].parse({ serverId: 7, sources }), scoped) as {
|
||||
observations: Array<{ source: string; lastStatus: string | null }>
|
||||
}
|
||||
assert.deepEqual(state.observations.map(row => [row.source, row.lastStatus]), [["uptime", null], ["uptime-probe", "warn"]])
|
||||
const timeline = registered.get("mm_incident_timeline_get")!
|
||||
const evidence = await timeline[8].read!(timeline[7].parse({ serverId: 7, from, to, sources }), scoped) as { items: unknown[] }
|
||||
assert.deepEqual(evidence.items, [{ at: observedPrecise, id: "probe-1", status: "warn", source: "uptime-probe",
|
||||
timestampKind: "backend-sample", rttMs: 50, lossPct: 25 }])
|
||||
})
|
||||
@@ -0,0 +1,213 @@
|
||||
import { z } from "zod"
|
||||
import { pool } from "../../db/index.js"
|
||||
import { hasPermission } from "../../lib/permissions.js"
|
||||
import { listMcpOperations } from "./registry.js"
|
||||
import { accessGeneration, decryptSecret, encryptSecret, fingerprint, McpError } from "./security.js"
|
||||
import type { ActionContext } from "./action-types.js"
|
||||
import type { add } from "./actions.js"
|
||||
|
||||
const sources = ["routeros-poll", "uptime", "logs", "netflow"] as const
|
||||
type Source = typeof sources[number]
|
||||
const permissions: Record<Source, string> = {
|
||||
"routeros-poll": "mm:servers:read", uptime: "mm:uptime:read", logs: "mm:servers:read", netflow: "mm:traffic:read",
|
||||
}
|
||||
const selection = {
|
||||
serverId: z.number().int().positive().safe(),
|
||||
sources: z.array(z.enum(sources)).min(1).max(sources.length).optional(),
|
||||
}
|
||||
const healthInput = z.object({ ...selection, serverId: selection.serverId.optional(),
|
||||
afterServerId: selection.serverId.optional(), limit: z.number().int().min(1).max(20).default(10),
|
||||
}).strict().refine(input => input.serverId === undefined || input.afterServerId === undefined, "Курсор доступен для списка серверов")
|
||||
const hourMs = 3_600_000
|
||||
const timelineSourceNames = [...sources, "uptime-probe", "mcp-request"] as const
|
||||
type TimelineSource = typeof timelineSourceNames[number]
|
||||
const cursorSchema = z.object({ scope: z.string(), at: z.iso.datetime({ precision: 6 }),
|
||||
source: z.enum(timelineSourceNames), key: z.string().max(1000),
|
||||
}).strict()
|
||||
const timelineInput = z.object({
|
||||
...selection, from: z.iso.datetime({ offset: true }), to: z.iso.datetime({ offset: true }),
|
||||
limit: z.number().int().min(1).max(200).default(50),
|
||||
includeManagerEvents: z.boolean().default(false),
|
||||
cursor: z.string().min(1).max(3000).optional(),
|
||||
}).strict().refine(({ from, to }) => {
|
||||
const duration = Date.parse(to) - Date.parse(from)
|
||||
return duration > 0 && duration <= 24 * hourMs
|
||||
}, "Требуется положительное окно до 24 часов")
|
||||
|
||||
function permittedSources(context: ActionContext, requested?: Source[]) {
|
||||
const permitted = (source: Source) => [context.connection.policy.permissions, context.connection.owner_permissions]
|
||||
.every(granted => hasPermission(granted, permissions[source]))
|
||||
if (requested?.some(source => !permitted(source))) throw new McpError("PERMISSION_DENIED", "Чтение выбранного источника запрещено", 403)
|
||||
return [...new Set(requested ?? sources.filter(permitted))]
|
||||
}
|
||||
|
||||
type HealthRow = { enabled: boolean | null; intervalSec: number | null; observedAt: Date | null; status: string | null; gapAt?: Date | null }
|
||||
type EvidenceRow = { at: string; key: string; id: string; status: string | null; timestampKind: string; receivedAt?: Date; topics?: string[]; message?: string; toolName?: string }
|
||||
const healthSources: Record<Source, string> = {
|
||||
"routeros-poll": `SELECT cfg.enabled,cfg.interval_sec AS "intervalSec",sample.sampled_at AS "observedAt",
|
||||
CASE sample.ok WHEN true THEN 'ok' WHEN false THEN 'error' END AS status
|
||||
FROM servers_api_ping_settings cfg LEFT JOIN LATERAL (
|
||||
SELECT sampled_at,ok FROM servers_rest_ping_samples WHERE server_id=$1 AND sampled_at BETWEEN $2 AND $3
|
||||
ORDER BY sampled_at DESC LIMIT 1
|
||||
) sample ON true WHERE cfg.id=1`,
|
||||
uptime: `SELECT cfg.enabled AND cfg.resources_enabled AS enabled,cfg.interval_sec AS "intervalSec",
|
||||
sample.sampled_at AS "observedAt",sample.status
|
||||
FROM uptime_settings cfg LEFT JOIN LATERAL (
|
||||
SELECT sampled_at,status FROM uptime_resource_samples WHERE server_id=$1 AND sampled_at BETWEEN $2 AND $3
|
||||
ORDER BY sampled_at DESC LIMIT 1
|
||||
) sample ON true WHERE cfg.id=1`,
|
||||
logs: `SELECT cfg.enabled,cfg.interval_sec AS "intervalSec",
|
||||
CASE WHEN sample.last_collected_at BETWEEN $2 AND $3 THEN sample.last_collected_at END AS "observedAt",
|
||||
CASE WHEN sample.gap_at BETWEEN $2 AND $3 THEN sample.gap_at END AS "gapAt",
|
||||
CASE WHEN sample.last_error IS NOT NULL AND sample.last_error <> '' THEN 'error'
|
||||
WHEN sample.last_collected_at BETWEEN $2 AND $3 THEN 'ok' END AS status
|
||||
FROM router_log_settings cfg LEFT JOIN router_log_collection_state sample ON sample.server_id=$1 WHERE cfg.id=1`,
|
||||
netflow: `SELECT NULL::boolean AS enabled,NULL::integer AS "intervalSec",bucket_at AS "observedAt",'retained-bucket' AS status
|
||||
FROM flow_minute_stats WHERE server_id=$1 AND bucket_at BETWEEN $2 AND $3
|
||||
ORDER BY bucket_at DESC LIMIT 1`,
|
||||
}
|
||||
const uptimeProbeHealth = `SELECT cfg.enabled AND cfg.ping_enabled AS enabled,
|
||||
COALESCE(NULLIF(sample.interval_sec,0),cfg.probe_interval_sec) AS "intervalSec",
|
||||
sample.sampled_at AS "observedAt",sample.status
|
||||
FROM uptime_settings cfg LEFT JOIN LATERAL (
|
||||
SELECT p.interval_sec,s.sampled_at,s.status FROM uptime_probes p CROSS JOIN LATERAL (
|
||||
SELECT sampled_at,status FROM uptime_probe_samples WHERE probe_id=p.id AND sampled_at BETWEEN $2 AND $3 AND sampled_at>=p.updated_at
|
||||
ORDER BY sampled_at DESC LIMIT 1
|
||||
) s WHERE p.src_server_id=$1 AND p.enabled ORDER BY s.sampled_at DESC,p.id LIMIT 1
|
||||
) sample ON true WHERE cfg.id=1`
|
||||
const timelineSources: Record<TimelineSource, { time: string; key: string; evidence: string }> = {
|
||||
"routeros-poll": { time: "sampled_at", key: "''::text", evidence: `sampled_at::text AS id,CASE ok WHEN true THEN 'ok' ELSE 'error' END AS status,
|
||||
'backend-sample' AS "timestampKind" FROM servers_rest_ping_samples WHERE server_id=$1` },
|
||||
uptime: { time: "sampled_at", key: "''::text", evidence: `sampled_at::text AS id,status,'backend-sample' AS "timestampKind"
|
||||
FROM uptime_resource_samples WHERE server_id=$1` },
|
||||
"uptime-probe": { time: "s.sampled_at", key: "p.id", evidence: `p.id,status,'backend-sample' AS "timestampKind",
|
||||
s.rtt_ms AS "rttMs",s.loss_pct AS "lossPct" FROM uptime_probes p
|
||||
JOIN uptime_probe_samples s ON s.probe_id=p.id WHERE p.src_server_id=$1 AND s.sampled_at>=p.updated_at` },
|
||||
logs: { time: "effective_at", key: "lpad(id::text,20,'0')", evidence: `id::text,level AS status,
|
||||
CASE WHEN event_at IS NULL THEN 'receipt' ELSE 'router' END AS "timestampKind",
|
||||
received_at AS "receivedAt",topics[1:20] AS topics,left(message,500) AS message FROM router_log_entries WHERE server_id=$1` },
|
||||
netflow: { time: "bucket_at", key: "''::text", evidence: `bucket_at::text AS id,'retained-bucket' AS status,'bucket' AS "timestampKind"
|
||||
FROM flow_minute_stats WHERE server_id=$1` },
|
||||
"mcp-request": { time: "created_at", key: "id::text", evidence: `id::text,CASE WHEN finished_at <= $3 THEN status END AS status,
|
||||
'request-created' AS "timestampKind",tool AS "toolName" FROM mcp_requests WHERE server_ids=ARRAY[$1]::bigint[]
|
||||
AND connection_id=$5 AND actor_id=$6 AND tool=ANY($7::text[])` },
|
||||
}
|
||||
|
||||
function timelineQuery(source: TimelineSource, parameters: unknown[], cursor?: z.infer<typeof cursorSchema>) {
|
||||
const { time, key, evidence } = timelineSources[source]
|
||||
const tie = `(${key}) COLLATE "C"`
|
||||
let clause = ""
|
||||
if (cursor) {
|
||||
const mark = `$${parameters.push(cursor.at)}::timestamptz`
|
||||
if (source === cursor.source) clause = `AND (${time},${tie}) < (${mark},$${parameters.push(cursor.key)}::text COLLATE "C")`
|
||||
else clause = `AND ${time} ${source > cursor.source ? "<=" : "<"} ${mark}`
|
||||
}
|
||||
return `SELECT to_char(${time} AT TIME ZONE 'UTC','YYYY-MM-DD"T"HH24:MI:SS.US"Z"') AS at,
|
||||
${key} AS key,${evidence} AND ${time} BETWEEN $2 AND $3 ${clause}
|
||||
ORDER BY ${time} DESC,${tie} DESC LIMIT $4`
|
||||
}
|
||||
|
||||
function managerEventTools(context: ActionContext) {
|
||||
const { policy, owner_permissions } = context.connection
|
||||
const hasBoth = (permission: string) => hasPermission(policy.permissions, permission) && hasPermission(owner_permissions, permission)
|
||||
if (!hasBoth("mm:mcp:read")) throw new McpError("PERMISSION_DENIED", "Чтение аудита MCP запрещено", 403)
|
||||
const allowed = new Set(policy.scope.operationIds)
|
||||
return listMcpOperations().filter(operation => operation.implementation === "available" && operation.scope === "servers" &&
|
||||
allowed.has(operation.id) && operation.requiredPermissions.every(hasBoth)).map(operation => operation.toolName)
|
||||
}
|
||||
|
||||
async function requireServer(serverId: number) {
|
||||
const { rows } = await pool.query<{ enabled: boolean }>("SELECT enabled FROM servers WHERE id=$1", [serverId])
|
||||
if (!rows.length) throw new McpError("NOT_FOUND", "Сервер не найден", 404)
|
||||
return rows[0].enabled
|
||||
}
|
||||
|
||||
export function telemetryFreshness(row: HealthRow | undefined, asOf: number, serverEnabled: boolean) {
|
||||
const ageMs = row?.observedAt ? asOf - row.observedAt.getTime() : null
|
||||
const staleAfterMs = row?.intervalSec ? row.intervalSec * 3000 : null
|
||||
const freshness = !serverEnabled || row?.enabled === false ? "disabled"
|
||||
: ageMs === null ? "unobserved" : staleAfterMs === null ? "unknown" : ageMs > staleAfterMs ? "stale" : "fresh"
|
||||
return { freshness, observedAt: row?.observedAt?.toISOString() ?? null, ageMs, lastStatus: row?.status ?? null,
|
||||
...(row?.gapAt && { gapAt: row.gapAt.toISOString() }) }
|
||||
}
|
||||
|
||||
export function registerIncidentActions(register: typeof add) {
|
||||
register("telemetry.health.read", "mm_telemetry_health_get", "Здоровье источников телеметрии сервера", "logs",
|
||||
"mm:servers:read", "read", "servers", healthInput, {
|
||||
target: (raw, context) => {
|
||||
const serverIds = typeof raw.serverId === "number" ? [raw.serverId] : context.connection.policy.scope.serverIds
|
||||
if (!serverIds.length) throw new McpError("SERVER_DENIED", "Подключению не выдан доступ к серверам", 403)
|
||||
return { scope: "servers", serverIds }
|
||||
},
|
||||
read: async (raw, context) => {
|
||||
const input = healthInput.parse(raw), selected = permittedSources(context, input.sources)
|
||||
const asOf = Date.now(), from = new Date(asOf - 24 * hourMs), to = new Date(asOf)
|
||||
const healthQueries = selected.map(source => ({ source: source as Source | "uptime-probe", sql: healthSources[source] }))
|
||||
if (selected.includes("uptime")) healthQueries.push({ source: "uptime-probe", sql: uptimeProbeHealth })
|
||||
const readServer = async (serverId: number, serverEnabled: boolean) => ({
|
||||
serverId, serverEnabled, observations: await Promise.all(healthQueries.map(async ({ source, sql }) => {
|
||||
const expectsActiveServer = source === "netflow" || serverEnabled
|
||||
try {
|
||||
const { rows } = await pool.query<HealthRow>(sql, [serverId, from, to])
|
||||
return { source, ...telemetryFreshness(rows[0], asOf, expectsActiveServer) }
|
||||
} catch {
|
||||
context.signal?.throwIfAborted()
|
||||
return { source, ...telemetryFreshness(undefined, asOf, expectsActiveServer), freshness: "unavailable" as const }
|
||||
}
|
||||
})),
|
||||
})
|
||||
const metadata = { observedAt: to.toISOString(), lookbackFrom: from.toISOString(),
|
||||
sourceOmissions: sources.filter(source => !selected.includes(source)).map(source => ({
|
||||
source, reason: input.sources ? "not-requested" : "permission-denied",
|
||||
})),
|
||||
netflowDataQuality: { available: false, reason: "no-server-scoped-collector-quality", exportCoverage: "unverified" } }
|
||||
if (input.serverId !== undefined) return { ...await readServer(input.serverId, await requireServer(input.serverId)), ...metadata }
|
||||
const { rows } = await pool.query<{ id: number; enabled: boolean }>(
|
||||
"SELECT id,enabled FROM servers WHERE id=ANY($1::bigint[]) AND id>$2 ORDER BY id LIMIT $3",
|
||||
[context.connection.policy.scope.serverIds, input.afterServerId ?? 0, input.limit + 1])
|
||||
const page = rows.slice(0, input.limit)
|
||||
const items = await Promise.all(page.map(row => readServer(Number(row.id), row.enabled)))
|
||||
return { ...metadata, items, nextAfterServerId: rows.length > input.limit ? Number(page.at(-1)?.id) : null }
|
||||
},
|
||||
})
|
||||
register("incident.timeline.read", "mm_incident_timeline_get", "Хронология наблюдений по серверу", "logs",
|
||||
"mm:servers:read", "read", "servers", timelineInput, {
|
||||
read: async (raw, context) => {
|
||||
const input = timelineInput.parse(raw), selected = permittedSources(context, input.sources)
|
||||
const managerTools = input.includeManagerEvents ? managerEventTools(context) : null
|
||||
const { cursor: token, limit, ...filters } = input
|
||||
const scope = async () => fingerprint({ purpose: "incident-timeline-v1", filters, generation: await accessGeneration(),
|
||||
connection: context.connection.id, credential: context.principal?.credentialId,
|
||||
policy: context.connection.policy, ownerPermissions: context.connection.owner_permissions })
|
||||
let cursor: z.infer<typeof cursorSchema> | undefined
|
||||
if (token) {
|
||||
try {
|
||||
cursor = cursorSchema.parse(JSON.parse(await decryptSecret(token)))
|
||||
if (cursor.scope !== await scope()) throw Error("scope")
|
||||
} catch { throw new McpError("RESET_REQUIRED", "Курсор устарел или относится к другим фильтрам", 409) }
|
||||
}
|
||||
await requireServer(input.serverId)
|
||||
const parameters = [input.serverId, input.from, input.to, limit + 1]
|
||||
const queries: Array<{ source: TimelineSource; parameters: unknown[] }> =
|
||||
selected.map(source => ({ source, parameters: [...parameters] }))
|
||||
if (selected.includes("uptime")) queries.push({ source: "uptime-probe", parameters: [...parameters] })
|
||||
if (managerTools) queries.push({ source: "mcp-request",
|
||||
parameters: [...parameters, context.connection.id, context.connection.owner_id, managerTools] })
|
||||
const batches = await Promise.all(queries.map(async ({ source, parameters }) => {
|
||||
const { rows } = await pool.query<EvidenceRow>(timelineQuery(source, parameters, cursor), parameters)
|
||||
return rows.map(row => ({ ...row, source }))
|
||||
}))
|
||||
const items = batches.flat().sort((a, b) => a.at < b.at ? 1 : a.at > b.at ? -1 : a.source < b.source ? -1 : a.source > b.source ? 1 : 0)
|
||||
const page = items.slice(0, limit)
|
||||
const last = page.at(-1)
|
||||
const nextCursor = last && items.length > limit
|
||||
? await encryptSecret(JSON.stringify({ at: last.at, key: last.key, source: last.source, scope: cursor?.scope ?? await scope() }))
|
||||
: null
|
||||
return { serverId: input.serverId, from: new Date(input.from).toISOString(), to: new Date(input.to).toISOString(),
|
||||
observedAt: new Date().toISOString(), order: "newest-first", sources: queries.map(query => query.source),
|
||||
items: page.map(({ key: _key, receivedAt, ...row }) => ({
|
||||
...row, ...(receivedAt && { receivedAt: receivedAt.toISOString() }),
|
||||
})), nextCursor, truncated: nextCursor !== null, coverageVerified: false, managerEventsIncluded: input.includeManagerEvents }
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -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])),
|
||||
"./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>>>={}
|
||||
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
|
||||
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"]){
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
import assert from "node:assert/strict"
|
||||
import test from "node:test"
|
||||
import { projectDnsState, projectFibTableState, projectRouteLookup } from "./network-diagnostic-actions.js"
|
||||
|
||||
const route = (prefix: string, immediateGateway: string, table = "tenant") => ({
|
||||
"routing-table": table, "dst-address": prefix, active: "true",
|
||||
gateway: immediateGateway, "immediate-gw": immediateGateway,
|
||||
})
|
||||
|
||||
test("requires positive FIB evidence in the explicitly selected table", () => {
|
||||
const main = { name: "main", fib: true, invalid: false }
|
||||
assert.equal(projectFibTableState([main], "main"), "ready")
|
||||
assert.equal(projectFibTableState([main], "tenant"), "table-not-found")
|
||||
assert.equal(projectFibTableState([main, main], "main"), "partial")
|
||||
assert.equal(projectFibTableState([{ ...main, fib: "" }], "main"), "partial")
|
||||
assert.equal(projectFibTableState([{ ...main, fib: "false" }], "main"), "table-not-fib")
|
||||
assert.equal(projectFibTableState([{ ...main, invalid: true }], "main"), "table-inactive")
|
||||
})
|
||||
|
||||
test("looks up IPv4 by longest active prefix and preserves ECMP path multiplicity", () => {
|
||||
const prefix = "203.0.113.0/24"
|
||||
const result = projectRouteLookup([
|
||||
route("0.0.0.0/0", "192.0.2.1%wan"),
|
||||
route("203.0.113.10/32", "192.0.2.2%main", "main"),
|
||||
{ ...route("203.0.113.10/32", "192.0.2.3%disabled"), disabled: "true" },
|
||||
{ ...route("203.0.113.10/32", "192.0.2.4%inactive"), active: "false" },
|
||||
route(prefix, "192.0.2.5%uplink,192.0.2.6%uplink"),
|
||||
route(prefix, "192.0.2.5%uplink"),
|
||||
], "tenant", "203.0.113.10")
|
||||
assert.equal(result.status, "matched")
|
||||
assert.deepEqual(result.routes.map(item => item.prefix), [prefix, prefix])
|
||||
assert.deepEqual(result.nextHops, ["192.0.2.5%uplink", "192.0.2.6%uplink", "192.0.2.5%uplink"])
|
||||
assert.deepEqual(result.nextHopDetails.map(hop => hop.interface), ["uplink", "uplink", "uplink"])
|
||||
})
|
||||
|
||||
test("matches IPv6 blackhole and distinguishes absent and partial observations", () => {
|
||||
const blackhole = { "routing-table": "tenant", "dst-address": "2001:db8:1::/48", active: "true", blackhole: "yes" }
|
||||
const result = projectRouteLookup([route("::/0", "fe80::1%uplink"), blackhole], "tenant", "2001:db8:1:2::15")
|
||||
assert.equal(result.status, "matched")
|
||||
assert.equal(result.routes[0].disposition, "blackhole")
|
||||
assert.deepEqual(result.nextHops, [])
|
||||
assert.equal(projectRouteLookup([blackhole], "tenant", "2001:db8:2::1").status, "no-route")
|
||||
assert.equal(projectRouteLookup([{ ...blackhole, active: undefined }], "tenant", "2001:db8:1::1").status, "partial")
|
||||
assert.equal(projectRouteLookup([route("::/0", "")], "tenant", "2001:db8:1::1").status, "partial")
|
||||
assert.equal(projectRouteLookup([route("::/0", "fe80::1%uplink"), { ...blackhole, "dst-address": "2001:db8:1::/129" }], "tenant", "2001:db8:1::1").status, "partial")
|
||||
assert.equal(projectRouteLookup([{ ...blackhole, blackhole: "" }], "tenant", "2001:db8:1::1").routes[0].disposition, "blackhole")
|
||||
assert.equal(projectRouteLookup([route("::/0", "bridge wan")], "tenant", "2001:db8:1::1").nextHopDetails[0].interface, "bridge wan")
|
||||
})
|
||||
|
||||
test("bounds ECMP output and exposes omissions as partial", () => {
|
||||
const rows = Array.from({ length: 129 }, () => route("0.0.0.0/0", "192.0.2.1%uplink"))
|
||||
const result = projectRouteLookup(rows, "tenant", "203.0.113.10")
|
||||
assert.equal(result.status, "partial")
|
||||
assert.equal(result.nextHops.length, 128)
|
||||
})
|
||||
|
||||
test("retains duplicate native array nexthops across active default rows", () => {
|
||||
const defaults = Array.from({ length: 2 }, () => ({
|
||||
"routing-table": "main", "dst-address": "0.0.0.0/0", active: true,
|
||||
gateway: ["192.0.2.1"], "immediate-gw": ["192.0.2.1%ether1"],
|
||||
}))
|
||||
const result = projectRouteLookup(defaults, "main", "203.0.113.10")
|
||||
assert.equal(result.status, "matched")
|
||||
assert.deepEqual(result.nextHops, ["192.0.2.1%ether1", "192.0.2.1%ether1"])
|
||||
assert.deepEqual(result.routes.map(item => item.gateways), [["192.0.2.1"], ["192.0.2.1"]])
|
||||
assert.equal(projectRouteLookup([{ ...defaults[0], "immediate-gw": ["192.0.2.1%ether1", 1] }], "main", "203.0.113.10").status, "partial")
|
||||
})
|
||||
|
||||
test("DNS reports ordered upstream addresses and projects DoH to a boolean", () => {
|
||||
assert.deepEqual(projectDnsState({
|
||||
"allow-remote-requests": "yes", servers: "192.0.2.53@tenant,2001:db8::53", "dynamic-servers": "",
|
||||
"use-doh-server": "https://example.invalid/dns-query?secret=private", "cache-used": "private",
|
||||
}), {
|
||||
allowRemoteRequests: true, staticServers: ["192.0.2.53@tenant", "2001:db8::53"],
|
||||
dynamicServers: [], dohEnabled: true, incomplete: false,
|
||||
})
|
||||
assert.deepEqual(projectDnsState({ "allow-remote-requests": false, servers: "", "use-doh-server": "" }), {
|
||||
allowRemoteRequests: false, staticServers: [], dynamicServers: null, dohEnabled: false, incomplete: true,
|
||||
})
|
||||
assert.deepEqual(projectDnsState([{ "allow-remote-requests": false, servers: ["192.0.2.53", "2001:db8::53"], "dynamic-servers": [], "use-doh-server": "" }]), {
|
||||
allowRemoteRequests: false, staticServers: ["192.0.2.53", "2001:db8::53"], dynamicServers: [], dohEnabled: false, incomplete: false,
|
||||
})
|
||||
assert.throws(() => projectDnsState([{}, {}]))
|
||||
})
|
||||
@@ -0,0 +1,184 @@
|
||||
import { isIP } from "node:net"
|
||||
import { z } from "zod"
|
||||
import { observedBoolean } from "../../services/ospf-observed-values.js"
|
||||
import { isConfirmedRoutingFibTable } from "../../services/routing-table-fib.js"
|
||||
import { ipv4ToInt, ipv6ToInt, parseCidrV4, parseCidrV6 } from "../../services/traffic-flow-ip.js"
|
||||
import type { add } from "./actions.js"
|
||||
import { readNetworkValue } from "./network-neighbor-actions.js"
|
||||
import { parseRoutingEndpoint } from "./routing-native-endpoint.js"
|
||||
import { McpError } from "./security.js"
|
||||
|
||||
const serverIdSchema = z.number().int().positive().safe()
|
||||
const tableSchema = z.string().min(1).max(200).refine(value => !/[\u0000-\u001f\u007f]/.test(value))
|
||||
const destinationSchema = z.string().max(45).refine(value => !value.includes("%") && isIP(value) !== 0)
|
||||
const rowSchema = z.record(z.string(), z.unknown())
|
||||
const tablePath = "/routing/table?.proplist=name,fib,disabled,invalid"
|
||||
const dnsPath = "/ip/dns?.proplist=allow-remote-requests,servers,dynamic-servers,use-doh-server"
|
||||
const flags = z.union([z.boolean(), z.string()]).transform(value => typeof value === "boolean" ? value : observedBoolean(value))
|
||||
const flag = (value: unknown) => flags.safeParse(value).data ?? null
|
||||
const routeRows = z.array(rowSchema).max(10000)
|
||||
const maxRoutePaths = 128
|
||||
|
||||
export function projectFibTableState(raw: unknown, table: string) {
|
||||
const rows = routeRows.parse(raw)
|
||||
if (rows.some(row => typeof row.name !== "string")) return "partial"
|
||||
const matches = rows.filter(row => row.name === table)
|
||||
if (matches.length > 1) return "partial"
|
||||
if (!matches.length) return "table-not-found"
|
||||
const row = matches[0]
|
||||
if (flag(row.fib) === false) return "table-not-fib"
|
||||
if (flag(row.disabled) === true || flag(row.invalid) === true) return "table-inactive"
|
||||
// This REST catalog has produced an empty fib value for non-FIB tables as well.
|
||||
return row.fib !== "" && isConfirmedRoutingFibTable(row) ? "ready" : "partial"
|
||||
}
|
||||
|
||||
function matchingLength(value: unknown, destination: string): number | null {
|
||||
const family = isIP(destination)
|
||||
if (typeof value !== "string" || value.length > 50 || !/^[^/%]+\/\d+$/.test(value)) return null
|
||||
if (isIP(value.split("/")[0]) !== family) return null
|
||||
if (family === 4) {
|
||||
const prefix = parseCidrV4(value)
|
||||
if (!prefix) return null
|
||||
return ((ipv4ToInt(destination)! & prefix.mask) >>> 0) === prefix.net ? prefix.prefixLen : -1
|
||||
}
|
||||
const prefix = parseCidrV6(value)
|
||||
if (!prefix) return null
|
||||
return (ipv6ToInt(destination)! >> prefix.shift) === prefix.net ? prefix.prefixLen : -1
|
||||
}
|
||||
|
||||
const routePath = z.string().min(1).max(512).refine(value => !/[\u0000-\u001f\u007f]/.test(value))
|
||||
function nativeList(value: unknown, maxCharacters: number, maxItems: number): string[] | null {
|
||||
if (value === "") return []
|
||||
const items = typeof value === "string" && value.length <= maxCharacters ? value.split(",") : value
|
||||
if (!Array.isArray(items) || items.length > maxItems) return null
|
||||
let characters = 0
|
||||
const result = []
|
||||
for (const item of items) {
|
||||
if (typeof item !== "string") return null
|
||||
characters += item.length
|
||||
const entry = item.trim()
|
||||
if (!entry || characters > maxCharacters) return null
|
||||
result.push(entry)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
function splitNexthops(value: unknown) {
|
||||
const paths = nativeList(value, 16384, 1024)
|
||||
return paths?.every(path => !path.includes(",") && routePath.safeParse(path).success) ? paths : []
|
||||
}
|
||||
|
||||
function nexthopDetails(value: string) {
|
||||
try {
|
||||
const hop = parseRoutingEndpoint(value)
|
||||
return { address: hop.address, interface: hop.interface ?? null, vrf: hop.vrf ?? null }
|
||||
} catch {
|
||||
const direct = /^([^%@/]+)(?:@([^%@/]+))?$/.exec(value)
|
||||
return { address: null, interface: direct?.[1] ?? null, vrf: direct?.[2] ?? null }
|
||||
}
|
||||
}
|
||||
|
||||
export function projectRouteLookup(raw: unknown, table: string, destination: string) {
|
||||
const routes: { prefix: string; disposition: "blackhole" | "unreachable" | "prohibit" | "forward"; gateways: string[]; immediateGateways: string[] }[] = []
|
||||
let longest = -1
|
||||
let unknownLongest = -1
|
||||
let limited = false
|
||||
let hopCount = 0
|
||||
for (const row of routeRows.parse(raw)) {
|
||||
if (typeof row["routing-table"] === "string" && row["routing-table"] !== table) continue
|
||||
if (flag(row.active) === false || flag(row.disabled) === true || flag(row.inactive) === true) continue
|
||||
const length = matchingLength(row["dst-address"], destination)
|
||||
if (length === null) {
|
||||
unknownLongest = isIP(destination) === 4 ? 32 : 128
|
||||
continue
|
||||
}
|
||||
if (length < 0) continue
|
||||
if (row["routing-table"] !== table || flag(row.active) !== true) {
|
||||
unknownLongest = Math.max(unknownLongest, length)
|
||||
continue
|
||||
}
|
||||
if (length < longest) continue
|
||||
if (length > longest) {
|
||||
routes.length = 0
|
||||
limited = false
|
||||
hopCount = 0
|
||||
longest = length
|
||||
}
|
||||
if (routes.length === maxRoutePaths) {
|
||||
limited = true
|
||||
continue
|
||||
}
|
||||
const disposition = row.blackhole === "" ? "blackhole" : (["blackhole", "unreachable", "prohibit"] as const)
|
||||
.find(kind => flag(row[kind]) === true || row.type === kind || row.gateway === kind) ?? "forward"
|
||||
const remaining = maxRoutePaths - hopCount
|
||||
const configured = disposition === "forward" ? splitNexthops(row.gateway) : []
|
||||
const resolved = disposition === "forward" ? splitNexthops(row["immediate-gw"]) : []
|
||||
const paths = Math.max(configured.length, resolved.length)
|
||||
limited ||= paths > remaining
|
||||
hopCount += Math.min(paths, remaining)
|
||||
const gateways = configured.slice(0, remaining)
|
||||
const immediateGateways = resolved.slice(0, remaining)
|
||||
routes.push({ prefix: String(row["dst-address"]), disposition, gateways, immediateGateways })
|
||||
}
|
||||
const nextHops = routes.flatMap(route => route.immediateGateways)
|
||||
const nextHopDetails = nextHops.map(nexthopDetails)
|
||||
const incomplete = (unknownLongest >= 0 && unknownLongest >= longest) || limited
|
||||
|| routes.some(route => route.disposition === "forward" && !route.immediateGateways.length)
|
||||
|| nextHopDetails.some(hop => !hop.address && !hop.interface)
|
||||
return { status: incomplete ? "partial" : routes.length ? "matched" : "no-route", incomplete, routes, nextHops, nextHopDetails }
|
||||
}
|
||||
|
||||
function dnsServers(value: unknown) {
|
||||
const items = nativeList(value, 8192, 128)
|
||||
if (!items || items.some(server => {
|
||||
const [address, vrf, extra] = server.split("@")
|
||||
return !isIP(address) || extra !== undefined || (vrf !== undefined && !tableSchema.safeParse(vrf).success)
|
||||
})) return null
|
||||
return items
|
||||
}
|
||||
|
||||
export function projectDnsState(raw: unknown) {
|
||||
const row = Array.isArray(raw) ? z.tuple([rowSchema]).parse(raw)[0] : rowSchema.parse(raw)
|
||||
const allowRemoteRequests = flag(row["allow-remote-requests"])
|
||||
const staticServers = dnsServers(row.servers)
|
||||
const dynamicServers = dnsServers(row["dynamic-servers"])
|
||||
const dohEnabled = typeof row["use-doh-server"] === "string" ? row["use-doh-server"].trim().length > 0 : null
|
||||
return { allowRemoteRequests, staticServers, dynamicServers, dohEnabled,
|
||||
incomplete: [allowRemoteRequests, staticServers, dynamicServers, dohEnabled].includes(null) }
|
||||
}
|
||||
|
||||
export function registerNetworkDiagnosticActions(register: typeof add) {
|
||||
register("network.route.lookup.read", "mm_route_lookup_get",
|
||||
"Поиск самого специфичного активного маршрута IPv4/IPv6 в явно выбранной таблице FIB RouterOS",
|
||||
"network", "mm:network:read", "read", "servers",
|
||||
z.object({ serverId: serverIdSchema, destination: destinationSchema, table: tableSchema }).strict(),
|
||||
{ read: async (input, context) => {
|
||||
const serverId = Number(input.serverId), destination = String(input.destination), table = String(input.table)
|
||||
const family = isIP(destination) === 4 ? "ipv4" : "ipv6"
|
||||
const empty = { routes: [], nextHops: [], nextHopDetails: [] }
|
||||
const observed = { serverId, family, table, destination, forwardingVerified: false, timestampKind: "backend-receipt" }
|
||||
try {
|
||||
const result = await readNetworkValue(serverId, context, tablePath, async (raw, get) => {
|
||||
const state = projectFibTableState(raw, table)
|
||||
if (state !== "ready") return { ...empty, status: state, incomplete: state === "partial" }
|
||||
const resource = family === "ipv4" ? "/ip/route" : "/ipv6/route"
|
||||
const path = `${resource}?.proplist=dst-address,routing-table,active,disabled,inactive,gateway,immediate-gw,blackhole,type&${new URLSearchParams({ "routing-table": table })}`
|
||||
return projectRouteLookup(await get(path), table, destination)
|
||||
})
|
||||
return { ...observed, ...result, observedAt: new Date().toISOString() }
|
||||
} catch (error) {
|
||||
if (!(error instanceof McpError) || error.code !== "STATE_UNAVAILABLE") throw error
|
||||
return { ...observed, ...empty, status: "partial", incomplete: true, reason: "source-unavailable", observedAt: null }
|
||||
}
|
||||
} },
|
||||
)
|
||||
register("network.dns.state.read", "mm_dns_state_get",
|
||||
"Состояние DNS RouterOS: удалённые запросы, статические и динамические серверы и признак настройки DoH",
|
||||
"network", "mm:network:read", "read", "servers", z.object({ serverId: serverIdSchema }).strict(),
|
||||
{ read: async (input, context) => {
|
||||
const serverId = Number(input.serverId)
|
||||
const state = await readNetworkValue(serverId, context, dnsPath, projectDnsState)
|
||||
return { serverId, ...state, observedAt: new Date().toISOString(), timestampKind: "backend-receipt" }
|
||||
} },
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,225 @@
|
||||
import assert from "node:assert/strict"
|
||||
import { randomUUID } from "node:crypto"
|
||||
import { createServer } from "node:http"
|
||||
import type { AddressInfo } from "node:net"
|
||||
import { basename, dirname, isAbsolute } from "node:path"
|
||||
import { mcpConnectionCreateSchema } from "@mmapp/contracts/mcp"
|
||||
import { Client, StreamableHTTPClientTransport } from "@modelcontextprotocol/client"
|
||||
|
||||
assert.equal(process.env.MMAPP_OWN_NETWORK_DIAGNOSTICS, "true")
|
||||
assert.equal(process.env.NODE_ENV, "test")
|
||||
const database = new URL(process.env.DATABASE_URL ?? "")
|
||||
assert.equal(database.protocol, "postgresql:")
|
||||
assert.equal(database.hostname, "127.0.0.1")
|
||||
assert.equal(database.username, "mcp_test")
|
||||
assert.equal(database.pathname, "/postgres")
|
||||
assert(database.port && database.password && !database.search && !database.hash)
|
||||
const stateDir = process.env.MCP_STATE_DIR ?? ""
|
||||
assert(isAbsolute(stateDir))
|
||||
assert.equal(basename(stateDir), "state")
|
||||
assert.match(basename(dirname(stateDir)), /^mm-mcp-test-/)
|
||||
|
||||
const { pool, closePool } = await import("../../db/index.js")
|
||||
const { applySqlMigrations } = await import("../../db/migrate.js")
|
||||
const { buildApp } = await import("../../index.js")
|
||||
const { createMcpConnection, updateMcpSettings } = await import("./store.js")
|
||||
const actor = {
|
||||
id: "network-diagnostics-owner", apps: ["mm"],
|
||||
permissions: ["mm:settings:admin", "mm:network:read", "mm:servers:read", "mm:traffic:read", "mm:mcp:read"],
|
||||
expiresAt: Date.now() + 3_600_000,
|
||||
}
|
||||
const operations = {
|
||||
mm_capabilities_get: "capabilities.read",
|
||||
mm_telemetry_health_get: "telemetry.health.read",
|
||||
mm_incident_timeline_get: "incident.timeline.read",
|
||||
mm_route_lookup_get: "network.route.lookup.read",
|
||||
mm_dns_state_get: "network.dns.state.read",
|
||||
mm_resilience_topology_get: "network.resilience.topology.read",
|
||||
mm_resilience_design_preview: "network.resilience.design.read",
|
||||
mm_failover_report_get: "network.resilience.failover.read",
|
||||
}
|
||||
const dnsSecret = "private-doh-url-fixture"
|
||||
const nativeReads: string[] = []
|
||||
const nativeRoutes = new Map<string, unknown>([
|
||||
["/rest/routing/table", [{ name: "main", fib: "true" }]],
|
||||
["/rest/ip/route", [{ "routing-table": "main", "dst-address": "0.0.0.0/0", active: "true",
|
||||
gateway: "192.0.2.1", "immediate-gw": "192.0.2.1%ether1" }]],
|
||||
["/rest/ip/dns", { "allow-remote-requests": "false", servers: "1.1.1.1", "dynamic-servers": "",
|
||||
"use-doh-server": `https://example.invalid/${dnsSecret}` }],
|
||||
])
|
||||
const router = createServer((request, response) => {
|
||||
const path = new URL(request.url ?? "/", "http://127.0.0.1").pathname
|
||||
nativeReads.push(`${request.method} ${path}`)
|
||||
const value = nativeRoutes.get(path)
|
||||
response.writeHead(request.method === "GET" && value !== undefined ? 200 : 404, { "content-type": "application/json" })
|
||||
response.end(JSON.stringify(value ?? {}))
|
||||
})
|
||||
const sdkClient = () => new Client({ name: "owned-network-diagnostics", version: "1.0.0" })
|
||||
let client = sdkClient()
|
||||
const call = (name: keyof typeof operations, args: Record<string, unknown>) => client.callTool({ name, arguments: args })
|
||||
async function read<T>(name: keyof typeof operations, args: Record<string, unknown>) {
|
||||
const response = await call(name, args)
|
||||
assert(!response.isError, `${name}: ${JSON.stringify(response.content)}`)
|
||||
const result = (response.structuredContent as { result?: T } | undefined)?.result
|
||||
assert(result !== undefined, `Missing structured result for ${name}`)
|
||||
return result
|
||||
}
|
||||
async function deny(name: keyof typeof operations, args: Record<string, unknown>, code: string) {
|
||||
const response = await call(name, args)
|
||||
assert.equal(response.isError, true, name)
|
||||
assert(JSON.stringify(response.content).includes(code), `${name}: ${JSON.stringify(response.content)}`)
|
||||
}
|
||||
|
||||
let app: Awaited<ReturnType<typeof buildApp>> | undefined
|
||||
try {
|
||||
await applySqlMigrations(pool)
|
||||
assert.equal((await pool.query("SELECT count(*)::int AS n FROM servers")).rows[0].n, 0)
|
||||
await new Promise<void>(resolve => router.listen(0, "127.0.0.1", resolve))
|
||||
const port = (router.address() as AddressInfo).port
|
||||
await pool.query(`INSERT INTO servers(id,name,host,port,use_ssl,verify_ssl,username,password,enabled)
|
||||
VALUES (1,'scoped-router','127.0.0.1',$1,false,false,'owned','fixture',true),
|
||||
(2,'foreign-router','127.0.0.1',$1,false,false,'owned','fixture',true)`, [port])
|
||||
const now = Date.now()
|
||||
const instant = (offset: number) => new Date(now + offset).toISOString()
|
||||
const [localAt, foreignAt] = [instant(-2_000), instant(-1_000)]
|
||||
await pool.query("UPDATE router_log_settings SET enabled=true,interval_sec=3600 WHERE id=1")
|
||||
for (const [id, eventAt, message] of [[1, localAt, "local-log-fixture"], [2, foreignAt, "foreign-log-fixture"]] as const) {
|
||||
await pool.query(`INSERT INTO router_log_collection_state(server_id,server_name,host,last_collected_at)
|
||||
VALUES ($1,'fixture','127.0.0.1',$2)`, [id, eventAt])
|
||||
await pool.query(`INSERT INTO router_log_entries(server_id,server_name,host,router_id,raw_time,event_at,received_at,effective_at,topics,level,message,generation)
|
||||
VALUES ($1,'fixture','127.0.0.1','fixture','fixture',NULL,$2,$2,ARRAY['system'],'info',$3,1)`, [id, eventAt, message])
|
||||
}
|
||||
const segment = async (name: string, peerServerId?: number) => {
|
||||
const id = randomUUID()
|
||||
const configuration = { name, sites: [{ serverId: 1, autonomousSystem: 64512, routerId: "192.0.2.5",
|
||||
interfaces: [{ name: "ether1", kind: "uplink", peerServerId }],
|
||||
groups: [{ id: "internet", gateway: "192.0.2.1", primary: { interface: "ether1", nextHop: "192.0.2.1", probe: "192.0.2.8" } }],
|
||||
exits: ["internet"],
|
||||
}] }
|
||||
await pool.query(`INSERT INTO ix_segments(id,name,revision,configuration) VALUES ($1,$2,1,$3)`, [id, name, configuration])
|
||||
return { kind: "ix-segment", segmentId: id }
|
||||
}
|
||||
const target = await segment("scoped-segment"), foreignTarget = await segment("foreign-segment", 2)
|
||||
await updateMcpSettings({ enabled: true }, actor)
|
||||
const issue = (audit: boolean) => createMcpConnection(mcpConnectionCreateSchema.parse({
|
||||
name: "Scoped network diagnostics", mode: "observer", expiresAt: instant(600_000),
|
||||
permissions: ["mm:network:read", "mm:servers:read", ...(audit ? ["mm:mcp:read"] : [])],
|
||||
scope: { serverIds: [1], operationIds: Object.values(operations), allowGlobal: false },
|
||||
limits: { callsPerMinute: 120 },
|
||||
}), actor)
|
||||
|
||||
app = await buildApp({ startScheduler: false, logger: false })
|
||||
const address = await app.listen({ host: "127.0.0.1", port: 0 })
|
||||
const connect = (token: string) => client.connect(new StreamableHTTPClientTransport(new URL(`${address}/mcp`),
|
||||
{ requestInit: { headers: { Authorization: `Bearer ${token}` } } }))
|
||||
const access = await issue(false)
|
||||
await connect(access.token)
|
||||
const { tools } = await client.listTools()
|
||||
assert.deepEqual(tools.map(tool => tool.name).sort(), Object.keys(operations).sort())
|
||||
assert(tools.every(tool => tool.annotations?.readOnlyHint === true))
|
||||
const legacy = await read<{ operations: Array<{ id: string; applicability?: unknown }>; schemaVersion: number }>("mm_capabilities_get", {})
|
||||
assert.deepEqual(Object.keys(legacy).sort(), ["operations", "schemaVersion"])
|
||||
assert.equal(legacy.schemaVersion, 1)
|
||||
assert.deepEqual(legacy.operations.map(row => row.id).sort(), Object.values(operations).sort())
|
||||
assert(legacy.operations.every(row => !Object.hasOwn(row, "applicability")))
|
||||
const applicable = await read<{ operations: Array<{ applicability: { decision: string; reasons: Array<{ code: string }> } }> }>(
|
||||
"mm_capabilities_get", { toolName: "mm_route_lookup_get", serverId: 2 })
|
||||
assert.equal(applicable.operations.length, 1)
|
||||
assert.equal(applicable.operations[0].applicability.decision, "denied")
|
||||
assert(applicable.operations[0].applicability.reasons.some(reason => reason.code === "SERVER_DENIED"))
|
||||
|
||||
const health = await read<{ observations: Array<{ source: string; freshness: string; observedAt: string }>; netflowDataQuality: { available: boolean } }>(
|
||||
"mm_telemetry_health_get", { serverId: 1 })
|
||||
assert.deepEqual(health.observations.map(row => row.source).sort(), ["logs", "routeros-poll"])
|
||||
const logs = health.observations.find(row => row.source === "logs")
|
||||
assert.equal(logs?.observedAt, localAt)
|
||||
assert.equal(logs?.freshness, "fresh")
|
||||
assert.equal(health.netflowDataQuality.available, false)
|
||||
assert(!JSON.stringify(health).includes(foreignAt))
|
||||
const fleet = await read<{ items: Array<{ serverId: number }>; nextAfterServerId: number | null }>(
|
||||
"mm_telemetry_health_get", { sources: ["logs"], limit: 1 })
|
||||
assert.deepEqual(fleet.items.map(row => row.serverId), [1])
|
||||
assert.equal(fleet.nextAfterServerId, null)
|
||||
assert(!JSON.stringify(fleet).includes(foreignAt))
|
||||
const window = { from: instant(-60_000), outageAt: instant(-40_000), restoreAt: instant(-20_000), to: instant(0) }
|
||||
const range = { from: window.from, to: window.to, sources: ["logs"] }
|
||||
const timeline = await read<{ items: Array<{ message: string; timestampKind: string }>; coverageVerified: boolean }>(
|
||||
"mm_incident_timeline_get", { serverId: 1, ...range })
|
||||
assert.equal(timeline.items.length, 1)
|
||||
assert.equal(timeline.items[0].message, "local-log-fixture")
|
||||
assert.equal(timeline.items[0].timestampKind, "receipt")
|
||||
assert.equal(timeline.coverageVerified, false)
|
||||
await deny("mm_telemetry_health_get", { serverId: 2 }, "SERVER_DENIED")
|
||||
await deny("mm_incident_timeline_get", { serverId: 2, ...range }, "SERVER_DENIED")
|
||||
await deny("mm_telemetry_health_get", { serverId: 1, sources: ["netflow"] }, "PERMISSION_DENIED")
|
||||
await deny("mm_incident_timeline_get", { serverId: 1, ...range, sources: ["uptime"] }, "PERMISSION_DENIED")
|
||||
await deny("mm_incident_timeline_get", { serverId: 1, ...range, includeManagerEvents: true }, "PERMISSION_DENIED")
|
||||
|
||||
const lookup = { destination: "198.51.100.10", table: "main" }
|
||||
const route = await read<{ status: string; nextHops: string[]; forwardingVerified: boolean }>("mm_route_lookup_get", { serverId: 1, ...lookup })
|
||||
assert.equal(route.status, "matched")
|
||||
assert.deepEqual(route.nextHops, ["192.0.2.1%ether1"])
|
||||
assert.equal(route.forwardingVerified, false)
|
||||
const dns = await read<{ staticServers: string[]; dohEnabled: boolean }>("mm_dns_state_get", { serverId: 1 })
|
||||
assert.deepEqual(dns.staticServers, ["1.1.1.1"])
|
||||
assert.equal(dns.dohEnabled, true)
|
||||
assert(!JSON.stringify(dns).includes(dnsSecret))
|
||||
await deny("mm_route_lookup_get", { serverId: 2, ...lookup }, "SERVER_DENIED")
|
||||
await deny("mm_dns_state_get", { serverId: 2 }, "SERVER_DENIED")
|
||||
|
||||
const topology = await read<{ serverIds: number[]; paths: unknown[]; physicalIndependenceVerified: boolean }>("mm_resilience_topology_get", { target })
|
||||
assert.deepEqual(topology.serverIds, [1])
|
||||
assert.equal(topology.paths.length, 1)
|
||||
assert.equal(topology.physicalIndependenceVerified, false)
|
||||
const design = { scenario: "wan" }
|
||||
const preview = await read<{ suggestedTools: string[] }>("mm_resilience_design_preview", { target, ...design })
|
||||
assert(preview.suggestedTools.includes("mm_ix_segment_get"))
|
||||
const reportArgs = { window, targetFailoverMs: 1000, targetFailbackMs: 1000 }
|
||||
const report = await read<{ status: string; reason: string; managementSsh: string }>("mm_failover_report_get", { target, ...reportArgs })
|
||||
assert.equal(report.status, "inconclusive")
|
||||
assert.equal(report.reason, "NO_SAVED_IX_CONTROL_PROBE_HISTORY")
|
||||
assert.equal(report.managementSsh, "inconclusive")
|
||||
await deny("mm_resilience_topology_get", { target: foreignTarget }, "NOT_FOUND")
|
||||
await deny("mm_resilience_design_preview", { target: foreignTarget, ...design }, "NOT_FOUND")
|
||||
await deny("mm_failover_report_get", { target: foreignTarget, ...reportArgs }, "NOT_FOUND")
|
||||
assert.deepEqual(nativeReads, ["GET /rest/routing/table", "GET /rest/ip/route", "GET /rest/ip/dns"])
|
||||
|
||||
const auditedAccess = await issue(true)
|
||||
const requestId = randomUUID()
|
||||
await pool.query(`INSERT INTO mcp_requests(id,connection_id,actor_id,tool,server_ids,status,input,created_at,finished_at)
|
||||
VALUES ($1,$2,$4,'mm_dns_state_get',ARRAY[1]::bigint[],'succeeded','{"credential":"audit-secret-fixture"}',$5,$5),
|
||||
($6,$3,$4,'mm_dns_state_get',ARRAY[1]::bigint[],'succeeded','{}',$5,$5),
|
||||
($7,$2,$4,'mm_dns_state_get',ARRAY[1,2]::bigint[],'succeeded','{}',$5,$5)`,
|
||||
[requestId, auditedAccess.connection.id, access.connection.id, actor.id, foreignAt, randomUUID(), randomUUID()])
|
||||
await client.close()
|
||||
client = sdkClient()
|
||||
await connect(auditedAccess.token)
|
||||
type TimelinePage = { items: Array<{ id: string; source: string; toolName?: string }>; nextCursor: string | null }
|
||||
const auditArgs = { serverId: 1, ...range, includeManagerEvents: true, limit: 1 }
|
||||
const audited = await read<TimelinePage>("mm_incident_timeline_get", auditArgs)
|
||||
assert.deepEqual(audited.items.map(item => item.source), ["mcp-request"])
|
||||
assert.equal(audited.items[0].id, requestId)
|
||||
assert.equal(audited.items[0].toolName, "mm_dns_state_get")
|
||||
assert(!JSON.stringify(audited).includes("audit-secret-fixture"))
|
||||
assert(audited.nextCursor)
|
||||
const pageArgs = { ...auditArgs, cursor: audited.nextCursor }
|
||||
const next = await read<TimelinePage>("mm_incident_timeline_get", pageArgs)
|
||||
assert.deepEqual(next.items.map(item => item.source), ["logs"])
|
||||
assert.equal(next.nextCursor, null)
|
||||
await deny("mm_incident_timeline_get", { ...pageArgs, includeManagerEvents: false }, "RESET_REQUIRED")
|
||||
|
||||
const { assertSignedResilienceHistory } = await import("../../test/resilience-report-acceptance.js")
|
||||
await assertSignedResilienceHistory({
|
||||
connectionId: auditedAccess.connection.id,
|
||||
foreignConnectionId: access.connection.id,
|
||||
serverId: 1,
|
||||
callReport: input => read("mm_failover_report_get", input),
|
||||
})
|
||||
assert.equal((await pool.query("SELECT count(*)::int AS n FROM mcp_plans")).rows[0].n, 0)
|
||||
assert.equal((await pool.query("SELECT count(*)::int AS n FROM mcp_operations")).rows[0].n, 0)
|
||||
} finally {
|
||||
await client.close()
|
||||
await app?.close()
|
||||
if (router.listening) await new Promise<void>((resolve, reject) => router.close(error => error ? reject(error) : resolve()))
|
||||
await closePool()
|
||||
}
|
||||
@@ -44,7 +44,7 @@ function catalogRows<T>(value: unknown, project: (text: (key: string) => string
|
||||
}).sort((left, right) => left.id.localeCompare(right.id))
|
||||
}
|
||||
|
||||
async function readNetworkValue<T>(serverId: number, context: ActionContext, path: string, project: (raw: unknown) => T) {
|
||||
export async function readNetworkValue<T>(serverId: number, context: ActionContext, path: string, project: (raw: unknown, get: (path: string) => Promise<unknown>) => T | Promise<T>) {
|
||||
const authorize = async () => {
|
||||
if (context.signal?.aborted) throw new McpError("READ_CANCELLED", "Чтение сетевого каталога отменено", 409)
|
||||
const current = await effectiveMcpConnection(context.principal)
|
||||
@@ -57,8 +57,8 @@ async function readNetworkValue<T>(serverId: number, context: ActionContext, pat
|
||||
const check = async () => { await authorize(); await source.assertCurrent(); await authorize() }
|
||||
try {
|
||||
const { client } = await routerClient(serverId)
|
||||
const raw = await client.get<unknown>(path, 10000, context.signal, 1048576, check)
|
||||
const value = project(raw)
|
||||
const get = (resource: string) => client.get<unknown>(resource, 10000, context.signal, 1048576, check)
|
||||
const value = await project(await get(path), get)
|
||||
await check()
|
||||
return value
|
||||
} catch (error) {
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
import assert from "node:assert/strict"
|
||||
import { test } from "node:test"
|
||||
import { routeAiProfileSchema } from "@mmapp/contracts/mcp-routing"
|
||||
import { assessFailover, routePaths, summarizePaths } from "./resilience-actions.js"
|
||||
|
||||
const first = { id: "a", wanInterface: "ether1", jumpHostId: 2, exitNodeId: 3,
|
||||
downstreamInterface: "wg-a", gateway: "192.0.2.1", gatewayRef: { resource: "ipv4_route", id: "*a" } }
|
||||
const second = { ...first, id: "b", jumpHostId: 4, exitNodeId: 5, downstreamInterface: "wg-b" }
|
||||
|
||||
function topology(reserve: typeof second) {
|
||||
const profile = routeAiProfileSchema.parse({ name: "failover", community: "65000:1", family: "ipv4", serverId: 1, candidates: [first, reserve] })
|
||||
return summarizePaths(routePaths(profile))
|
||||
}
|
||||
|
||||
test("different jump and exit nodes still share a WAN on the origin router", () => {
|
||||
const result = topology(second)
|
||||
assert.deepEqual(result.sharedDomains, [
|
||||
{ kind: "source", serverId: 1, pathIds: ["a", "b"] },
|
||||
{ kind: "wan", serverId: 1, interfaceName: "ether1", pathIds: ["a", "b"] },
|
||||
])
|
||||
assert.equal(result.physicalIndependenceVerified, false)
|
||||
})
|
||||
|
||||
test("logically disjoint WAN, jump and exit nodes retain an unknown physical domain", () => {
|
||||
const result = topology({ ...second, wanInterface: "ether2" })
|
||||
assert.deepEqual(result.sharedDomains, [{ kind: "source", serverId: 1, pathIds: ["a", "b"] }])
|
||||
assert.ok(result.unknownDomains.includes("carrier"))
|
||||
assert.equal(result.physicalIndependenceVerified, false)
|
||||
})
|
||||
|
||||
test("pinned profiles retain the other path for inspection and exclude it from eligible reserve", () => {
|
||||
const profile = routeAiProfileSchema.parse({
|
||||
name: "pinned", community: "65000:1", family: "ipv4", serverId: 1, pinnedCandidateId: "a",
|
||||
candidates: [{ ...first, wanRemoteInterface: "wan-up", downstreamRemoteInterface: "wg-remote" }, second],
|
||||
})
|
||||
const result = summarizePaths(routePaths(profile))
|
||||
assert.deepEqual(result.eligiblePathIds, ["a"])
|
||||
assert.deepEqual(result.sharedDomains, [])
|
||||
assert.deepEqual(result.paths[0].dependencies.slice(-2), [
|
||||
{ kind: "wan", serverId: 2, interfaceName: "wan-up" },
|
||||
{ kind: "tunnel", serverId: 3, interfaceName: "wg-remote" },
|
||||
])
|
||||
})
|
||||
|
||||
test("separate IX groups with a single eligible path do not form a reserve pair", () => {
|
||||
const profile = routeAiProfileSchema.parse({ name: "failover", community: "65000:1", family: "ipv4", serverId: 1, candidates: [first, second] })
|
||||
const paths = routePaths(profile).map((path, index) => ({ ...path, groupId: `${index + 2}/exit` }))
|
||||
assert.deepEqual(summarizePaths(paths).alternativeGroups, [
|
||||
{ groupId: "2/exit", eligiblePathIds: ["a"] },
|
||||
{ groupId: "3/exit", eligiblePathIds: ["b"] },
|
||||
])
|
||||
})
|
||||
|
||||
const time = (offset: number) => new Date(Date.UTC(2026, 0, 1, 0, 0, 0, offset)).toISOString()
|
||||
const request = {
|
||||
target: { kind: "route-ai" as const, profileId: "1551445f-7c71-4411-976f-ce30302dcefe" },
|
||||
window: { from: time(0), outageAt: time(3000), restoreAt: time(10000), to: time(20000) },
|
||||
controlProbe: { primaryCandidateId: "a", backupCandidateId: "b" },
|
||||
targetFailoverMs: 1000, targetFailbackMs: 1000,
|
||||
}
|
||||
const probe = (candidateId: string, status: "passed" | "failed" | "unknown", begin: number, end: number) => ({
|
||||
id: candidateId + begin, candidateId, status, startedAt: time(begin), observedAt: time(end),
|
||||
})
|
||||
const baseline = probe("a", "passed", 2500, 2700)
|
||||
const failure = probe("a", "failed", 3100, 3300)
|
||||
const recovered = probe("a", "passed", 10100, 10500)
|
||||
|
||||
test("report passes each probe deadline and leaves HTTPS, SSH and existing connections unverified", () => {
|
||||
const result = assessFailover(request, [baseline, failure, probe("b", "failed", 3100, 3400), probe("b", "passed", 3500, 3800), recovered])
|
||||
assert.equal(result.status, "passed")
|
||||
assert.equal(result.failover.lowerBoundMs, 100)
|
||||
assert.equal(result.failover.upperBoundMs, 800)
|
||||
assert.equal(result.failover.firstGood?.id, "b3500")
|
||||
assert.equal(result.failback.upperBoundMs, 500)
|
||||
assert.equal(result.https, "inconclusive")
|
||||
assert.equal(result.serviceFailover, "inconclusive")
|
||||
assert.equal(result.existingConnections, "inconclusive")
|
||||
assert.equal(result.managementSsh, "inconclusive")
|
||||
assert.equal(result.returnPathVerified, false)
|
||||
})
|
||||
|
||||
test("report fails when the latest definitive failed probe started after the deadline", () => {
|
||||
const result = assessFailover(request, [baseline, failure, probe("b", "failed", 4500, 4700), probe("b", "passed", 4800, 5000), recovered])
|
||||
assert.equal(result.status, "failed")
|
||||
assert.equal(result.failover.lowerBoundMs, 1500)
|
||||
assert.equal(result.failover.upperBoundMs, 2000)
|
||||
assert.equal(result.failover.lastBad?.id, "b4500")
|
||||
})
|
||||
|
||||
test("late first success, unknown evidence, flap, or truncated history cannot establish success", () => {
|
||||
const history = [baseline, failure, recovered]
|
||||
assert.equal(assessFailover(request, [...history, probe("b", "passed", 4500, 4700)]).status, "inconclusive")
|
||||
assert.equal(assessFailover(request, [...history, probe("b", "unknown", 4500, 4700)]).status, "inconclusive")
|
||||
const pass = probe("b", "passed", 3500, 3700)
|
||||
assert.equal(assessFailover(request, [...history, pass, probe("b", "failed", 3800, 4000)]).status, "inconclusive")
|
||||
assert.equal(assessFailover(request, [...history, pass], true).status, "inconclusive")
|
||||
assert.equal(assessFailover(request, [baseline, probe("a", "unknown", 3100, 3300), recovered, pass]).status, "inconclusive")
|
||||
})
|
||||
@@ -0,0 +1,352 @@
|
||||
import { z } from "zod"
|
||||
import { routeAiProfileSchema, type RouteAiProfile } from "@mmapp/contracts/mcp-routing"
|
||||
import type { IxSegment } from "@mmapp/contracts/internet-exchange"
|
||||
import { pool } from "../../db/index.js"
|
||||
import { ixDeviceIds } from "../../services/internet-exchange-plan.js"
|
||||
import { readIxRevision, readIxSegment } from "../../services/internet-exchange-store.js"
|
||||
import type { add } from "./actions.js"
|
||||
import type { ActionContext } from "./action-types.js"
|
||||
import { PATH_PROOF_VERSION, pathProofTag } from "./path-proof-purpose.js"
|
||||
import { constantEqual, fingerprint, McpError, privateFingerprinterExisting } from "./security.js"
|
||||
|
||||
const siteId = z.number().int().positive().safe()
|
||||
const name = z.string().trim().min(1).max(100)
|
||||
const targetSchema = z.discriminatedUnion("kind", [
|
||||
z.object({ kind: z.literal("route-ai"), profileId: z.uuid() }).strict(),
|
||||
z.object({ kind: z.literal("ix-segment"), segmentId: z.uuid() }).strict(),
|
||||
z.object({ kind: z.literal("ix-client"), segmentId: z.uuid(), serverId: siteId, interfaceName: z.string().regex(/^[A-Za-z0-9_.-]{1,48}$/) }).strict(),
|
||||
])
|
||||
const topologyArgs = z.object({ target: targetSchema }).strict()
|
||||
const serviceEndpoint = z.object({
|
||||
serverId: siteId.optional(), interfaceName: z.string().regex(/^[A-Za-z0-9_.-]{1,48}$/).optional(),
|
||||
address: z.union([z.ipv4(), z.ipv6()]).optional(),
|
||||
}).strict().refine(endpoint => endpoint.serverId !== undefined || endpoint.address !== undefined)
|
||||
const designArgs = topologyArgs.extend({
|
||||
scenario: z.enum(["wan", "jump-host", "exit", "tunnel", "return", "flap"]),
|
||||
offset: z.number().int().min(0).max(1000).default(0),
|
||||
limit: z.number().int().min(1).max(25).default(10),
|
||||
protectedService: z.object({
|
||||
name, source: serviceEndpoint.optional(), destination: serviceEndpoint.optional(),
|
||||
maxInterruptionMs: z.number().int().min(1).max(3600000).optional(),
|
||||
}).strict().optional(),
|
||||
})
|
||||
const timestamp = z.iso.datetime({ offset: true })
|
||||
const reportArgs = topologyArgs.extend({
|
||||
controlProbe: z.object({ primaryCandidateId: name, backupCandidateId: name }).strict().optional(),
|
||||
window: z.object({ from: timestamp, outageAt: timestamp, restoreAt: timestamp, to: timestamp }).strict(),
|
||||
targetFailoverMs: z.number().int().min(1).max(3600000),
|
||||
targetFailbackMs: z.number().int().min(1).max(3600000),
|
||||
})
|
||||
|
||||
type Target = z.infer<typeof targetSchema>
|
||||
type ReportArgs = z.infer<typeof reportArgs>
|
||||
type Domain = { kind: "source" | "wan" | "jump-host" | "exit" | "tunnel" | "peer"; serverId: number; interfaceName?: string }
|
||||
type Path = { id: string; groupId: string; eligible: boolean; dependencies: Domain[] }
|
||||
type Source = { target: Target; serverIds: number[] } & (
|
||||
{ kind: "route-ai"; profile: RouteAiProfile; revision: number } |
|
||||
{ kind: "ix"; segment: IxSegment; paths: Path[] }
|
||||
)
|
||||
|
||||
export function routePaths(profile: RouteAiProfile): Path[] {
|
||||
return profile.candidates.map(candidate => ({
|
||||
id: candidate.id,
|
||||
groupId: "route-ai",
|
||||
eligible: !profile.excludedCandidateIds.includes(candidate.id) &&
|
||||
(profile.pinnedCandidateId === null || profile.pinnedCandidateId === candidate.id),
|
||||
dependencies: [
|
||||
{ kind: "source", serverId: profile.serverId },
|
||||
{ kind: "wan", serverId: profile.serverId, interfaceName: candidate.wanInterface },
|
||||
{ kind: "jump-host", serverId: candidate.jumpHostId },
|
||||
{ kind: "exit", serverId: candidate.exitNodeId },
|
||||
{ kind: "tunnel", serverId: candidate.jumpHostId, interfaceName: candidate.downstreamInterface },
|
||||
...(candidate.wanRemoteInterface ? [{ kind: "wan" as const, serverId: candidate.jumpHostId, interfaceName: candidate.wanRemoteInterface }] : []),
|
||||
...(candidate.downstreamRemoteInterface ? [{ kind: "tunnel" as const, serverId: candidate.exitNodeId, interfaceName: candidate.downstreamRemoteInterface }] : []),
|
||||
],
|
||||
}))
|
||||
}
|
||||
|
||||
export function summarizePaths(paths: Path[]) {
|
||||
const domains = new Map<string, { domain: Domain; pathIds: Set<string> }>()
|
||||
const eligibleGroups = new Map<string, string[]>()
|
||||
for (const path of paths.filter(path => path.eligible)) {
|
||||
const alternatives = eligibleGroups.get(path.groupId) ?? []
|
||||
alternatives.push(path.id)
|
||||
eligibleGroups.set(path.groupId, alternatives)
|
||||
for (const domain of path.dependencies) {
|
||||
const key = domain.kind === "wan" || domain.kind === "tunnel"
|
||||
? JSON.stringify([domain.serverId, domain.interfaceName])
|
||||
: JSON.stringify([domain.serverId])
|
||||
const record = domains.get(key) ?? { domain, pathIds: new Set<string>() }
|
||||
record.pathIds.add(path.id)
|
||||
domains.set(key, record)
|
||||
}
|
||||
}
|
||||
return {
|
||||
paths,
|
||||
eligiblePathIds: paths.filter(path => path.eligible).map(path => path.id),
|
||||
alternativeGroups: [...eligibleGroups].map(([groupId, eligiblePathIds]) => ({ groupId, eligiblePathIds })),
|
||||
sharedDomains: [...domains.values()].filter(value => value.pathIds.size > 1).map(value => ({
|
||||
...value.domain, pathIds: [...value.pathIds],
|
||||
})),
|
||||
unknownDomains: ["physical-uplink", "carrier", "power", "facility", "management", "return-path"],
|
||||
physicalIndependenceVerified: false,
|
||||
}
|
||||
}
|
||||
|
||||
function ixPaths(segment: IxSegment, target: Extract<Target, { kind: "ix-segment" | "ix-client" }>): Path[] {
|
||||
const paths: Path[] = []
|
||||
let bindingFound = false
|
||||
for (const site of segment.configuration.sites) {
|
||||
const client = target.kind === "ix-client" && target.serverId === site.serverId
|
||||
? site.interfaces.find(binding => binding.name === target.interfaceName && binding.linux)
|
||||
: undefined
|
||||
if (target.kind === "ix-client" && !client) continue
|
||||
if (client) bindingFound = true
|
||||
const selectedExits = client?.linux?.exit ? [client.linux.exit] : site.exits
|
||||
for (const group of site.groups) {
|
||||
if (client && !selectedExits.includes(group.id)) continue
|
||||
for (const role of ["primary", "backup"] as const) {
|
||||
const path = group[role]
|
||||
if (!path) continue
|
||||
const binding = site.interfaces.find(item => item.name === path.interface)
|
||||
const remote = binding?.peerServerId
|
||||
const dependencies: Domain[] = [
|
||||
{ kind: "source", serverId: site.serverId },
|
||||
{ kind: path.viaMain || binding?.kind === "uplink" ? "wan" : "tunnel", serverId: site.serverId, interfaceName: path.interface },
|
||||
]
|
||||
if (client) dependencies.push({ kind: "tunnel", serverId: site.serverId, interfaceName: client.name })
|
||||
if (remote !== undefined) {
|
||||
dependencies.push({ kind: selectedExits.includes(group.id) ? "exit" : "peer", serverId: remote })
|
||||
const remoteWan = binding?.provisionTransit?.remoteWan.interface
|
||||
if (remoteWan) dependencies.push({ kind: "wan", serverId: remote, interfaceName: remoteWan })
|
||||
}
|
||||
paths.push({
|
||||
id: `${site.serverId}/${group.id}/${role}`,
|
||||
groupId: `${site.serverId}/${group.id}`,
|
||||
eligible: client?.linux?.enabled ?? true,
|
||||
dependencies,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
if (target.kind === "ix-client" && !bindingFound) throw new McpError("NOT_FOUND", "Подключение IX не найдено", 404)
|
||||
return paths
|
||||
}
|
||||
|
||||
async function resolve(target: Target, context: ActionContext): Promise<Source> {
|
||||
const allowed = context.connection.policy.scope.serverIds
|
||||
const inScope = (ids: number[]) => ids.every(id => allowed.includes(id))
|
||||
if (target.kind === "route-ai") {
|
||||
const { rows: [row] } = await (context.transactionClient ?? pool).query(
|
||||
"SELECT version,config FROM mcp_routing_profiles WHERE id=$1 AND connection_id=$2",
|
||||
[target.profileId, context.connection.id],
|
||||
)
|
||||
if (!row) throw new McpError("NOT_FOUND", "Профиль Route AI не найден", 404)
|
||||
const profile = routeAiProfileSchema.parse(row.config)
|
||||
const serverIds = [...new Set([profile.serverId, ...profile.candidates.flatMap(candidate => [candidate.jumpHostId, candidate.exitNodeId])])]
|
||||
if (!inScope(serverIds)) throw new McpError("NOT_FOUND", "Профиль Route AI не найден", 404)
|
||||
return { kind: target.kind, target, profile, serverIds, revision: row.version }
|
||||
}
|
||||
|
||||
const segment = await readIxSegment(target.segmentId, context.transactionClient)
|
||||
if (!segment || !inScope(ixDeviceIds(segment.configuration))) throw new McpError("NOT_FOUND", "Сегмент IX не найден", 404)
|
||||
const applied = segment.appliedRevision !== null && segment.appliedRevision !== segment.revision
|
||||
? await readIxRevision(segment.id, segment.appliedRevision)
|
||||
: null
|
||||
const serverIds = [...new Set([...ixDeviceIds(segment.configuration), ...(applied ? ixDeviceIds(applied) : [])])]
|
||||
if (!inScope(serverIds)) throw new McpError("NOT_FOUND", "Сегмент IX не найден", 404)
|
||||
return { kind: "ix", target, segment, serverIds, paths: ixPaths(segment, target) }
|
||||
}
|
||||
|
||||
function topology(source: Source) {
|
||||
const { target, serverIds } = source
|
||||
const details = source.kind === "route-ai"
|
||||
? { source: "saved-route-ai-profile", revision: source.revision, pinnedCandidateId: source.profile.pinnedCandidateId }
|
||||
: { source: "saved-ix-configuration", revision: source.segment.revision, appliedRevision: source.segment.appliedRevision }
|
||||
return { target, serverIds, ...details, ...summarizePaths(source.kind === "route-ai" ? routePaths(source.profile) : source.paths) }
|
||||
}
|
||||
|
||||
const design = {
|
||||
wan: { tools: ["mm_server_wan_runtime_get", "mm_recursive_routes_get", "mm_recursive_routes_replace_plan"], criteria: "Разные WAN и next hop, с проверкой физической независимости линий." },
|
||||
"jump-host": { tools: ["mm_route_optimizer_analyze", "mm_ospf_application_preview"], criteria: "Разнести транзит по разным узлам и проверить общие зависимости кандидатов." },
|
||||
exit: { tools: ["mm_route_optimizer_analyze", "mm_bgp_sessions_get", "mm_ecmp_plan"], criteria: "Проверить независимость выходов, NAT, анонсы и доступность префиксов со стороны назначения." },
|
||||
tunnel: { tools: ["mm_wireguard_state_get", "mm_ospf_state_get", "mm_recursive_routes_get"], criteria: "Проверить тоннели, выбранный маршрут и детектирование отказа подложки." },
|
||||
return: { tools: ["mm_route_optimizer_analyze", "mm_route_path_verify"], criteria: "Проверить предпочтительный путь после восстановления, обратное направление и сохранение доступа управления вне переключаемого пути." },
|
||||
flap: { tools: ["mm_route_controller_get", "mm_route_profile_save_plan"], criteria: "Сопоставить интервалы наблюдений, подтверждения, гистерезис, cooldown и бюджет переключений с допустимым временем восстановления." },
|
||||
} as const
|
||||
|
||||
function scenarioFailures(paths: Path[], scenario: keyof typeof design) {
|
||||
if (scenario === "return" || scenario === "flap") return []
|
||||
const eligible = paths.filter(path => path.eligible)
|
||||
const failures = new Map<string, { groupId: string; domain: Domain }>()
|
||||
for (const path of eligible) {
|
||||
for (const domain of path.dependencies.filter(domain => domain.kind === scenario)) {
|
||||
failures.set(JSON.stringify([path.groupId, domain.serverId, domain.interfaceName]), { groupId: path.groupId, domain })
|
||||
}
|
||||
}
|
||||
return [...failures.values()].map(({ groupId, domain }) => ({
|
||||
groupId, domain,
|
||||
remainingEligiblePathIds: eligible.filter(path => path.groupId === groupId && !path.dependencies.some(dependency =>
|
||||
dependency.serverId === domain.serverId &&
|
||||
(domain.interfaceName === undefined || dependency.interfaceName === domain.interfaceName),
|
||||
)).map(path => path.id),
|
||||
}))
|
||||
}
|
||||
|
||||
type Observation = { id: string; candidateId: string; status: "passed" | "failed" | "unknown"; startedAt: string; observedAt: string }
|
||||
type PhaseStatus = "passed" | "failed" | "inconclusive"
|
||||
const at = (date: string) => Date.parse(date)
|
||||
|
||||
function phase(observations: Observation[], start: number, end: number, targetMs: number, goodAfter = start) {
|
||||
const samples = observations.filter(row => at(row.startedAt) >= start && at(row.observedAt) <= end)
|
||||
.sort((left, right) => at(left.observedAt) - at(right.observedAt))
|
||||
const firstGood = samples.find(row => row.status === "passed" && at(row.startedAt) >= goodAfter)
|
||||
const lastBad = samples.filter(row => row.status === "failed" && (!firstGood || at(row.observedAt) <= at(firstGood.startedAt))).at(-1)
|
||||
const subsequentFailure = firstGood && samples.find(row => row.status === "failed" && at(row.startedAt) >= at(firstGood.observedAt))
|
||||
const lowerBoundMs = (lastBad ? at(lastBad.startedAt) : start) - start
|
||||
const upperBoundMs = firstGood ? at(firstGood.observedAt) - start : null
|
||||
const ambiguous = firstGood && samples.some(row => row.status === "failed" &&
|
||||
at(row.startedAt) < at(firstGood.observedAt) && at(row.observedAt) > at(firstGood.startedAt))
|
||||
const status: PhaseStatus = ambiguous || subsequentFailure ? "inconclusive"
|
||||
: upperBoundMs !== null && upperBoundMs <= targetMs ? "passed"
|
||||
: lowerBoundMs > targetMs ? "failed" : "inconclusive"
|
||||
return { status, lowerBoundMs, upperBoundMs, targetMs, firstGood: firstGood ?? null, lastBad: lastBad ?? null, subsequentFailure: subsequentFailure ?? null }
|
||||
}
|
||||
|
||||
export function assessFailover(input: ReportArgs, observations: Observation[], truncated = false) {
|
||||
const { window, controlProbe } = input
|
||||
const ordered = [...observations].sort((left, right) => at(left.observedAt) - at(right.observedAt))
|
||||
const primary = ordered.filter(row => row.candidateId === controlProbe?.primaryCandidateId)
|
||||
const backup = ordered.filter(row => row.candidateId === controlProbe?.backupCandidateId)
|
||||
const outage = at(window.outageAt), restore = at(window.restoreAt)
|
||||
const latestBaseline = primary.filter(row => at(row.startedAt) >= at(window.from) && at(row.observedAt) < outage).at(-1)
|
||||
const baseline = latestBaseline?.status === "passed" ? latestBaseline : null
|
||||
const primaryFailure = primary.find(row => row.status === "failed" && at(row.startedAt) >= outage && at(row.observedAt) < restore) ?? null
|
||||
const failover = phase(backup, outage, restore - 1, input.targetFailoverMs, primaryFailure ? at(primaryFailure.observedAt) : restore)
|
||||
const failback = phase(primary, restore, at(window.to), input.targetFailbackMs)
|
||||
const status: PhaseStatus = truncated || !baseline || !primaryFailure ? "inconclusive"
|
||||
: [failover.status, failback.status].includes("failed") ? "failed"
|
||||
: failover.status === "passed" && failback.status === "passed" ? "passed" : "inconclusive"
|
||||
return {
|
||||
status, scope: "configured-control-probe-reachability", baseline, primaryFailure, failover, failback,
|
||||
restoredPath: failback.firstGood ? "control-probe-observed" : "inconclusive",
|
||||
serviceFailover: "inconclusive", https: "inconclusive", existingConnections: "inconclusive", managementSsh: "inconclusive",
|
||||
forwardingSelectionVerified: false, returnPathVerified: false, truncated,
|
||||
}
|
||||
}
|
||||
|
||||
const savedObservation = z.object({
|
||||
id: z.uuid(), connectionId: z.uuid(), profileHash: z.string(), candidateId: name,
|
||||
proofPurpose: z.literal("control-path"), proofVersion: z.literal(PATH_PROOF_VERSION),
|
||||
dependencyProof: z.string().regex(/^[a-f0-9]{64}$/), status: z.enum(["passed", "failed", "unknown"]), startedAt: timestamp, observedAt: timestamp,
|
||||
sourceProofs: z.array(z.object({ serverId: siteId, proof: z.string().regex(/^[a-f0-9]{64}$/) }).strict()).min(1).max(3),
|
||||
})
|
||||
|
||||
async function report(input: ReportArgs, source: Source, context: ActionContext) {
|
||||
const { window, controlProbe } = input
|
||||
const from = at(window.from), outage = at(window.outageAt), restore = at(window.restoreAt), to = at(window.to)
|
||||
if (!(from < outage && outage < restore && restore < to && to <= Date.now() && to - from <= 86400000)) {
|
||||
throw new McpError("INVALID_INPUT", "Окно должно быть завершено, не длиннее 24 часов и включать фазы до отказа, после отказа и после восстановления", 400)
|
||||
}
|
||||
if (source.kind !== "route-ai") return { ...assessFailover(input, []), target: input.target, window, reason: "NO_SAVED_IX_CONTROL_PROBE_HISTORY" }
|
||||
if (!controlProbe || controlProbe.primaryCandidateId === controlProbe.backupCandidateId ||
|
||||
![controlProbe.primaryCandidateId, controlProbe.backupCandidateId].every(id => source.profile.candidates.some(candidate => candidate.id === id && candidate.controlProbe))) {
|
||||
throw new McpError("INVALID_INPUT", "Выберите два разных кандидата с контрольной пробой из сохранённого профиля", 400)
|
||||
}
|
||||
const connectionId = context.connection.id
|
||||
const profileHash = fingerprint(source.profile)
|
||||
const { rows } = await pool.query<{ id: string; candidate_id: string; status: string; evidence: Record<string, unknown> | null }>(
|
||||
`SELECT id,candidate_id,status,CASE WHEN octet_length(evidence::text)<=32768 THEN evidence END AS evidence FROM mcp_path_checks
|
||||
WHERE connection_id=$1 AND profile_hash=$2 AND candidate_id=ANY($3::text[])
|
||||
AND created_at >= $4::timestamptz AND created_at <= $5::timestamptz
|
||||
AND evidence->>'proofPurpose' IS DISTINCT FROM 'community'
|
||||
ORDER BY created_at,id LIMIT 501`,
|
||||
[connectionId, profileHash, [controlProbe.primaryCandidateId, controlProbe.backupCandidateId], window.from, window.to],
|
||||
)
|
||||
const sign = rows.length ? await privateFingerprinterExisting("route-control-path-context-v1").catch(error => {
|
||||
if (error instanceof McpError && error.code === "STATE_UNAVAILABLE") return null
|
||||
throw error
|
||||
}) : null
|
||||
const observations: Observation[] = []
|
||||
const sourceProofs = new Map<number, string>()
|
||||
let evidenceError: "INVALID_CONTROL_PATH_EVIDENCE" | "SOURCE_IDENTITY_CHANGED" | null = null
|
||||
for (const row of rows.slice(0, 500)) {
|
||||
const { proof, ...payload } = row.evidence ?? {}
|
||||
const parsed = savedObservation.safeParse(payload)
|
||||
if (!parsed.success || !sign || typeof proof !== "string") {
|
||||
evidenceError = "INVALID_CONTROL_PATH_EVIDENCE"
|
||||
break
|
||||
}
|
||||
const { id, status, candidateId, startedAt, observedAt, dependencyProof } = parsed.data
|
||||
const candidate = source.profile.candidates.find(candidate => candidate.id === candidateId)
|
||||
const expected = new Set([source.profile.serverId, candidate?.jumpHostId, candidate?.exitNodeId])
|
||||
const observed = new Set(parsed.data.sourceProofs.map(source => source.serverId))
|
||||
if (id !== row.id || status !== row.status || candidateId !== row.candidate_id ||
|
||||
parsed.data.connectionId !== connectionId || parsed.data.profileHash !== profileHash ||
|
||||
at(startedAt) > at(observedAt) || observed.size !== parsed.data.sourceProofs.length ||
|
||||
expected.size !== observed.size || ![...expected].every(id => id !== undefined && observed.has(id)) ||
|
||||
!constantEqual(sign(pathProofTag("control-path") + fingerprint({ dependencyProof, value: payload })), proof)) {
|
||||
evidenceError = "INVALID_CONTROL_PATH_EVIDENCE"
|
||||
break
|
||||
}
|
||||
if (at(startedAt) < from || at(observedAt) > to) continue
|
||||
for (const source of parsed.data.sourceProofs) {
|
||||
if (sourceProofs.has(source.serverId) && sourceProofs.get(source.serverId) !== source.proof) evidenceError = "SOURCE_IDENTITY_CHANGED"
|
||||
sourceProofs.set(source.serverId, source.proof)
|
||||
}
|
||||
observations.push({ id, status, candidateId, startedAt, observedAt })
|
||||
}
|
||||
const result = assessFailover(input, evidenceError ? [] : observations, rows.length > 500)
|
||||
const eligible = routePaths(source.profile).filter(path => path.eligible).map(path => path.id)
|
||||
const reason = rows.length && !sign ? "PROOF_KEY_UNAVAILABLE" : evidenceError ?? (
|
||||
!eligible.includes(controlProbe.primaryCandidateId) || !eligible.includes(controlProbe.backupCandidateId) ? "CANDIDATE_UNAVAILABLE_IN_PROFILE" : null)
|
||||
return { target: input.target, window, controlProbe, ...result,
|
||||
...(reason ? { status: "inconclusive" as const, reason } : {}),
|
||||
}
|
||||
}
|
||||
|
||||
export function registerResilienceActions(register: typeof add) {
|
||||
const target = async (input: Record<string, unknown>, context: ActionContext) => ({
|
||||
scope: "servers" as const, serverIds: (await resolve(targetSchema.parse(input.target), context)).serverIds,
|
||||
})
|
||||
register("network.resilience.topology.read", "mm_resilience_topology_get", "Зависимости путей и общие домены отказа", "network", "mm:network:read", "read", "servers", topologyArgs, {
|
||||
target,
|
||||
read: async (input, context) => topology(await resolve(topologyArgs.parse(input).target, context)),
|
||||
})
|
||||
register("network.resilience.design.read", "mm_resilience_design_preview", "Предпросмотр резервирования по сценарию отказа", "network", "mm:network:read", "read", "servers", designArgs, {
|
||||
target,
|
||||
read: async (input, context) => {
|
||||
const args = designArgs.parse(input)
|
||||
const source = await resolve(args.target, context)
|
||||
const serviceServers = [args.protectedService?.source?.serverId, args.protectedService?.destination?.serverId]
|
||||
if (serviceServers.some(id => id !== undefined && !source.serverIds.includes(id))) {
|
||||
throw new McpError("INVALID_INPUT", "Устройство защищаемого сервиса вне выбранной топологии", 400)
|
||||
}
|
||||
const observed = topology(source)
|
||||
const proposal = design[args.scenario]
|
||||
const failures = scenarioFailures(observed.paths, args.scenario)
|
||||
const tools = source.kind === "ix"
|
||||
? ["mm_ix_segment_get", "mm_ix_change_plan", ...(args.target.kind === "ix-client" ? ["mm_ix_linux_path_get"] : []),
|
||||
...proposal.tools.filter(tool => !tool.startsWith("mm_route_") && !tool.endsWith("_plan"))]
|
||||
: [...proposal.tools]
|
||||
return {
|
||||
target: args.target, scenario: args.scenario, protectedService: args.protectedService ?? null,
|
||||
criteria: proposal.criteria, suggestedTools: tools,
|
||||
eligiblePathIds: observed.eligiblePathIds, alternativeGroups: observed.alternativeGroups,
|
||||
configuredReserve: observed.alternativeGroups.some(group => group.eligiblePathIds.length > 1),
|
||||
configuredPathsAfterFailure: failures.slice(args.offset, args.offset + args.limit),
|
||||
nextOffset: args.offset + args.limit < failures.length ? args.offset + args.limit : null,
|
||||
sharedDomains: observed.sharedDomains, unknownDomains: observed.unknownDomains,
|
||||
missingEvidence: ["usable-capacity", "path-mtu", "return-path", "service-interruption", "management-reachability"],
|
||||
requiredChecks: ["Отдельная проверка активного маршрута и обратного направления", "Непрерывность HTTPS, действующих соединений и независимого SSH-управления по отдельным измерениям"],
|
||||
}
|
||||
},
|
||||
})
|
||||
register("network.resilience.failover.read", "mm_failover_report_get", "Оценка failover и failback по сохранённым контрольным пробам", "network", "mm:network:read", "read", "servers", reportArgs, {
|
||||
target,
|
||||
read: async (input, context) => {
|
||||
const args = reportArgs.parse(input)
|
||||
return report(args, await resolve(args.target, context), context)
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -85,6 +85,17 @@ const firewall = {
|
||||
"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(),
|
||||
}
|
||||
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 = {
|
||||
"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(),
|
||||
@@ -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: "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 },
|
||||
...(["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: "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"] },
|
||||
@@ -154,7 +165,7 @@ export function supportsRosPlacement(step: Pick<RosStep, "resource" | "action" |
|
||||
export const ROS_SNAPSHOT_VERSION = 3
|
||||
// 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 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 }
|
||||
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"])
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
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 { proveRosDriftExpectation, verifyRosStepSnapshots } from "./ros-step-verification.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, 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 updated = { ...a, action: "accept" }
|
||||
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)) {
|
||||
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
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { z } from "zod"
|
||||
import { pool } from "../../db/index.js"
|
||||
import { hasPermission } from "../../lib/permissions.js"
|
||||
import { executeTerminalDiagnostic, terminalDiagnosticSchema, type TerminalDiagnosticClient } from "../../services/terminal-diagnostics.js"
|
||||
import { executeTerminalDiagnostic, readTerminalInterfaceCounters, terminalDiagnosticNames, terminalDiagnosticSchema, terminalInterfaceCountersSchema, type TerminalDiagnosticClient } from "../../services/terminal-diagnostics.js"
|
||||
import { withTerminalDiagnosticClient } from "../../services/terminal-diagnostic-client.js"
|
||||
import { readRoutingEndpoints } from "./routing-observation-source.js"
|
||||
import { effectiveMcpConnection } from "./store.js"
|
||||
@@ -10,11 +10,20 @@ import type { add } from "./actions.js"
|
||||
|
||||
export const TERMINAL_DIAGNOSTIC_MAX_OUTPUT_BYTES = 12000
|
||||
export function registerTerminalDiagnosticActions(register: typeof add) {
|
||||
const schema = terminalDiagnosticSchema.safeExtend({ serverId: z.number().int().positive().safe() })
|
||||
const schema = z.object({
|
||||
...terminalDiagnosticSchema.shape,
|
||||
serverId: z.number().int().positive().safe(),
|
||||
diagnostic: z.enum([...terminalDiagnosticNames, "interface_counters"]),
|
||||
interface: terminalInterfaceCountersSchema.shape.interface,
|
||||
}).strict().superRefine(({ serverId: _id, ...args }, ctx) => {
|
||||
const parsed = args.diagnostic === "interface_counters" ? terminalInterfaceCountersSchema.safeParse(args) : terminalDiagnosticSchema.safeParse(args)
|
||||
if (!parsed.success) for (const issue of parsed.error.issues) ctx.addIssue({ code: "custom", message: issue.message, path: issue.path })
|
||||
})
|
||||
register("servers.terminal.read", "mm_server_terminal_diagnostic", "Разрешённая типизированная диагностика REST-терминала", "servers", "mm:servers:write", "read", "servers", schema, {
|
||||
read: async (input, context) => {
|
||||
const serverId = Number(input.serverId), { serverId: _id, ...args } = input
|
||||
const command = terminalDiagnosticSchema.parse(args), generation = await accessGeneration()
|
||||
const command = args.diagnostic === "interface_counters" ? terminalInterfaceCountersSchema.parse(args) : terminalDiagnosticSchema.parse(args)
|
||||
const generation = await accessGeneration()
|
||||
const initial = (await pool.query("SELECT id,enabled,routing_endpoint_epoch FROM servers WHERE id=$1", [serverId])).rows[0]
|
||||
const authorize = async () => {
|
||||
context.signal?.throwIfAborted()
|
||||
@@ -33,11 +42,20 @@ export function registerTerminalDiagnosticActions(register: typeof add) {
|
||||
await authorize()
|
||||
if (endpoints.length !== 1 || endpoints[0].routingEndpointEpoch !== initial.routing_endpoint_epoch || !endpoints[0].enabled) throw new McpError("STATE_CONFLICT", "Источник диагностики изменился", 409)
|
||||
const endpoint = endpoints[0]
|
||||
try { output = await withTerminalDiagnosticClient(endpoint, { signal: context.signal, authorize }, client => executeTerminalDiagnostic(client, command)) }
|
||||
const secrets = [endpoint.password, Buffer.from(`${endpoint.username}:${endpoint.password}`).toString("base64")].filter(Boolean)
|
||||
try {
|
||||
if (command.diagnostic === "interface_counters") {
|
||||
const protect = (value: string) => secrets.some(secret => value.includes(secret)) ? "[redacted]" : String(redact(value))
|
||||
const interfaceCounters = await withTerminalDiagnosticClient(endpoint, { signal: context.signal, authorize }, client => readTerminalInterfaceCounters(client, command, protect))
|
||||
await authorize()
|
||||
return { serverId, diagnostic: command.diagnostic, interfaceCounters, activity: { kind: "read", configurationApplied: false } }
|
||||
}
|
||||
output = await withTerminalDiagnosticClient(endpoint, { signal: context.signal, authorize }, client => executeTerminalDiagnostic(client, command))
|
||||
}
|
||||
catch (error) { if (error instanceof McpError) throw error; throw new McpError("STATE_UNAVAILABLE", "Терминальная диагностика не вернула подтверждённый результат", 409) }
|
||||
// Free-form comments and log text may echo stored credentials. Mask exact
|
||||
// credentials as well as labelled secrets before returning or auditing.
|
||||
for (const value of [endpoint.password, Buffer.from(`${endpoint.username}:${endpoint.password}`).toString("base64")].filter(Boolean)) output = output.split(value).join("[redacted]")
|
||||
for (const value of secrets) output = output.split(value).join("[redacted]")
|
||||
}
|
||||
await authorize()
|
||||
const redactionTruncated = output.length > MAX_MCP_PUBLIC_STRING_LENGTH
|
||||
|
||||
@@ -276,7 +276,8 @@ export async function requireAuth(
|
||||
/** Gate the matched route, including encoded static segments in the raw URL. */
|
||||
export async function requireApiAuth(request: FastifyRequest, reply: FastifyReply): Promise<void> {
|
||||
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)
|
||||
}
|
||||
|
||||
|
||||
@@ -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))
|
||||
// The service owns exclusivity, including calls that do not originate in HTTP.
|
||||
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 }
|
||||
streams.set(request, state)
|
||||
try {
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { coalesceCatalogReads, observationIsCurrent, readCatalogWithObservedCache, withCatalogWriteLock } from "../services/routing-catalog-observation.js"
|
||||
import { and, asc, eq, inArray } from "drizzle-orm"
|
||||
import { z } from "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 { parseDbServerId } from "../utils/server-id.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 { managedComment, hasManagedCommentPrefix } from "../managed-markers.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[]) {
|
||||
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 => ({
|
||||
@@ -381,20 +383,26 @@ export async function readFilterRulesCatalog(selected: ServerRow[], options: { s
|
||||
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 }))
|
||||
}
|
||||
const readSelected = () => Promise.all(selected.map(async server => {
|
||||
return Promise.all(selected.map(async server => {
|
||||
try {
|
||||
const remote = await fetchServerFilters(server)
|
||||
if (options.persistObserved) {
|
||||
const read = async (fresh: boolean) => {
|
||||
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 appendRevisionIfChanged({ serverId: server.id, section: "filters", source: "observed", payload: canonicalFilterRules(remote.rules) })
|
||||
}
|
||||
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 { remote, rules: await cacheRulesetsForServer(server.id), current: true }
|
||||
})
|
||||
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 options.persistObserved
|
||||
? withApplicationMutationLock(() => withConfigMutationLock(selected.map(server => server.id), readSelected)) : readSelected()
|
||||
}
|
||||
|
||||
export async function applyFiltersToServer(
|
||||
@@ -406,7 +414,7 @@ export async function applyFiltersToServer(
|
||||
if (!server.enabled) throw new McpError("DEVICE_UNAVAILABLE", "Сервер выключен; изменение фильтров запрещено", 409)
|
||||
if (options.managedRuleComment !== undefined && !hasManagedCommentPrefix(options.managedRuleComment)) throw new McpError("PROTECTED_OBJECT", "Сохранённый comment фильтра не принадлежит приложению", 409)
|
||||
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 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)
|
||||
@@ -442,7 +450,7 @@ const filtersRoutes: FastifyPluginAsyncZod = async (app) => {
|
||||
const server = enabledServers.find(s => s.id === sid)
|
||||
if (!server) return reply.status(404).send({ error: "Server not found" })
|
||||
try {
|
||||
const remote = await fetchServerFilters(server)
|
||||
const remote = await readWebFilters(server)
|
||||
return reply.send({ tunnels: remote.tunnels })
|
||||
} catch (error) {
|
||||
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. */
|
||||
@@ -523,6 +531,7 @@ const filtersRoutes: FastifyPluginAsyncZod = async (app) => {
|
||||
rules: cached,
|
||||
})
|
||||
} catch (err) {
|
||||
if (err instanceof McpError && err.statusCode === 409) throw err
|
||||
app.log.error({ serverId, err: String(err) }, "filters apply failed")
|
||||
await appendEvent({
|
||||
level: "critical",
|
||||
@@ -588,6 +597,7 @@ const filtersRoutes: FastifyPluginAsyncZod = async (app) => {
|
||||
})
|
||||
return reply.send({ ok: true, rules: cached, pushedRules: result.pushed })
|
||||
} catch (err) {
|
||||
if (err instanceof McpError) throw err
|
||||
app.log.error({ serverId: server.id, err: String(err) }, "filters restore failed")
|
||||
return reply.status(500).send({ error: String(err) })
|
||||
}
|
||||
|
||||
@@ -5,7 +5,9 @@ import { ixBondEditSchema, ixChangeSchema, ixLinuxClientRequest, ixTransitReques
|
||||
import { fingerprint, McpError } from "../modules/mcp/security.js"
|
||||
import { audit } from "../modules/mcp/store.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 { 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 { applyIxChange, assignIxRouterIds, configureIxLinuxClient, configureIxTransit, listIxLinuxClients, observeIxLinuxPath, observeIxSegment, prepareIxChange, prepareIxRemoval, readIxLinuxClient, readIxNodeInventory, removeIxSegment } from "../services/internet-exchange-execution.js"
|
||||
@@ -49,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 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) => {
|
||||
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 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" })
|
||||
request.log.error({ error: error instanceof Error ? error.name : "unknown" }, "IX request failed")
|
||||
const errorMessage = request.method === "DELETE" ? "Удаление сегмента IX не подтверждено. Обновите данные и проверьте план."
|
||||
@@ -81,11 +99,25 @@ const ixRoutes: FastifyPluginAsync = async app => {
|
||||
})
|
||||
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 } = planRequest.parse(request.body)
|
||||
const scope = { deadlineAt: Date.now() + 90_000 }
|
||||
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 { ownerId } = await authorize()
|
||||
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 })
|
||||
@@ -158,12 +190,36 @@ const ixRoutes: FastifyPluginAsync = async app => {
|
||||
})
|
||||
app.post("/ix/segments/:id/linux/credential", async (request, reply) => {
|
||||
const { id } = segmentParams.parse(request.params)
|
||||
const { serverId, interfaceName, transportOnly } = clientKey.extend({ transportOnly: z.boolean().optional() }).parse(request.body)
|
||||
const scope = { deadlineAt: Date.now() + 60_000 }
|
||||
const { serverId, interfaceName, transportOnly, importLink } = clientKey.extend({
|
||||
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 { 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)
|
||||
if (!segment) throw new IxConflict("Сегмент IX не найден", 404)
|
||||
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 audit(pool, ownerId, "ix.linux.credential_exported", null, { segmentId: id, serverId, interfaceName, revision: access.revision })
|
||||
|
||||
@@ -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 { parseRecursiveCatalog, parseRecursiveGatewayCatalog, readRecursiveEffectiveProperties, type RecursiveObservedProperty } from "../services/recursive-route-catalog.js"
|
||||
import { executeRecursiveApply, RecursiveApplyError } from "../services/recursive-apply.js"
|
||||
import { storeRecursiveRoutes } from "../services/recursive-route-store.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 { z } from "zod"
|
||||
import type { FastifyPluginAsyncZod } from "@fastify/type-provider-zod"
|
||||
@@ -100,7 +101,7 @@ export async function applyRecursiveToServer(
|
||||
source: ConfigRevisionSource,
|
||||
validateExisting?: (rows: ReturnType<typeof parseRecursiveCatalog>) => void | Promise<void>,
|
||||
): Promise<{ pushed: number; deleted: number }> {
|
||||
return withApplicationMutationLock(() => withConfigMutationLock([server.id], async () => {
|
||||
return withCatalogWriteLock(server, "recursive-routes", async () => {
|
||||
await storeRecursiveRoutes(server.id, routes, source, true)
|
||||
const client = MikrotikClient.fromServer(server)
|
||||
return executeRecursiveApply(client, routes.map(toRouterPayload), async () => {
|
||||
@@ -116,7 +117,7 @@ export async function applyRecursiveToServer(
|
||||
await validateExisting?.(parseRecursiveCatalog(observed))
|
||||
return observed
|
||||
}, () => readRecursiveNativeRowsForServer(server))
|
||||
}))
|
||||
})
|
||||
}
|
||||
|
||||
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;
|
||||
* 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 } = {}) {
|
||||
const read = async () => {
|
||||
type RecursiveReadDependencies = Pick<RecursiveRouteDependencies, "readRaw" | "readProperty" | "getRoutes" | "saveObserved">
|
||||
|
||||
const readWebRecursiveRows = coalesceCatalogReads(readRecursiveNativeRowsForServer)
|
||||
|
||||
async function observeRecursiveRoutes(server: ServerRow, deps: RecursiveReadDependencies, persist: boolean) {
|
||||
const read = async (fresh: boolean) => {
|
||||
if (!server.enabled) throw new Error("Устройство отключено: каталог маршрутов недоступен")
|
||||
const observed = await readRecursiveEffectiveProperties(await deps.readRaw(server), (id, property) => deps.readProperty(server, id, property))
|
||||
const routes = mergeCachedCountry(parseRecursiveCatalog(observed), await deps.getRoutes(server.id))
|
||||
if (options.persistObserved !== false) await deps.saveObserved(server.id, routes)
|
||||
return { serverId: server.id, routes, live: true, stale: false }
|
||||
const observed = !fresh && persist && deps === recursiveDefaults ? await readWebRecursiveRows(server)
|
||||
: await readRecursiveEffectiveProperties(await deps.readRaw(server), (id, property) => deps.readProperty(server, id, property))
|
||||
const cached = await deps.getRoutes(server.id)
|
||||
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
|
||||
? withApplicationMutationLock(() => withConfigMutationLock([server.id], read)) : read()
|
||||
const save = async (snapshot: Awaited<ReturnType<typeof 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) {
|
||||
@@ -187,22 +204,18 @@ export async function readRecursiveGatewaysForServer(server: ServerRow, deps: Pi
|
||||
|
||||
/** Legacy application read, including its explicit stale fallback. MCP observers
|
||||
* 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("Устройство отключено: опрос маршрутов недоступен")
|
||||
const read = async () => {
|
||||
const cached = await deps.getRoutes(server.id)
|
||||
try {
|
||||
const result = await readRecursiveCatalogForServer(server, deps, options)
|
||||
const routes = options.persistObserved === false
|
||||
? planRecursiveIdentities(cached, result.routes, new Set(), "observed").rows.map((row, index) => ({ ...row, id: row.id || result.routes[index].id }))
|
||||
: await deps.getRoutes(server.id)
|
||||
return { ...result, routes }
|
||||
} catch {
|
||||
return { serverId: server.id, routes: cached, live: false, stale: true, error: "Не удалось подтвердить живой каталог; возвращена сохранённая конфигурация" }
|
||||
}
|
||||
try {
|
||||
const observed = await observeRecursiveRoutes(server, deps, options.persistObserved !== false)
|
||||
const routes = options.persistObserved === false
|
||||
? planRecursiveIdentities(observed.cached, observed.routes, new Set(), "observed").rows.map((row, index) => ({ ...row, id: row.id || observed.routes[index].id }))
|
||||
: observed.cached
|
||||
return { serverId: server.id, routes, live: true, stale: false }
|
||||
} catch (error) {
|
||||
if (error instanceof McpError && (error.code === "CONFIGURATION_BUSY" || error.code === "STATE_CONFLICT")) throw error
|
||||
return { serverId: server.id, routes: await deps.getRoutes(server.id), live: false, stale: true, error: "Не удалось подтвердить живой каталог; возвращена сохранённая конфигурация" }
|
||||
}
|
||||
return deps === recursiveDefaults && options.persistObserved !== false
|
||||
? withApplicationMutationLock(() => withConfigMutationLock([server.id], read)) : read()
|
||||
}
|
||||
|
||||
export function createRecursiveRoutes(overrides: Partial<RecursiveRouteDependencies> = {}): FastifyPluginAsyncZod {
|
||||
@@ -218,6 +231,7 @@ export function createRecursiveRoutes(overrides: Partial<RecursiveRouteDependenc
|
||||
try {
|
||||
return reply.send(await readRecursiveCatalogForServer(server, deps))
|
||||
} catch (error) {
|
||||
if (error instanceof McpError) throw error
|
||||
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 })
|
||||
} catch (err) {
|
||||
const receipt = recursiveFailureReceipt(err, result)
|
||||
if (!receipt && err instanceof McpError) throw err
|
||||
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 })
|
||||
} catch (err) {
|
||||
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 })
|
||||
}
|
||||
})
|
||||
|
||||
@@ -5,6 +5,7 @@ import { createSchedulerRoutes } from "./scheduler.js"
|
||||
import type { SchedulerRunReceipt } from "../services/scheduler-recorded-run.js"
|
||||
import { pauseSchedulerJobsAndWait, resumeSchedulerJobs } from "../services/scheduler-running.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 } }
|
||||
async function setup(patch: Partial<Parameters<typeof createSchedulerRoutes>[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") } })
|
||||
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() }
|
||||
})
|
||||
@@ -51,11 +51,11 @@ return async (app) => {
|
||||
return reply.send({ ok: result.status === "ok", result, status, ...(statusError ? { statusError } : {}) })
|
||||
} catch (e) {
|
||||
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)
|
||||
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 })
|
||||
}
|
||||
})
|
||||
|
||||
@@ -210,7 +210,9 @@ const trafficFlowRoutes: FastifyPluginAsyncZod = async (app) => {
|
||||
|
||||
app.get("/traffic/flow/map-hops", async (req, reply) => {
|
||||
const query = analyticsQuery(req)
|
||||
return reply.send(await readFlowWindow(query.minutes, minutes => buildFlowMapHops({ ...query, minutes }), mcpDatabaseRequestSignal()))
|
||||
const includeCurrentMinute = (req.query as { range?: string }).range?.toLowerCase() === "1m"
|
||||
const requestedMinutes = includeCurrentMinute ? 1 : query.minutes
|
||||
return reply.send(await readFlowWindow(requestedMinutes, minutes => buildFlowMapHops({ ...query, minutes, includeCurrentMinute }), mcpDatabaseRequestSignal()))
|
||||
})
|
||||
|
||||
app.get("/traffic/flow/monthly", async (req, reply) => {
|
||||
|
||||
@@ -13,12 +13,13 @@ import {
|
||||
} from "../services/traffic-collector.js"
|
||||
import { refreshScheduler } from "../services/scheduler.js"
|
||||
import { collectTrafficManually } from "../services/manual-traffic-collection.js"
|
||||
import { readTrafficLiveSample, TrafficLiveSourceChanged } from "../services/traffic-live.js"
|
||||
import { readTrafficLiveInterfaces, readTrafficLiveSample, TrafficLiveSourceChanged } from "../services/traffic-live.js"
|
||||
import { MikrotikClient, MikrotikError } from "../services/mikrotik.js"
|
||||
import { getEnabledServerById } from "../services/wireguard-live.js"
|
||||
import { readTrafficCollectionContext } from "../services/traffic-collection-state.js"
|
||||
import { readServerTrafficHistory, readServerTrafficHistoryWithSeries, readServerTrafficInterfaces } from "../services/traffic-history-read.js"
|
||||
import { mergeBuiltTraffic } from "../services/traffic-rate.js"
|
||||
import { getUserById } from "../modules/users/service/users-service.js"
|
||||
import {
|
||||
buildBoundInterfaceTraffic,
|
||||
buildUserTrafficList,
|
||||
@@ -106,9 +107,15 @@ const trafficRoutes: FastifyPluginAsyncZod = async (app) => {
|
||||
})
|
||||
app.get("/traffic/servers/:id/live", async (req, reply) => {
|
||||
const p = req.params as { id?: string | number }
|
||||
const q = req.query as { iface?: string; once?: string }
|
||||
if (q.once === "1" && (typeof q.iface !== "string" || !q.iface.trim() ||
|
||||
q.iface.length > 128 || q.iface === "__all__" || /[,\x00-\x1f\x7f]/.test(q.iface))) {
|
||||
const q = req.query as { iface?: string; ifaces?: string; once?: string }
|
||||
const validIface = (name: unknown): name is string => typeof name === "string" && Boolean(name.trim()) &&
|
||||
name.length <= 128 && name !== "__all__" && !/[,\x00-\x1f\x7f]/.test(name)
|
||||
const interfaces = typeof q.ifaces === "string" ? q.ifaces.split(",") : []
|
||||
if (q.ifaces !== undefined && (q.once !== "1" || q.iface !== undefined || !interfaces.length ||
|
||||
interfaces.length > 16 || new Set(interfaces).size !== interfaces.length || !interfaces.every(validIface))) {
|
||||
return reply.code(400).send({ error: "Укажите до 16 разных интерфейсов для live-измерения" })
|
||||
}
|
||||
if (q.once === "1" && !interfaces.length && !validIface(q.iface)) {
|
||||
return reply.code(400).send({ error: "Укажите один интерфейс для live-измерения" })
|
||||
}
|
||||
const readServer = (id: string | number, signal?: AbortSignal) => withDatabaseApiRequest(async () => {
|
||||
@@ -123,11 +130,12 @@ const trafficRoutes: FastifyPluginAsyncZod = async (app) => {
|
||||
const onlyInterface = q.iface && q.iface !== "__all__" ? q.iface : undefined
|
||||
const client = MikrotikClient.fromServer(server)
|
||||
const cache = { names: onlyInterface ? [onlyInterface] : [] as string[], joinedFailed: false }
|
||||
const readSample = (signal: AbortSignal) => readTrafficLiveSample(client, onlyInterface, cache, signal, async () => {
|
||||
const assertSource = async (signal: AbortSignal) => {
|
||||
const current = await readServer(server.id, signal)
|
||||
if (!current) throw new TrafficLiveSourceChanged("Устройство выключено или удалено. Переподключите live-поток")
|
||||
if (Date.parse(current.updatedAt) !== Date.parse(server.updatedAt)) throw new TrafficLiveSourceChanged("Конфигурация устройства изменилась. Переподключите live-поток")
|
||||
})
|
||||
}
|
||||
const readSample = (signal: AbortSignal) => readTrafficLiveSample(client, onlyInterface, cache, signal, () => assertSource(signal))
|
||||
const abort = new AbortController()
|
||||
const onClose = () => abort.abort()
|
||||
registerDatabaseStreamAbort(req, onClose)
|
||||
@@ -136,7 +144,9 @@ const trafficRoutes: FastifyPluginAsyncZod = async (app) => {
|
||||
if (q.once === "1") {
|
||||
reply.raw.once("close", onClose)
|
||||
try {
|
||||
const sample = await readSample(abort.signal)
|
||||
const sample = interfaces.length
|
||||
? { interfaces: await readTrafficLiveInterfaces(client, interfaces, abort.signal, () => assertSource(abort.signal)) }
|
||||
: await readSample(abort.signal)
|
||||
return reply.header("Cache-Control", "no-store").send(sample)
|
||||
} catch {
|
||||
if (!reply.raw.destroyed) return reply.code(503).send({ error: "Live-измерение интерфейса недоступно" })
|
||||
@@ -227,9 +237,9 @@ const trafficRoutes: FastifyPluginAsyncZod = async (app) => {
|
||||
const minutes = rangeToMinutes(q.range)
|
||||
const rangeEndMs = Date.now()
|
||||
const rangeStartMs = rangeEndMs - minutes * 60_000
|
||||
const users = await buildUserTrafficList(rangeStartMs, rangeEndMs)
|
||||
const user = users.find((u) => u.id === id)
|
||||
if (!user) return reply.status(404).send({ error: "Пользователь не найден" })
|
||||
const source = await getUserById(id)
|
||||
if (!source) return reply.status(404).send({ error: "Пользователь не найден" })
|
||||
const [user] = await buildUserTrafficList(rangeStartMs, rangeEndMs, { users: [source] })
|
||||
return reply.send({ user })
|
||||
})
|
||||
|
||||
|
||||
@@ -14,10 +14,10 @@ const held = new AsyncLocalStorage<ServerLockCompletion>()
|
||||
const applicationLease = new AsyncLocalStorage<LockCompletion>()
|
||||
const collectorLease = new AsyncLocalStorage<LockCompletion>()
|
||||
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 {
|
||||
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> {
|
||||
@@ -80,17 +80,36 @@ export async function withApplicationMutationLock<T>(work: () => Promise<T>, opt
|
||||
/** Collectors coexist with each other but exclude configuration mutation for
|
||||
* the complete native/sample/status operation. This lock grants no authority.
|
||||
* 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()
|
||||
if (applicationLease.getStore()?.active || captureOperationConfigurationLockHandoff()) return withApplicationMutationLock(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
|
||||
const completed = new Promise<void>(resolve => { complete = resolve })
|
||||
const client = await pool.connect(), context = { active: true, completed }
|
||||
let acquired = false, unsafe = false
|
||||
try {
|
||||
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)
|
||||
} finally {
|
||||
context.active = false
|
||||
@@ -159,7 +178,7 @@ async function runConfigMutationLock<T>(serverIds: number[], work: () => Promise
|
||||
}
|
||||
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])
|
||||
if (!row.acquired) throw Object.assign(new Error("Конфигурация сервера изменяется другой операцией"), { statusCode: 409 })
|
||||
if (!row.acquired) throw new ConfigurationBusyError("server")
|
||||
acquired.push(id)
|
||||
signal.throwIfAborted()
|
||||
}
|
||||
|
||||
@@ -14,6 +14,26 @@ const route: IxRouterObject = {
|
||||
}
|
||||
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", () => {
|
||||
const changes = planIxNative(id, [vrf, route], [], device({
|
||||
"/ip/vrf": [{ ".id": "*A", name: "main", interfaces: "all", builtin: "true" }],
|
||||
|
||||
@@ -98,6 +98,9 @@ export function planIxNative(id: string, desired: IxRouterObject[], previous: Ix
|
||||
rows.some(row => egressObject(row.comment)))).map(device => device.serverId))
|
||||
// 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))
|
||||
// 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 previousByKey = new Map(previous.map(object => [deviceMarker(object), object]))
|
||||
const result: Task[] = []
|
||||
@@ -356,7 +359,7 @@ async function configureIxLinuxTunnel(segment: IxSegment, input: IxLinuxClientRe
|
||||
const binding: IxSite["interfaces"][number] = {
|
||||
name, kind: input.kind, prefixes: input.prefixes,
|
||||
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") {
|
||||
const existing = previous?.provisionWireguard
|
||||
@@ -870,7 +873,7 @@ export async function observeIxLinuxPath(segment: IxSegment, serverId: number, n
|
||||
})) }
|
||||
}
|
||||
|
||||
export async function readIxLinuxClient(segment: IxSegment, serverId: number, name: string, includeCredential: boolean | "wireguard" = false, transportOnly = 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("Сначала примените конфигурацию площадки")
|
||||
const configuration = await readIxRevision(segment.id, segment.appliedRevision)
|
||||
const site = configuration.sites.find(site => site.serverId === serverId)
|
||||
@@ -902,7 +905,15 @@ export async function readIxLinuxClient(segment: IxSegment, serverId: number, na
|
||||
throw new IxConflict("Действующий PSK не совпал с применённой ревизией. Выполните сверку")
|
||||
}
|
||||
}
|
||||
return { ...clientInfo, kind: "gre-ipsec", ...ixGreClientTemplate(binding, serverId, peer, credential, transportOnly) }
|
||||
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")
|
||||
const wireguard = await readRows(client, "/interface/wireguard", ["name", "public-key", "listen-port", "comment", "disabled"])
|
||||
|
||||
@@ -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,
|
||||
localAddress: "10.254.1.1/30", peerAddress: "10.254.1.2", hubEndpoint: "192.0.2.10" } })
|
||||
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 defaults = objects.filter(object => object.fields["routing-table"] === clientTable)
|
||||
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")))
|
||||
})
|
||||
|
||||
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", () => {
|
||||
const value = fixture(), site = value.sites[0]
|
||||
site.interfaces.push({ name: "it-abc", kind: "wireguard", prefixes: [], peerServerId: 99,
|
||||
|
||||
@@ -84,6 +84,11 @@ function compileLinuxPolicy(namespace: string, site: IxSite, binding: IxSite["in
|
||||
const permitted = privateTable + "-dst"
|
||||
const sourcesCidr = [...new Set([host(tunnel.peerAddress), ...binding.prefixes.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 exit = site.groups.find(group => group.id === policy.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,
|
||||
action: "accept", disabled: String(!policy.enabled) })
|
||||
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
|
||||
add("/routing/table", key + "-table", { name: privateTable, fib: "true" })
|
||||
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(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) })
|
||||
const mainPaths = paths.filter(path => path.viaMain)
|
||||
for (const [index, path] of mainPaths.entries()) {
|
||||
|
||||
@@ -12,11 +12,12 @@ import {
|
||||
uptimeSpeedProbes,
|
||||
} from "../db/schema.js"
|
||||
import { listServersRead } from "../modules/servers/service/servers-service.js"
|
||||
import { rosIdToIfIndex } from "./traffic-flow-ifindex.js"
|
||||
import { MikrotikClient } from "./mikrotik.js"
|
||||
import type { InternetPathRunSnapshot } from "../types/scheduler-run-snapshot.js"
|
||||
import { SCHEDULER_RUN_SNAPSHOT_VERSION } from "../types/scheduler-run-snapshot.js"
|
||||
|
||||
import { collectConfirmedInternetPath, readInternetPathRows } from "./internet-path-snapshot.js"
|
||||
import { collectConfirmedInternetPath, observedGrePeers, readGreEnrichment, readInternetPathRows } from "./internet-path-snapshot.js"
|
||||
|
||||
const INTERNET_TARGET = "1.1.1.1"
|
||||
let collecting = false
|
||||
@@ -47,7 +48,7 @@ async function getSettingsRow() {
|
||||
retentionDays: 14,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
})
|
||||
}).onConflictDoNothing({ target: internetPathSettings.id })
|
||||
return (await db.select().from(internetPathSettings).where(eq(internetPathSettings.id, 1)).limit(1))[0]
|
||||
}
|
||||
|
||||
@@ -177,12 +178,22 @@ function parseInnerIps(comment: string): { localInnerIp: string; remoteInnerIp:
|
||||
|
||||
async function collectGreTunnels() {
|
||||
const enabled = await db.select().from(servers).where(eq(servers.enabled, true))
|
||||
const assignedAddresses = new Map<string, Set<string>>()
|
||||
const all = await Promise.all(enabled.map(async (srv) => {
|
||||
try {
|
||||
const client = MikrotikClient.fromServer(srv)
|
||||
const rows = await client.get<unknown>("/interface/gre").then(raw => readInternetPathRows(raw, "GRE " + srv.id, [".id", "name", "local-address", "remote-address"]))
|
||||
if (!rows.length) return []
|
||||
const [addresses, interfaces] = await Promise.all([
|
||||
readGreEnrichment(() => client.get<unknown>("/ip/address"), "GRE addresses " + srv.id, ["interface", "address"]),
|
||||
readGreEnrichment(() => client.get<unknown>("/interface"), "interfaces " + srv.id, [".id", "name"]),
|
||||
])
|
||||
const activeAddresses = addresses.filter(a => !isTrue(a.disabled) && !isTrue(a.invalid))
|
||||
assignedAddresses.set(String(srv.id), new Set(activeAddresses.map(a => a.address!.split("/")[0]!)))
|
||||
return rows.map((g, idx) => {
|
||||
const keepalive = String(g.keepalive ?? "0,0").split(",")
|
||||
const identities = interfaces.filter(row => row.name === g.name)
|
||||
const identity = identities.length === 1 ? identities[0] : undefined
|
||||
const inner = parseInnerIps(String(g.comment ?? ""))
|
||||
return {
|
||||
id: String(g.name ?? g[".id"] ?? `gre-${srv.id}-${idx}`),
|
||||
@@ -190,6 +201,10 @@ async function collectGreTunnels() {
|
||||
serverId: String(srv.id),
|
||||
localAddress: String(g["local-address"] ?? ""),
|
||||
remoteAddress: String(g["remote-address"] ?? ""),
|
||||
currentRemoteAddress: String(g["current-remote-address"] ?? ""),
|
||||
nativeIndex: rosIdToIfIndex(identity?.[".id"]),
|
||||
ifIndex: /^[1-9][0-9]*$/.test(identity?.ifindex ?? "") ? Number(identity!.ifindex) : null,
|
||||
observedAddresses: activeAddresses.filter(a => a.interface === g.name).map(a => a.address!),
|
||||
localInnerIp: inner.localInnerIp,
|
||||
remoteInnerIp: inner.remoteInnerIp,
|
||||
poolId: "live",
|
||||
@@ -212,7 +227,7 @@ async function collectGreTunnels() {
|
||||
throw new Error(`Internet path: GRE устройства ${srv.id}: ${error instanceof Error ? error.message : String(error)}`)
|
||||
}
|
||||
}))
|
||||
return all.flat()
|
||||
return observedGrePeers(all.flat(), new Map(enabled.map(server => [String(server.id), server.host])), assignedAddresses)
|
||||
}
|
||||
|
||||
export async function getInternetPathSettings() {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import assert from "node:assert/strict"
|
||||
import {collectConfirmedInternetPath, readInternetPathRows, readStoredInternetPathPayload, mapStoredInternetPathResponse} from "./internet-path-snapshot.js"
|
||||
import {collectConfirmedInternetPath, observedGrePeers, readGreEnrichment, readInternetPathRows, readStoredInternetPathPayload, mapStoredInternetPathResponse} from "./internet-path-snapshot.js"
|
||||
const servers=[{id:1,type:"home-router",enabled:true},{id:2,type:"home-router",enabled:false},{id:3,type:"exit-node",enabled:true}]
|
||||
const sampledAt="2026-10-04T00:00:00Z"
|
||||
const defaults={servers:async()=>servers,gre:async()=>[],filters:async()=>[],speed:async()=>[],route:async(id:number)=>{assert.equal(id,1);return {gateway:null,routingMark:null}},wan:async(id:number)=>{assert.equal(id,1);return {defaultGateway:null,defaultInterface:null,uplinks:[]}}}
|
||||
@@ -35,3 +35,29 @@ for (const stored of ["2026-10-04 07:00:00+07", "2026-10-04T00:00:00Z"]) {
|
||||
for (const invalid of ["", "bad", null]) assert.throws(()=>mapStoredInternetPathResponse({payloadJson:good,sampledAt:invalid as string}))
|
||||
assert.throws(()=>mapStoredInternetPathResponse({payloadJson:"bad",sampledAt}))
|
||||
console.log("internet path HTTP timestamp: PostgreSQL/ISO instant preserved; invalid metadata rejected")
|
||||
|
||||
const jh = { serverId: "7", enabled: true, localAddress: "0.0.0.0", remoteAddress: "198.51.100.9", observedAddresses: ["10.200.100.53/30"] }
|
||||
const exit = { serverId: "9", enabled: true, localAddress: "198.51.100.9", remoteAddress: "198.51.100.7", observedAddresses: ["10.200.100.54/30"] }
|
||||
const hosts = new Map([["7", "198.51.100.7"], ["9", "198.51.100.9"]])
|
||||
assert.deepEqual(observedGrePeers([jh, exit], hosts, new Map()).map(t => t.observedNextHops), [[{ip:"10.200.100.54",serverId:"9"}],[{ip:"10.200.100.53",serverId:"7"}]])
|
||||
for (const incomplete of [[jh], [jh, exit, {...exit, serverId:"18"}], [jh, {...exit, enabled:false}], [jh, {...exit, remoteAddress:"198.51.100.8"}], [jh, {...exit, observedAddresses:["10.200.100.55/30"]}]]) {
|
||||
assert.ok(observedGrePeers(incomplete, hosts, new Map()).every(t => !t.observedNextHops.length))
|
||||
}
|
||||
|
||||
const wildcard = observedGrePeers([
|
||||
{...jh, localAddress:"0.0.0.0",remoteAddress:"exit.example",currentRemoteAddress:"198.51.100.2"},
|
||||
{...exit,localAddress:"0.0.0.0",remoteAddress:"198.51.100.1"},
|
||||
], new Map([["7","jump.example"],["9","exit.example"]]), new Map([["7",new Set(["198.51.100.1"])],["9",new Set(["198.51.100.2"])]]))
|
||||
assert.deepEqual(wildcard[0]?.observedNextHops, [{ip:"10.200.100.54",serverId:"9"}])
|
||||
|
||||
for (const read of [async () => { throw Error("forbidden") }, async () => ({ message:"invalid response" })]) {
|
||||
const observed = await readGreEnrichment(read, "GRE", ["address","interface"])
|
||||
const [base] = observedGrePeers([{...jh, observedAddresses:observed.map(a => a.address!),localInnerIp:"10.0.0.1/30"}],hosts,new Map())
|
||||
assert.equal(base?.localInnerIp,"10.0.0.1/30")
|
||||
assert.deepEqual(base?.observedNextHops,[])
|
||||
}
|
||||
|
||||
const staleDns = observedGrePeers([
|
||||
{...jh, remoteAddress:"exit.example",currentRemoteAddress:"192.0.2.11"}, exit,
|
||||
], new Map([["7","198.51.100.7"],["9","exit.example"]]), new Map())
|
||||
assert.ok(staleDns.every(t => !t.observedNextHops.length))
|
||||
@@ -1,3 +1,5 @@
|
||||
import { ipv4ToInt, parseCidrV4 } from "./traffic-flow-ip.js"
|
||||
|
||||
// No database or RouterOS imports: this boundary can be checked with injected readers.
|
||||
type PathServer = {id: number | string; type: string; enabled: boolean}
|
||||
export async function collectConfirmedInternetPath<S extends PathServer, G, F, P, R extends object, W extends object>(sampledAt: string, readers: {
|
||||
@@ -36,3 +38,50 @@ export function mapStoredInternetPathResponse(row: { payloadJson: unknown; sampl
|
||||
if (typeof row.sampledAt !== "string" || !row.sampledAt.trim()) throw new Error("Сохранённая дата Internet path повреждена")
|
||||
return { snapshot: readStoredInternetPathPayload(row.payloadJson), sampledAt: new Date(row.sampledAt).toISOString() }
|
||||
}
|
||||
|
||||
|
||||
// Enrichment may be unauthorized on otherwise observable GRE routers.
|
||||
export async function readGreEnrichment(read: () => Promise<unknown>, source: string, fields: string[]) {
|
||||
try { return readInternetPathRows(await read(), source, fields) } catch { return [] }
|
||||
}
|
||||
|
||||
// A shared point-to-point subnet and matching outer peers identify the exact next hop on this exporter.
|
||||
export function observedGrePeers<T extends {serverId: string; enabled: boolean; localAddress: string; remoteAddress: string; currentRemoteAddress?: string; localInnerIp?: string; observedAddresses: string[]}>(
|
||||
tunnels: T[], hosts: Map<string, string>, assignedAddresses: Map<string, Set<string>>,
|
||||
) {
|
||||
const subnets = new Map<string, Array<{ tunnel: T; ip: string }>>()
|
||||
const peers = new Map<T, Array<{ ip: string; serverId: string }>>()
|
||||
for (const tunnel of tunnels) {
|
||||
if (!tunnel.enabled) continue
|
||||
for (const cidr of tunnel.observedAddresses) {
|
||||
if (!/^[0-9.]+\/(30|31)$/.test(cidr)) continue
|
||||
const parsed = parseCidrV4(cidr)
|
||||
const ip = cidr.split("/")[0]!
|
||||
if (!parsed || (parsed.prefixLen === 30 && (ipv4ToInt(ip) === parsed.net || ipv4ToInt(ip) === parsed.net + 3))) continue
|
||||
const key = parsed.net + "/" + parsed.prefixLen
|
||||
const entries = subnets.get(key) ?? []
|
||||
entries.push({ tunnel, ip })
|
||||
subnets.set(key, entries)
|
||||
}
|
||||
}
|
||||
function pointsTo(local: T, peer: T) {
|
||||
const current = local.currentRemoteAddress?.trim().toLowerCase()
|
||||
const remote = current && current !== "0.0.0.0" ? current : local.remoteAddress.trim().toLowerCase()
|
||||
return remote && remote !== "0.0.0.0" && (remote === peer.localAddress.toLowerCase() ||
|
||||
remote === hosts.get(peer.serverId)?.toLowerCase() || assignedAddresses.get(peer.serverId)?.has(remote))
|
||||
}
|
||||
for (const endpoints of subnets.values()) {
|
||||
if (endpoints.length !== 2) continue
|
||||
const [a, b] = endpoints as [typeof endpoints[number], typeof endpoints[number]]
|
||||
if (a.ip === b.ip || a.tunnel.serverId === b.tunnel.serverId || !pointsTo(a.tunnel, b.tunnel) || !pointsTo(b.tunnel, a.tunnel)) continue
|
||||
for (const [local, peer] of [[a, b], [b, a]] as const) {
|
||||
const matches = peers.get(local.tunnel) ?? []
|
||||
matches.push({ ip: peer.ip, serverId: peer.tunnel.serverId })
|
||||
peers.set(local.tunnel, matches)
|
||||
}
|
||||
}
|
||||
return tunnels.map(tunnel => {
|
||||
const { observedAddresses, ...rest } = tunnel
|
||||
return { ...rest, localInnerIp: observedAddresses[0] ?? tunnel.localInnerIp ?? "", observedNextHops: peers.get(tunnel) ?? [] }
|
||||
})
|
||||
}
|
||||
@@ -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), /истекла/)
|
||||
})
|
||||
@@ -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"
|
||||
|
||||
assertOwnedBandwidthSql();await prepareOwnedBandwidthState()
|
||||
const {pool,closePool}=await import("../db/index.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 routing=await acceptRoutingMeasurementPoolSql(ids)
|
||||
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")
|
||||
console.log("Owned automatic scheduler: "+JSON.stringify(await acceptAutomaticSchedulerSql(ids)))
|
||||
}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() }
|
||||
}
|
||||
@@ -216,7 +216,7 @@ export async function runSchedulerJobNow(jobKey: string): Promise<SchedulerRunRe
|
||||
throw new Error(`Unknown job key: ${jobKey}`)
|
||||
}
|
||||
if (!tryBeginSchedulerJob(jobKey)) {
|
||||
const err = new Error(isSchedulerJobsPaused() ? "Планировщик приостановлен для операции с базой" : "Job already running")
|
||||
const err = new Error(isSchedulerJobsPaused() ? "Планировщик приостановлен для операции с базой" : "Задача уже выполняется")
|
||||
;(err as Error & { statusCode?: number }).statusCode = 409
|
||||
if (isSchedulerJobsPaused()) (err as Error & { code?: string }).code = "SCHEDULER_PAUSED"
|
||||
throw err
|
||||
|
||||
@@ -20,7 +20,7 @@ async function getSettingsRow() {
|
||||
intervalSec: 120,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
})
|
||||
}).onConflictDoNothing({ target: serversApiPingSettings.id })
|
||||
return (await db.select().from(serversApiPingSettings).where(eq(serversApiPingSettings.id, 1)).limit(1))[0]
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import assert from "node:assert/strict"
|
||||
import { setTimeout as delay } from "node:timers/promises"
|
||||
import { MikrotikClient } from "./mikrotik.js"
|
||||
import { dispatchTerminalCommand, executeTerminalDiagnostic, parseTerminalCommand, terminalDiagnosticSchema } from "./terminal-diagnostics.js"
|
||||
import { dispatchTerminalCommand, executeTerminalDiagnostic, parseTerminalCommand, readTerminalInterfaceCounters, terminalDiagnosticSchema, terminalInterfaceCountersSchema } from "./terminal-diagnostics.js"
|
||||
import { withTerminalDiagnosticClient } from "./terminal-diagnostic-client.js"
|
||||
import { createTerminalDiagnosticFixture, terminalDiagnosticCases } from "../test/terminal-diagnostic-fixture.js"
|
||||
|
||||
@@ -22,6 +22,24 @@ try {
|
||||
for (const bad of [{ diagnostic: "execute", command: "/system reboot" }, { diagnostic: "interfaces", target: "host" }, { diagnostic: "logs", count: 2 }, { diagnostic: "ping" }, { diagnostic: "ping", target: "192.0.2.1", count: 21 }, { diagnostic: "logs", limit: 201 }]) assert.equal(terminalDiagnosticSchema.safeParse(bad).success, false)
|
||||
for (const bad of ["/system reboot", ":execute /system resource print", "ip address print;system reboot", "log print limit=0", "ping host count=1junk"]) assert.throws(() => parseTerminalCommand(bad))
|
||||
const oldInterfaces = fixture.payloads["/interface"]
|
||||
fixture.payloads["/interface"] = [
|
||||
{ name: "ether-a", running: "true", "rx-byte": "18446744073709551615", "rx-error": "0", "tx-error": "-1", "rx-drop": "2", "link-downs": "3", "last-link-down-time": "2026-01-01 00:00:00", comment: endpoint.password },
|
||||
{ name: "ether-b", "tx-queue-drop": "4" },
|
||||
]
|
||||
const counters = (args: object) => withTerminalDiagnosticClient(endpoint, { authorize }, native => readTerminalInterfaceCounters(native,
|
||||
terminalInterfaceCountersSchema.parse({ diagnostic: "interface_counters", ...args }), value => value))
|
||||
const first = await counters({ limit: 1 })
|
||||
assert.equal(first.total, 2)
|
||||
assert.equal(first.truncated, true)
|
||||
assert.equal(first.rows.length, 1)
|
||||
assert.equal(first.rows[0].lastLinkDownAt, "2026-01-01 00:00:00")
|
||||
assert.equal(first.rows[0].running, true)
|
||||
assert.deepEqual(first.rows[0].counters, { rxBytes: "18446744073709551615", txBytes: null, rxPackets: null, txPackets: null, rxDrops: "2", txDrops: null, txQueueDrops: null, rxErrors: "0", txErrors: null, linkDowns: "3" })
|
||||
assert.equal(first.resetHistoryAvailable, false)
|
||||
assert.ok(first.routerUptime)
|
||||
assert.ok(!JSON.stringify(first).includes(endpoint.password))
|
||||
assert.equal((await counters({ interface: "ether-b" })).rows[0].counters.txQueueDrops, "4")
|
||||
assert.equal(terminalInterfaceCountersSchema.safeParse({ diagnostic: "interface_counters", limit: 51 }).success, false)
|
||||
fixture.payloads["/interface"] = Array.from({ length: 1001 }, () => ({ name: "x" }))
|
||||
await assert.rejects(withTerminalDiagnosticClient(endpoint, { authorize }, native => native.getInterfaces()))
|
||||
fixture.payloads["/interface"] = [{ name: "x".repeat(1048577) }]
|
||||
|
||||
@@ -236,6 +236,46 @@ export const terminalDiagnosticSchema = z.object({
|
||||
})
|
||||
export type TerminalDiagnostic = z.infer<typeof terminalDiagnosticSchema>
|
||||
export type TerminalDiagnosticClient = Pick<MikrotikClient, "getIpAddresses" | "getInterfaces" | "getResource" | "getIdentity" | "getIpRoutes" | "getFirewallFilters" | "getBgpSessions" | "getOspfNeighbors" | "getOspfAreas" | "getOspfInstances" | "getOspfInterfaceTemplates" | "getBfdSessions" | "getLogs" | "ping">
|
||||
export const terminalInterfaceCountersSchema = z.object({
|
||||
diagnostic: z.literal("interface_counters"),
|
||||
interface: z.string().min(1).max(128).regex(/^[^\p{Cc}]+$/u).optional(),
|
||||
limit: z.number().int().min(1).max(50).default(20),
|
||||
}).strict()
|
||||
|
||||
export async function readTerminalInterfaceCounters(
|
||||
client: Pick<TerminalDiagnosticClient, "getInterfaces" | "getResource">,
|
||||
input: z.infer<typeof terminalInterfaceCountersSchema>,
|
||||
protect: (value: string) => string,
|
||||
) {
|
||||
const [interfaces, resource] = await Promise.all([client.getInterfaces(), client.getResource()])
|
||||
const properties = {
|
||||
rxBytes: "rx-byte", txBytes: "tx-byte", rxPackets: "rx-packet", txPackets: "tx-packet",
|
||||
rxDrops: "rx-drop", txDrops: "tx-drop", txQueueDrops: "tx-queue-drop",
|
||||
rxErrors: "rx-error", txErrors: "tx-error", linkDowns: "link-downs",
|
||||
} as const
|
||||
const text = (value: unknown, max: number) =>
|
||||
typeof value === "string" && value.length <= max && /^[^\p{Cc}]+$/u.test(value) ? protect(value) : null
|
||||
const counter = (value: unknown) => {
|
||||
if (typeof value !== "string" || !/^\d{1,20}$/.test(value) || BigInt(value) > 18446744073709551615n) return null
|
||||
return protect(value) === value ? value : null
|
||||
}
|
||||
const flag = (value: unknown) => value === "true" ? true : value === "false" ? false : null
|
||||
const selected = interfaces.filter(row => input.interface === undefined || row.name === input.interface)
|
||||
const rows = selected.slice(0, input.limit).map(row => {
|
||||
const native = row as typeof row & Partial<Record<(typeof properties)[keyof typeof properties] | "last-link-down-time" | "last-link-up-time", unknown>>
|
||||
const counters = Object.fromEntries(Object.entries(properties).map(([key, property]) => [key, counter(native[property])])) as Record<keyof typeof properties, string | null>
|
||||
return {
|
||||
name: text(row.name, 128), type: text(row.type, 64), running: flag(row.running), disabled: flag(row.disabled),
|
||||
counters,
|
||||
lastLinkDownAt: text(native["last-link-down-time"], 40), lastLinkUpAt: text(native["last-link-up-time"], 40),
|
||||
}
|
||||
})
|
||||
return {
|
||||
rows, total: selected.length, limit: input.limit, truncated: rows.length < selected.length,
|
||||
observedAt: new Date().toISOString(), routerUptime: text(resource.uptime, 64),
|
||||
countersAreCumulative: true, lastCounterResetAt: null, resetHistoryAvailable: false,
|
||||
}
|
||||
}
|
||||
export class ExecValidationError extends Error { readonly statusCode = 400 }
|
||||
|
||||
/** REST grammar is intentionally an allowlist, never a RouterOS script. */
|
||||
|
||||
@@ -80,7 +80,7 @@ async function getSettingsRow() {
|
||||
...trafficSettingsDefaults,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
})
|
||||
}).onConflictDoNothing({ target: trafficSettings.id })
|
||||
return readSettingsRow()
|
||||
}
|
||||
|
||||
|
||||
@@ -27,6 +27,7 @@ import { resolveIfaceName } from "./traffic-flow-ifaces.js"
|
||||
import { factIfaceAliases } from "./traffic-flow-ifindex.js"
|
||||
import { getTrafficFlowSettingsRow } from "./traffic-flow-settings.js"
|
||||
import { applicationName, flowRowMatchesFilter } from "./traffic-flow-apps.js"
|
||||
import { canonicalIp, ipv6ToInt } from "./traffic-flow-ip.js"
|
||||
import { collapseGreEspRows, dedupFlowRowsMaxBytes, flowTupleKey } from "./traffic-flow-dedup.js"
|
||||
import { enqueueRipeMisses } from "./traffic-flow-ripe.js"
|
||||
import { classifyFlowPlane, flowBps, shouldKeepPlane } from "./traffic-flow-planes.js"
|
||||
@@ -37,7 +38,8 @@ import {
|
||||
getServerCatalog,
|
||||
latestWireBps,
|
||||
loadFlowTopology,
|
||||
resolveClient,
|
||||
flowClientInterfaces,
|
||||
resolveFlowClient,
|
||||
resolveEn,
|
||||
} from "./traffic-flow-topology.js"
|
||||
|
||||
@@ -49,6 +51,7 @@ export interface FlowAnalyticsQuery {
|
||||
serverId?: number
|
||||
userId?: string
|
||||
iface?: string
|
||||
tuple?: { srcIp?: string; dstIp?: string; srcPort?: number; dstPort?: number; protocol?: number }
|
||||
/** Default true: один 5-tuple за минуту = max байт по ifaces. */
|
||||
dedup?: boolean
|
||||
/** Default true: скрыть GRE/WG между клиентами JH. */
|
||||
@@ -95,18 +98,6 @@ function bump(
|
||||
map.set(id, prev)
|
||||
}
|
||||
|
||||
async function userIfaceAllow(userId: string): Promise<Map<number, Set<string>> | null> {
|
||||
if (!userId) return null
|
||||
const binds = await flowReadDbAll<{serverId:number;interfaceName:string}>('SELECT server_id AS "serverId",interface_name AS "interfaceName" FROM user_interface_bindings WHERE user_id=?',[userId])
|
||||
const allow = new Map<number, Set<string>>()
|
||||
for (const b of binds) {
|
||||
const set = allow.get(b.serverId) ?? new Set<string>()
|
||||
set.add(b.interfaceName)
|
||||
allow.set(b.serverId, set)
|
||||
}
|
||||
return allow
|
||||
}
|
||||
|
||||
function seriesFromRows(rows: PendingFlowRow[], minutes: number, direction: (row: PendingFlowRow) => "rx" | "tx" | "both" | null, now = Date.now()) {
|
||||
const slots = Math.min(60, Math.max(5, minutes))
|
||||
const slotMs = (minutes * 60_000) / slots
|
||||
@@ -182,6 +173,7 @@ function analyticsQueryKey(q: FlowAnalyticsQuery): string {
|
||||
serverId: q.serverId ?? null,
|
||||
userId: q.userId ?? null,
|
||||
iface: q.iface ?? null,
|
||||
tuple: q.tuple ?? null,
|
||||
dedup: q.dedup !== false,
|
||||
excludeMesh: q.excludeMesh !== false,
|
||||
excludeOverlay: q.excludeOverlay !== false,
|
||||
@@ -241,7 +233,7 @@ async function buildFlowAnalyticsUncached(q: FlowAnalyticsQuery, scope?: ScopedF
|
||||
const excludeOverlay = q.excludeOverlay !== false
|
||||
await authorize()
|
||||
const topo = await loadFlowTopology(scope?.serverIds, authorize)
|
||||
const allow = q.userId ? scope ? new Map([...topo.clientByIface.values()].filter(b => b.userId === q.userId).map(b => [b.serverId, new Set([...topo.clientByIface.values()].filter(other => other.userId === q.userId && other.serverId === b.serverId).map(other => other.interfaceName))])) : await userIfaceAllow(q.userId) : null
|
||||
const allow = q.userId ? flowClientInterfaces(topo, q.userId) : null
|
||||
if (scope && q.userId && !allow?.size) throw new Error("Пользователь не найден в разрешённой топологии")
|
||||
|
||||
if (!scope) refreshFlowCatalogInBackground()
|
||||
@@ -253,7 +245,21 @@ async function buildFlowAnalyticsUncached(q: FlowAnalyticsQuery, scope?: ScopedF
|
||||
const ingress = matchesIngress(row), egress = matchesEgress(row)
|
||||
return ingress === egress ? null : ingress ? "rx" : "tx"
|
||||
}
|
||||
const selected = ifaceFilter || allow ? raw.filter(row => matchesIngress(row) || matchesEgress(row)) : raw
|
||||
const visible = ifaceFilter || allow ? raw.filter(row => (matchesIngress(row) || matchesEgress(row)) &&
|
||||
(!q.userId || resolveFlowClient(topo, row.serverId, resolveIfaceName(row.serverId, row.inIface).name, resolveIfaceName(row.serverId, row.outIface).name)?.userId === q.userId)) : raw
|
||||
const tuple = q.tuple
|
||||
const ipKey = (value: string) => {
|
||||
const ip = canonicalIp(value)
|
||||
return ip.includes(":") ? ipv6ToInt(ip) ?? ip : ip
|
||||
}
|
||||
const src = tuple?.srcIp === undefined ? undefined : ipKey(tuple.srcIp)
|
||||
const dst = tuple?.dstIp === undefined ? undefined : ipKey(tuple.dstIp)
|
||||
const selected = tuple ? visible.filter(row =>
|
||||
(src === undefined || src === ipKey(row.src)) &&
|
||||
(dst === undefined || dst === ipKey(row.dst)) &&
|
||||
(tuple.srcPort === undefined || tuple.srcPort === row.srcPort) &&
|
||||
(tuple.dstPort === undefined || tuple.dstPort === row.dstPort) &&
|
||||
(tuple.protocol === undefined || tuple.protocol === row.proto)) : visible
|
||||
const { rows, espDirections } = collapseGreEspRows(selected, ifaceFilter ? interfaceDirection : serverDirection)
|
||||
const previousMinute = new Date(Math.floor(now / 60_000) * 60_000 - 60_000).toISOString()
|
||||
const ifacesForWire = new Set<string>()
|
||||
@@ -370,7 +376,7 @@ async function buildFlowAnalyticsUncached(q: FlowAnalyticsQuery, scope?: ScopedF
|
||||
inIface: resolved.name,
|
||||
outIface: outResolved.name,
|
||||
}, topo.plane)
|
||||
const client = resolveClient(topo, r.serverId, resolved.name) ?? resolveClient(topo, r.serverId, outResolved.name)
|
||||
const client = resolveFlowClient(topo, r.serverId, resolved.name, outResolved.name)
|
||||
const en = resolveEn(topo, r.nextHop, outResolved.name)
|
||||
const outIface = outResolved.name === "—" ? "" : outResolved.name
|
||||
const pathKey = JSON.stringify([client?.userId ?? "unknown", r.serverId, en?.id ?? "", dst, resolved.name, outIface,
|
||||
@@ -489,7 +495,7 @@ async function buildFlowAnalyticsUncached(q: FlowAnalyticsQuery, scope?: ScopedF
|
||||
const topCategory = topLabel(categories)
|
||||
|
||||
const ringServer = q.serverId ?? (matched[0]?.serverId ?? 0)
|
||||
const ring = ringServer && !ifaceFilter && !allow && excludeOverlay ? getRingMbps(ringServer) : null
|
||||
const ring = ringServer && !ifaceFilter && !allow && !tuple && excludeOverlay ? getRingMbps(ringServer) : null
|
||||
|
||||
// The live ring covers about one minute; historical charts must use the requested window.
|
||||
const fromBuckets = seriesFromRows(working, q.minutes, row => {
|
||||
@@ -546,11 +552,11 @@ async function buildFlowAnalyticsUncached(q: FlowAnalyticsQuery, scope?: ScopedF
|
||||
const bpsNow = ring
|
||||
? (!fromBuckets.undirectedBytes && (ring.rxNow + ring.txNow) * 1_000_000) || (totalBytes * 8) / windowSec
|
||||
: (recentBytes * 8) / 60 || (totalBytes * 8) / windowSec
|
||||
const greNames = ringServer ? enGreIfaceNames(topo, ringServer, [...ifacesForWire]) : []
|
||||
const greNames = ringServer && !q.userId ? enGreIfaceNames(topo, ringServer, [...ifacesForWire]) : []
|
||||
await authorize()
|
||||
const wire = ringServer ? await latestWireBps(ringServer, greNames, Boolean(scope)) : { bps: 0, bytes: 0 }
|
||||
await authorize()
|
||||
const admittedTotals = q.serverId !== undefined && !q.userId
|
||||
const admittedTotals = q.serverId !== undefined && !q.userId && !tuple
|
||||
? await readAdmittedFlowTotals(q.serverId, ifaceFilter, q.minutes, now)
|
||||
: undefined
|
||||
|
||||
@@ -660,32 +666,26 @@ export async function listFlowExporters(minutes: number): Promise<FlowExportersD
|
||||
}
|
||||
}
|
||||
|
||||
export async function listFlowClients(minutes: number): Promise<{ clients: { id: string; name: string; subtitle: string; site: string; country: string; status: "online" | "offline" | "degraded"; rxNow: number; txNow: number; sessions: number; rxSeries: number[]; txSeries: number[]; bytes: number; }[]; }> {
|
||||
const inputs = await readFlowClientInputs(minutes)
|
||||
const users = inputs.users
|
||||
const binds = users.flatMap(user => user.bindings.map(binding => ({ ...binding, userId: user.id })))
|
||||
const byUser = new Map<string, typeof binds>()
|
||||
for (const b of binds) {
|
||||
const list = byUser.get(b.userId) ?? []
|
||||
list.push(b)
|
||||
byUser.set(b.userId, list)
|
||||
export async function listFlowClients(minutes: number): Promise<{ clients: FlowEntityCard[] }> {
|
||||
const [inputs, topo] = await Promise.all([readFlowClientInputs(minutes), loadFlowTopology()])
|
||||
const byUser = new Map<string, PendingFlowRow[]>()
|
||||
for (const row of inputs.window.rows) {
|
||||
const inIface = resolveIfaceName(row.serverId, row.inIface).name
|
||||
const outIface = resolveIfaceName(row.serverId, row.outIface).name
|
||||
const client = resolveFlowClient(topo, row.serverId, inIface, outIface)
|
||||
if (!client || classifyFlowPlane({ ...row, inIface, outIface }, topo.plane) !== "payload") continue
|
||||
const rows = byUser.get(client.userId) ?? []
|
||||
rows.push(row)
|
||||
byUser.set(client.userId, rows)
|
||||
}
|
||||
const rows = inputs.window.rows
|
||||
const clients: FlowEntityCard[] = []
|
||||
for (const u of users) {
|
||||
const userBinds = byUser.get(u.id) ?? []
|
||||
if (userBinds.length === 0) continue
|
||||
const allow = new Map<number, Set<string>>()
|
||||
for (const b of userBinds) {
|
||||
const set = allow.get(b.serverId) ?? new Set<string>()
|
||||
set.add(b.interfaceName)
|
||||
allow.set(b.serverId, set)
|
||||
}
|
||||
for (const u of inputs.users) {
|
||||
const allow = flowClientInterfaces(topo, u.id)
|
||||
const namedBindings = u.bindings.filter(binding => allow.get(binding.serverId)?.has(binding.interfaceName)).length
|
||||
const bound = (id: number, iface: string) => {
|
||||
const names = allow.get(id)
|
||||
return names?.has(iface) || names?.has(resolveIfaceName(id, iface).name)
|
||||
return allow.get(id)?.has(resolveIfaceName(id, iface).name)
|
||||
}
|
||||
const matched = rows.filter(r => bound(r.serverId, r.inIface) || bound(r.serverId, r.outIface))
|
||||
const matched = dedupFlowRowsMaxBytes(byUser.get(u.id) ?? [])
|
||||
const rates = seriesFromRows(matched, minutes, r => {
|
||||
if (!bound(r.serverId, r.inIface)) return "rx"
|
||||
return bound(r.serverId, r.outIface) ? "both" : "tx"
|
||||
@@ -694,18 +694,18 @@ export async function listFlowClients(minutes: number): Promise<{ clients: { id:
|
||||
id: u.id,
|
||||
name: u.login,
|
||||
subtitle: u.name || u.login,
|
||||
site: `${userBinds.length} ifaces`,
|
||||
site: namedBindings < u.bindings.length ? `IPFIX: ${namedBindings}/${u.bindings.length} привязок` : `${namedBindings} инт.`,
|
||||
country: "UN",
|
||||
status: u.active ? "online" : "offline",
|
||||
rxNow: rates.rxNow,
|
||||
txNow: rates.txNow,
|
||||
rxNow: matched.length ? rates.rxNow : null,
|
||||
txNow: matched.length ? rates.txNow : null,
|
||||
sessions: matched.length,
|
||||
rxSeries: rates.rx,
|
||||
txSeries: rates.tx,
|
||||
rxSeries: matched.length ? rates.rx : [],
|
||||
txSeries: matched.length ? rates.tx : [],
|
||||
bytes: matched.reduce((sum, row) => sum + row.bytes, 0),
|
||||
})
|
||||
}
|
||||
clients.sort((a, b) => b.rxNow - a.rxNow)
|
||||
clients.sort((a, b) => (b.rxNow ?? -1) - (a.rxNow ?? -1))
|
||||
return { clients }
|
||||
}
|
||||
|
||||
|
||||
@@ -36,6 +36,7 @@ const WELL_KNOWN: Record<string, string> = {
|
||||
"17:853": "DNS",
|
||||
"6:853": "DNS",
|
||||
"17:51820": "WireGuard",
|
||||
"17:13231": "WireGuard",
|
||||
"17:13232": "WireGuard",
|
||||
"17:51821": "WireGuard",
|
||||
"17:4789": "VXLAN",
|
||||
@@ -63,6 +64,13 @@ export function applicationName(proto: number, dstPort: number, srcPort = 0): st
|
||||
return WELL_KNOWN[dstKey] ?? WELL_KNOWN[srcKey] ?? `${protoName(proto)}/${dstPort || srcPort || "—"}`
|
||||
}
|
||||
|
||||
/** Port hints keep a conventional service port separate from the observed transport. */
|
||||
export function flowPortApplication(proto: number, port: number): string | null {
|
||||
if (proto === 6 && port === 853) return "DNS over TLS"
|
||||
if (proto === 17 && port === 853) return "Защищённый DNS"
|
||||
return port > 0 ? WELL_KNOWN[`${proto}:${port}`] ?? null : null
|
||||
}
|
||||
|
||||
export interface FlowMatchQuery {
|
||||
serverId?: number
|
||||
userId?: string
|
||||
|
||||
@@ -46,6 +46,8 @@ assert.equal(isNamedInternetService("DNS", "DNS"), false)
|
||||
assert.equal(mapServiceNodeId("AWS"), "svc:aws")
|
||||
assert.equal(mapServiceNodeId("Cloudflare"), "svc:cloudflare")
|
||||
assert.equal(mapServiceNodeId("Прочее"), "svc:other")
|
||||
assert.notEqual(mapServiceNodeId("Видео"), mapServiceNodeId("Игры"))
|
||||
assert.notEqual(mapServiceNodeId("Microsoft Работа"), mapServiceNodeId("Microsoft Игры"))
|
||||
assert.equal(mapCountryNodeId("US"), "cc:us")
|
||||
assert.equal(mapCountryNodeId("nl"), "cc:nl")
|
||||
assert.equal(mapCountryNodeId(""), "cc:other")
|
||||
@@ -87,7 +89,12 @@ assert.equal(resolveFlowBrand("173.194.160.163", 15169, "GOOGLE", 6, 443, 51234)
|
||||
assert.equal(resolveFlowBrand("64.233.161.1", 0, "", 17, 443, 50000)?.service, "YouTube")
|
||||
assert.equal(resolveFlowBrand("64.233.161.1", 0, "", 6, 80, 50000)?.service, "Google")
|
||||
assert.equal(resolveFlowBrand("2001:4860:4860::8888", 15169, "GOOGLE", 17, 53, 53000)?.service, "Google")
|
||||
assert.equal(resolveFlowBrand("2001:4860:4860::8888", 15169, "GOOGLE", 17, 443, 50000)?.service, "YouTube")
|
||||
assert.equal(resolveFlowBrand("2001:4860:4860::8888", 15169, "GOOGLE", 17, 443, 50000)?.service, "Google")
|
||||
assert.equal(resolveFlowBrand("2001:4860:4860:0:0:0:0:8844/128", 15169, "GOOGLE", 6, 443)?.service, "Google")
|
||||
assert.equal(resolveFlowBrand("::ffff:8.8.4.4", 15169, "", 17, 443)?.service, "Google")
|
||||
assert.equal(resolveFlowBrand("2607:f8b0::123", 15169, "", 17, 443)?.service, "YouTube")
|
||||
assert.equal(resolveFlowBrand("64.233.161.1", 396982, "", 6, 443)?.service, "Google")
|
||||
assert.equal(resolveFlowBrand("64.233.161.1", 0, "", 6, 50000, 443)?.service, "Google", "443 на стороне клиента")
|
||||
|
||||
assert.equal(brandByAsn(32934)?.service, "Meta")
|
||||
assert.equal(lookupBrand("157.240.12.52", 0)?.service, "Meta")
|
||||
@@ -98,12 +105,12 @@ assert.equal(isNamedInternetService("Instagram", "Видео / стриминг"
|
||||
assert.equal(
|
||||
resolveFlowBrand("157.240.12.52", 32934, "FACEBOOK", 6, 443, 51234)?.service,
|
||||
"Instagram",
|
||||
"HTTPS на Meta front → Instagram, как YouTube на Google",
|
||||
"HTTPS в сети Meta",
|
||||
)
|
||||
assert.equal(
|
||||
resolveFlowBrand("57.144.22.192", 0, "", 17, 443, 50000)?.service,
|
||||
"Instagram",
|
||||
"cdninstagram CIDR :443 без ASN → Instagram",
|
||||
"QUIC в префиксе Meta без ASN",
|
||||
)
|
||||
assert.equal(
|
||||
resolveFlowBrand("157.240.12.52", 32934, "FACEBOOK", 6, 80, 50000)?.service,
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
import { ipInCidrV4, parseCidrV4 } from "./traffic-flow-ip.js"
|
||||
import { canonicalIp, ipInCidrV4, ipv6ToInt, parseCidrV4 } from "./traffic-flow-ip.js"
|
||||
|
||||
export const OTHER_SERVICE = "Прочее"
|
||||
|
||||
export interface BrandHit {
|
||||
service: string
|
||||
category: string
|
||||
operator?: string
|
||||
heuristic?: true
|
||||
}
|
||||
|
||||
const CDN = { category: "CDN" } as const
|
||||
@@ -12,6 +14,7 @@ const WEB = { category: "Веб" } as const
|
||||
const VIDEO = { category: "Видео / стриминг" } as const
|
||||
const GAMES = { category: "Игры" } as const
|
||||
const VOICE = { category: "Голос" } as const
|
||||
const MESSAGING = { category: "Мессенджеры" } as const
|
||||
const AI = { category: "ИИ" } as const
|
||||
const DNS = { category: "DNS" } as const
|
||||
|
||||
@@ -39,7 +42,7 @@ const TIMEWEB: BrandHit = { service: "Timeweb", ...CDN }
|
||||
const BEGET: BrandHit = { service: "Beget", ...CDN }
|
||||
const DDOS_GUARD: BrandHit = { service: "DDoS-Guard", ...CDN }
|
||||
const META: BrandHit = { service: "Meta", ...CDN }
|
||||
const INSTAGRAM: BrandHit = { service: "Instagram", ...VIDEO }
|
||||
const INSTAGRAM: BrandHit = { service: "Instagram", operator: META.service, ...VIDEO }
|
||||
|
||||
const GOOGLE: BrandHit = { service: "Google", ...WEB }
|
||||
const GITHUB: BrandHit = { service: "GitHub", ...WEB }
|
||||
@@ -54,7 +57,9 @@ const WIKIPEDIA: BrandHit = { service: "Wikipedia", ...WEB }
|
||||
const PAYPAL: BrandHit = { service: "PayPal", ...WEB }
|
||||
const SALESFORCE: BrandHit = { service: "Salesforce", ...WEB }
|
||||
|
||||
const YOUTUBE: BrandHit = { service: "YouTube", ...VIDEO }
|
||||
const YOUTUBE: BrandHit = { service: "YouTube", operator: GOOGLE.service, ...VIDEO }
|
||||
const LIKELY_YOUTUBE: BrandHit = { ...YOUTUBE, heuristic: true }
|
||||
const LIKELY_INSTAGRAM: BrandHit = { ...INSTAGRAM, heuristic: true }
|
||||
const NETFLIX: BrandHit = { service: "Netflix", ...VIDEO }
|
||||
const TWITCH: BrandHit = { service: "Twitch", ...VIDEO }
|
||||
const TIKTOK: BrandHit = { service: "TikTok", ...VIDEO }
|
||||
@@ -69,7 +74,7 @@ const ROBLOX: BrandHit = { service: "Roblox", ...GAMES }
|
||||
const UBISOFT: BrandHit = { service: "Ubisoft", ...GAMES }
|
||||
|
||||
const DISCORD: BrandHit = { service: "Discord", ...VOICE }
|
||||
const TELEGRAM: BrandHit = { service: "Telegram", ...VOICE }
|
||||
const TELEGRAM: BrandHit = { service: "Telegram", ...MESSAGING }
|
||||
const ZOOM: BrandHit = { service: "Zoom", ...VOICE }
|
||||
|
||||
const CHATGPT: BrandHit = { service: "ChatGPT", ...AI }
|
||||
@@ -222,18 +227,13 @@ const HOLDER_BRANDS: Array<{ re: RegExp; hit: BrandHit }> = [
|
||||
const NON_ISO = new Set(["EU", "AP", "ZZ", "XX", "A1", "A2", "O1"])
|
||||
|
||||
const STEAM_ASN = 32590
|
||||
const GOOGLE_FRONT_ASN = new Set([15169, 396982])
|
||||
/** AS32934 / AS63293 — Meta front (Facebook + Instagram CDN). AS54115 — WhatsApp, не Instagram. */
|
||||
const META_FRONT_ASN = new Set([32934, 63293])
|
||||
const WHATSAPP_ASN = 54115
|
||||
const GOOGLE_DNS_V6 = new Set([ipv6ToInt("2001:4860:4860::8888")!, ipv6ToInt("2001:4860:4860::8844")!])
|
||||
|
||||
function isGooglePublicDns(ip: string): boolean {
|
||||
return ipInCidrV4(ip, "8.8.8.0/24") || ipInCidrV4(ip, "8.8.4.0/24")
|
||||
}
|
||||
|
||||
function isHttpsOrQuic(proto: number, dstPort: number, srcPort: number): boolean {
|
||||
if (proto !== 6 && proto !== 17) return false
|
||||
return dstPort === 443 || srcPort === 443
|
||||
const host = canonicalIp(ip)
|
||||
if (host === "8.8.8.8" || host === "8.8.4.4") return true
|
||||
const ipv6 = host.includes(":") ? ipv6ToInt(host) : null
|
||||
return ipv6 !== null && GOOGLE_DNS_V6.has(ipv6)
|
||||
}
|
||||
|
||||
export function isIsoCountry(code: string): boolean {
|
||||
@@ -295,19 +295,10 @@ export function lookupBrand(ip: string, asn: number): BrandHit | null {
|
||||
return brandByCidr(ip) || brandByAsn(asn)
|
||||
}
|
||||
|
||||
function isGoogleFront(asn: number, cidrBrand: BrandHit | null, asnBrand: BrandHit | null): boolean {
|
||||
return GOOGLE_FRONT_ASN.has(asn) || cidrBrand?.service === "Google" || asnBrand?.service === "Google"
|
||||
}
|
||||
|
||||
function isInstagramFront(asn: number, cidrBrand: BrandHit | null, asnBrand: BrandHit | null): boolean {
|
||||
if (asn === WHATSAPP_ASN) return false
|
||||
return META_FRONT_ASN.has(asn) || cidrBrand?.service === "Meta" || asnBrand?.service === "Meta"
|
||||
}
|
||||
|
||||
/**
|
||||
* Cloudflare CIDR бьёт holder (витрина на CF не становится Steam).
|
||||
* Holder (YouTube / Instagram и др.) бьёт остальные CIDR/ASN.
|
||||
* HTTPS/QUIC на Google front → YouTube (кроме 8.8.8.8); на Meta front → Instagram (кроме WhatsApp ASN).
|
||||
* На порту 443 интернет-узла общие сети Google и Meta дают вероятную атрибуцию.
|
||||
* Порты Steam — только AS32590 и не выше Cloudflare CIDR.
|
||||
*/
|
||||
export function resolveFlowBrand(
|
||||
@@ -323,13 +314,12 @@ export function resolveFlowBrand(
|
||||
const holderBrand = brandByHolder(holder)
|
||||
if (holderBrand) return holderBrand
|
||||
const asnBrand = brandByAsn(asn)
|
||||
if (!isGooglePublicDns(ip) && isHttpsOrQuic(proto, dstPort, srcPort) && isGoogleFront(asn, cidrBrand, asnBrand)) {
|
||||
return YOUTUBE
|
||||
}
|
||||
if (isHttpsOrQuic(proto, dstPort, srcPort) && isInstagramFront(asn, cidrBrand, asnBrand)) {
|
||||
return INSTAGRAM
|
||||
}
|
||||
const fromLookup = cidrBrand || asnBrand
|
||||
if (asnBrand === YOUTUBE && cidrBrand === GOOGLE) return YOUTUBE
|
||||
if ((proto === 6 || proto === 17) && dstPort === 443) {
|
||||
if (fromLookup === GOOGLE && (!asn || asn === 15169) && !isGooglePublicDns(ip)) return LIKELY_YOUTUBE
|
||||
if (fromLookup === META && (!asn || asn === 32934 || asn === 63293)) return LIKELY_INSTAGRAM
|
||||
}
|
||||
if (fromLookup) return fromLookup
|
||||
if (asn === STEAM_ASN && isSteamGamePort(proto, dstPort, srcPort)) return STEAM
|
||||
return null
|
||||
@@ -358,6 +348,7 @@ export function isNamedInternetService(service: string, category: string): boole
|
||||
export function mapServiceNodeId(label: string): string {
|
||||
const raw = label.trim()
|
||||
if (raw === OTHER_SERVICE) return "svc:other"
|
||||
if (/[^\x00-\x7f]/.test(raw)) return `svc:label:${encodeURIComponent(raw.normalize("NFC").toLowerCase())}`
|
||||
const slug = raw
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9]+/g, "-")
|
||||
|
||||
@@ -8,14 +8,18 @@ for (const value of [-1, NaN, Infinity, "bad", "1.5", "9007199254740992", null,
|
||||
assert.equal(flowCounter("0"), 0); assert.equal(flowCounterSum([0, 5, 10]), 15)
|
||||
assert.throws(() => flowCounterSum([Number.MAX_SAFE_INTEGER, 1]))
|
||||
const row = { serverId: 1, bytes: 1000, packets: 10, inIface: "client-vlan", bucketAt: "2026-10-19T00:00:00Z" } as PendingFlowRow
|
||||
const user: FlowClientInput = { id: "u", login: "user", name: "Name", active: true, bindingCount: 2, selectedBindingCount: 1, bindings: [{ serverId: 1, interfaceName: "client-vlan", peerSpecific: false }] }
|
||||
const user: FlowClientInput = { id: "u", login: "user", name: "Name", active: true, bindingCount: 2, selectedBindingCount: 1, bindings: [{ serverId: 1, interfaceName: "client-vlan", peerSpecific: false, attributable: true }] }
|
||||
const observed = observeFlowClient(user, [row, { ...row, inIface: "2", bytes: 9999 }, { ...row, serverId: 2, bytes: 8888 }], 5)
|
||||
assert.equal(observed.ingressNamedRowsBytes, 1000); assert.equal(observed.ingressNamedRowCount, 1)
|
||||
assert.equal(observed.ifIndexRowsNotAttributed, 1); assert.equal(observed.completeSourceSet, false); assert.equal(observed.completeAttribution, false)
|
||||
assert.equal(observed.availability, "unknown"); assert.equal(observed.rxMbps, null); assert.equal(observed.txMbps, null); assert.equal(observed.historicalOwnershipVerified, false)
|
||||
assert.equal(observeFlowClient(user, [row], 5).completeAttribution, false)
|
||||
const peer = observeFlowClient({ ...user, bindings: [{ ...user.bindings[0], peerSpecific: true }] }, [row], 5)
|
||||
const peer = observeFlowClient({ ...user, bindings: [{ ...user.bindings[0], peerSpecific: true, attributable: false }] }, [row], 5)
|
||||
assert.equal(peer.ingressNamedRowsBytes, null); assert.equal(peer.peerBindingsNotAttributed, 1)
|
||||
const exclusivePeer = observeFlowClient({ ...user, bindingCount: 1, bindings: [{ ...user.bindings[0], peerSpecific: true }] }, [row], 5)
|
||||
assert.equal(exclusivePeer.ingressNamedRowsBytes, 1000)
|
||||
assert.equal(exclusivePeer.peerBindingsNotAttributed, 0)
|
||||
assert.equal(exclusivePeer.completeAttribution, true)
|
||||
assert.equal(observeFlowClient({ ...user, active: false }, [], 5).availability, "unknown")
|
||||
const source = { id: 1, name: "R", site: "site", country: "RU", host: "192.0.2.1", type: "home-router", enabled: false }
|
||||
const exporter = observeFlowExporter({ catalog: { list: [source], byId: new Map([[1, source]]) }, configuredIds: new Set([1]), configurationMembershipVerified: true, window: { rows: [row], since: "", until: "", topRowsPerBucketLimit: 20 } }, 1, 5)
|
||||
|
||||
@@ -3,7 +3,7 @@ import { flowCounter, flowCounterSum } from "./traffic-flow-observed-values.js"
|
||||
export { flowCounter, flowCounterSum } from "./traffic-flow-observed-values.js"
|
||||
import { listStoredFlowRows, type PendingFlowRow } from "./traffic-flow-ingest.js"
|
||||
import { getTrafficFlowSettingsRow } from "./traffic-flow-settings.js"
|
||||
import { getServerCatalog } from "./traffic-flow-topology.js"
|
||||
import { flowBindingAttributionSql, getServerCatalog } from "./traffic-flow-topology.js"
|
||||
import { observeFlowRing } from "./traffic-flow-engine.js"
|
||||
|
||||
const fail = (message: string) => Object.assign(new Error(message), { statusCode: 502 })
|
||||
@@ -39,7 +39,7 @@ export async function readFlowExporterInputs(minutes: number, serverIds?: readon
|
||||
}
|
||||
export interface FlowClientInput {
|
||||
id: string; login: string; name: string; active: boolean; bindingCount: number; selectedBindingCount: number;
|
||||
bindings: { serverId: number; interfaceName: string; peerSpecific: boolean }[];
|
||||
bindings: { serverId: number; interfaceName: string; peerSpecific: boolean; attributable: boolean }[];
|
||||
}
|
||||
/** Eligibility, hidden-binding exclusion, paging and selected bindings use one
|
||||
* SQL statement/snapshot. No hidden user or binding is deserialized in Node. */
|
||||
@@ -57,7 +57,8 @@ export async function readFlowClientInputs(minutes: number, options?: { serverId
|
||||
SELECT p.*,
|
||||
(SELECT count(*) FROM user_interface_bindings b WHERE b.user_id=p.id) AS "bindingCount",
|
||||
(SELECT count(*) FROM user_interface_bindings b WHERE b.user_id=p.id AND ($1::bigint[] IS NULL OR b.server_id=ANY($1))) AS "selectedBindingCount",
|
||||
COALESCE((SELECT jsonb_agg(jsonb_build_object('serverId',b.server_id,'interfaceName',b.interface_name,'peerSpecific',b.peer_public_key<>''))
|
||||
COALESCE((SELECT jsonb_agg(jsonb_build_object('serverId',b.server_id,'interfaceName',b.interface_name,
|
||||
'peerSpecific',b.peer_public_key<>'','attributable',(${flowBindingAttributionSql})))
|
||||
FROM (SELECT b.* FROM user_interface_bindings b WHERE b.user_id=p.id AND ($1::bigint[] IS NULL OR b.server_id=ANY($1)) ORDER BY b.id LIMIT $5) b),'[]'::jsonb) AS bindings
|
||||
FROM page p
|
||||
) SELECT (SELECT count(*) FROM eligible) AS total,COALESCE(jsonb_agg(to_jsonb(projected)),'[]'::jsonb) AS users FROM projected
|
||||
@@ -68,7 +69,7 @@ export async function readFlowClientInputs(minutes: number, options?: { serverId
|
||||
if (!user || typeof user.id !== "string" || typeof user.login !== "string" || typeof user.name !== "string" || typeof user.active !== "boolean" || !Array.isArray(user.bindings)) throw fail("Некорректный клиент NetFlow")
|
||||
const bindingCount = flowCounter(user.bindingCount), selectedBindingCount = flowCounter(user.selectedBindingCount)
|
||||
if (options && user.bindings.length > 1000 || user.bindings.length !== selectedBindingCount) throw fail("Превышен предел привязок клиента NetFlow")
|
||||
if (user.bindings.some((binding: FlowClientInput["bindings"][number]) => !Number.isSafeInteger(binding.serverId) || typeof binding.interfaceName !== "string" || typeof binding.peerSpecific !== "boolean" || selected && !selected.includes(binding.serverId))) throw fail("Некорректная привязка клиента NetFlow")
|
||||
if (user.bindings.some((binding: FlowClientInput["bindings"][number]) => !Number.isSafeInteger(binding.serverId) || typeof binding.interfaceName !== "string" || typeof binding.peerSpecific !== "boolean" || typeof binding.attributable !== "boolean" || selected && !selected.includes(binding.serverId))) throw fail("Некорректная привязка клиента NetFlow")
|
||||
return { id: user.id, login: user.login, name: user.name, active: user.active, bindingCount, selectedBindingCount, bindings: user.bindings }
|
||||
})
|
||||
return { users, total, window: await readFlowCatalogWindow(minutes, selected) }
|
||||
@@ -84,16 +85,16 @@ export function observeFlowExporter(input: Awaited<ReturnType<typeof readFlowExp
|
||||
}
|
||||
export function observeFlowClient(user: FlowClientInput, rows: PendingFlowRow[], minutes: number) {
|
||||
const interfaces = new Map<number, Set<string>>()
|
||||
for (const binding of user.bindings) if (!binding.peerSpecific) {
|
||||
for (const binding of user.bindings) if (binding.attributable) {
|
||||
const names = interfaces.get(binding.serverId) ?? new Set<string>(); names.add(binding.interfaceName); interfaces.set(binding.serverId, names)
|
||||
}
|
||||
const ifIndexRowsNotAttributed = rows.filter(row => interfaces.has(row.serverId) && /^#?\d+$/.test(row.inIface)).length
|
||||
const matched = rows.filter(row => !/^#?\d+$/.test(row.inIface) && interfaces.get(row.serverId)?.has(row.inIface))
|
||||
const attributable = user.bindings.some(binding => !binding.peerSpecific), bytes = attributable ? flowCounterSum(matched.map(row => row.bytes)) : null
|
||||
const attributable = interfaces.size > 0, bytes = attributable ? flowCounterSum(matched.map(row => row.bytes)) : null
|
||||
return { id: user.id, name: user.login, displayName: user.name, accountEnabled: user.active, availability: "unknown",
|
||||
scopedBindingCount: user.bindingCount, selectedBindingCount: user.selectedBindingCount, peerBindingsNotAttributed: user.bindings.filter(binding => binding.peerSpecific).length,
|
||||
completeSourceSet: user.bindingCount === user.selectedBindingCount, completeAttribution: user.bindingCount === user.selectedBindingCount && user.bindings.every(binding => !binding.peerSpecific) && ifIndexRowsNotAttributed === 0,
|
||||
ifIndexRowsNotAttributed, historicalOwnershipVerified: false, attribution: "current-named-whole-interface-bindings",
|
||||
scopedBindingCount: user.bindingCount, selectedBindingCount: user.selectedBindingCount, peerBindingsNotAttributed: user.bindings.filter(binding => binding.peerSpecific && !binding.attributable).length,
|
||||
completeSourceSet: user.bindingCount === user.selectedBindingCount, completeAttribution: user.bindingCount === user.selectedBindingCount && user.bindings.every(binding => binding.attributable) && ifIndexRowsNotAttributed === 0,
|
||||
ifIndexRowsNotAttributed, historicalOwnershipVerified: false, attribution: "current exclusive interface bindings, including confirmed single-peer WireGuard",
|
||||
ingressNamedRowsBytes: bytes, ingressNamedRowCount: attributable ? matched.length : null,
|
||||
ingressNamedRowsMeanMbps: bytes === null ? null : bytes * 8 / (minutes * 60) / 1000000,
|
||||
serverContextFlowRing: user.bindings.length ? { serverId: user.bindings[0].serverId, scope: "server-payload; not per-client", ...observeFlowRing(user.bindings[0].serverId) } : null,
|
||||
|
||||
@@ -1,16 +1,25 @@
|
||||
import assert from "node:assert/strict"
|
||||
import { applicationName } from "./traffic-flow-apps.js"
|
||||
import { applicationName, flowPortApplication } from "./traffic-flow-apps.js"
|
||||
import { classifyFlowDst, disableCatalogFetchForTests, resetFlowCatalogForTests, seedFlowCatalogForTests } from "./traffic-flow-classify.js"
|
||||
|
||||
disableCatalogFetchForTests()
|
||||
resetFlowCatalogForTests()
|
||||
seedFlowCatalogForTests({
|
||||
cidrs: [{ cidr: "192.0.2.0/24", purpose: "steam-gaming" }],
|
||||
cidrs: [{ cidr: "192.0.2.0/24", purpose: "steam-gaming" },
|
||||
{ cidr: "198.51.100.0/25", purpose: "Игры" },
|
||||
{ cidr: "198.51.100.128/25", purpose: "Видео / стриминг" },
|
||||
{ cidr: "173.194.0.0/16", purpose: "GOOGLE" },
|
||||
{ cidr: "173.194.1.0/24", purpose: "Work" },
|
||||
{ cidr: "57.144.0.0/16", purpose: "Meta" },
|
||||
{ cidr: "203.0.113.128/25", purpose: "main" }],
|
||||
})
|
||||
|
||||
const hit = classifyFlowDst("192.0.2.10", 6, 443, 50000, null)
|
||||
assert.equal(hit.category, "Игры")
|
||||
assert.equal(hit.service, "steam-gaming")
|
||||
assert.equal(hit.basis, "catalog")
|
||||
assert.equal(classifyFlowDst("198.51.100.10", 6, 443, 50000, null).category, "Игры")
|
||||
assert.equal(classifyFlowDst("198.51.100.150", 6, 443, 50000, null).category, "Видео / стриминг")
|
||||
|
||||
const miss = classifyFlowDst("203.0.113.9", 17, 53, 53000, null)
|
||||
assert.equal(miss.category, "DNS")
|
||||
@@ -33,11 +42,11 @@ const google = classifyFlowDst("173.194.160.163", 6, 443, 1, {
|
||||
ok: true,
|
||||
fetchedAt: Date.now(),
|
||||
})
|
||||
assert.equal(google.service, "YouTube")
|
||||
assert.equal(google.category, "Видео / стриминг")
|
||||
assert.deepEqual(google, { service: "YouTube", category: "Видео / стриминг", basis: "heuristic" })
|
||||
assert.equal(classifyFlowDst("173.194.1.1", 17, 443, 50000, null).service, "Work")
|
||||
|
||||
const googleCidr = classifyFlowDst("173.194.151.65", 6, 80, 50000, null)
|
||||
assert.equal(googleCidr.service, "Google")
|
||||
assert.equal(googleCidr.service, "GOOGLE")
|
||||
assert.equal(googleCidr.category, "Веб")
|
||||
|
||||
const youtube = classifyFlowDst("173.194.160.163", 6, 443, 1, {
|
||||
@@ -52,6 +61,8 @@ const youtube = classifyFlowDst("173.194.160.163", 6, 443, 1, {
|
||||
})
|
||||
assert.equal(youtube.service, "YouTube")
|
||||
assert.equal(youtube.category, "Видео / стриминг")
|
||||
assert.equal(youtube.basis, "network")
|
||||
assert.equal(classifyFlowDst("208.65.153.1", 17, 443, 50000, null).basis, "network")
|
||||
|
||||
const valve = classifyFlowDst("203.0.113.40", 17, 27015, 50000, {
|
||||
prefix: "203.0.113.0/24",
|
||||
@@ -115,8 +126,8 @@ const googleCloud = classifyFlowDst("203.0.113.43", 6, 443, 1, {
|
||||
ok: true,
|
||||
fetchedAt: Date.now(),
|
||||
})
|
||||
assert.equal(googleCloud.service, "YouTube")
|
||||
assert.equal(googleCloud.category, "Видео / стриминг")
|
||||
assert.equal(googleCloud.service, "Google")
|
||||
assert.equal(googleCloud.category, "Веб")
|
||||
|
||||
const gre = classifyFlowDst("198.51.100.1", 47, 0, 0, null)
|
||||
assert.equal(gre.service, "GRE")
|
||||
@@ -142,8 +153,10 @@ const dnsGoogle = classifyFlowDst("8.8.8.8", 17, 53, 53000, {
|
||||
ok: true,
|
||||
fetchedAt: Date.now(),
|
||||
})
|
||||
assert.equal(dnsGoogle.service, "Google")
|
||||
assert.notEqual(dnsGoogle.service, "Прочее")
|
||||
assert.equal(dnsGoogle.service, "DNS")
|
||||
assert.deepEqual(classifyFlowDst("104.18.35.51", 6, 853, 53000, null), {service: "DNS", category: "DNS", basis: "port"})
|
||||
assert.deepEqual(classifyFlowDst("203.0.113.10", 17, 13231, 53000, null), {service: "WireGuard", category: "Туннель", basis: "port"})
|
||||
assert.deepEqual(classifyFlowDst("203.0.113.132", 6, 443, 53000, null), {service: "Прочее", category: "Прочее", basis: "unknown"})
|
||||
const ipv6Yt = classifyFlowDst("2001:4860:4860::8888", 17, 443, 50000, {
|
||||
prefix: "2001:4860:4860::8888/128",
|
||||
asn: 15169,
|
||||
@@ -154,7 +167,7 @@ const ipv6Yt = classifyFlowDst("2001:4860:4860::8888", 17, 443, 50000, {
|
||||
ok: true,
|
||||
fetchedAt: Date.now(),
|
||||
})
|
||||
assert.equal(ipv6Yt.service, "YouTube")
|
||||
assert.equal(ipv6Yt.service, "Google")
|
||||
|
||||
const instagram = classifyFlowDst("157.240.12.52", 6, 443, 62598, {
|
||||
prefix: "157.240.0.0/16",
|
||||
@@ -166,9 +179,7 @@ const instagram = classifyFlowDst("157.240.12.52", 6, 443, 62598, {
|
||||
ok: true,
|
||||
fetchedAt: Date.now(),
|
||||
})
|
||||
assert.equal(instagram.service, "Instagram")
|
||||
assert.equal(instagram.category, "Видео / стриминг")
|
||||
assert.notEqual(instagram.service, "Meta")
|
||||
assert.deepEqual(instagram, { service: "Instagram", category: "Видео / стриминг", basis: "heuristic" })
|
||||
|
||||
const metaHttp = classifyFlowDst("157.240.12.52", 6, 80, 50000, {
|
||||
prefix: "157.240.0.0/16",
|
||||
@@ -194,14 +205,17 @@ const igHolder = classifyFlowDst("203.0.113.80", 6, 443, 1, {
|
||||
fetchedAt: Date.now(),
|
||||
})
|
||||
assert.equal(igHolder.service, "Instagram")
|
||||
assert.equal(igHolder.basis, "network")
|
||||
|
||||
const igCidr = classifyFlowDst("57.144.22.192", 17, 443, 50000, null)
|
||||
assert.equal(igCidr.service, "Instagram")
|
||||
assert.equal(igCidr.category, "Видео / стриминг")
|
||||
assert.deepEqual(igCidr, { service: "Instagram", category: "Видео / стриминг", basis: "heuristic" })
|
||||
|
||||
const esp = classifyFlowDst("198.51.100.1", 50, 0, 0, null)
|
||||
assert.equal(esp.category, "Туннель")
|
||||
assert.equal(applicationName(17, 443, 50000), "QUIC")
|
||||
assert.equal(applicationName(17, 853, 50000), "DNS")
|
||||
assert.equal(flowPortApplication(6, 853), "DNS over TLS")
|
||||
assert.equal(flowPortApplication(17, 853), "Защищённый DNS")
|
||||
assert.equal(flowPortApplication(17, 50505), null)
|
||||
|
||||
console.log("traffic-flow-classify.test.ts: ok")
|
||||
@@ -6,10 +6,12 @@ import { withActiveDatabaseRequest } from "../modules/mcp/database-request-lease
|
||||
import { ipInCidrV4, parseCidrV4 } from "./traffic-flow-ip.js"
|
||||
import type { FlowIpMeta } from "./traffic-flow-ripe.js"
|
||||
import { applicationName } from "./traffic-flow-apps.js"
|
||||
import type { FlowServiceBasis } from "@mmapp/contracts/traffic-flow"
|
||||
|
||||
export interface FlowClassification {
|
||||
service: string
|
||||
category: string
|
||||
basis: FlowServiceBasis
|
||||
}
|
||||
|
||||
interface CatalogCidr {
|
||||
@@ -50,12 +52,13 @@ export function seedFlowCatalogForTests(input: {
|
||||
}
|
||||
|
||||
export function categoryFromPurpose(purpose: string, proto: number, dstPort: number, srcPort: number): string {
|
||||
const p = purpose.toLowerCase()
|
||||
if (/gaming|steam|epic|riot|playstation|roblox|ubisoft/.test(p)) return "Игры"
|
||||
if (/streaming|youtube|netflix|twitch|video|spotify|instagram/.test(p)) return "Видео / стриминг"
|
||||
const p = purpose.trim().toLowerCase()
|
||||
if (/игры|gaming|steam|epic|riot|playstation|roblox|ubisoft/.test(p)) return "Игры"
|
||||
if (/видео|стриминг|streaming|youtube|netflix|twitch|video|spotify|instagram/.test(p)) return "Видео / стриминг"
|
||||
if (/cdn|cloudflare|akamai|fastly|hetzner|ovh|apple/.test(p)) return "CDN"
|
||||
if (/voip|discord|zoom/.test(p)) return "Голос"
|
||||
if (/openai|chatgpt|\bai\b/.test(p)) return "ИИ"
|
||||
if (/мессенджер|telegram/.test(p)) return "Мессенджеры"
|
||||
if (/голос|voip|discord|zoom/.test(p)) return "Голос"
|
||||
if (p === "ии" || /openai|chatgpt|\bai\b/.test(p)) return "ИИ"
|
||||
if (/quad9|opendns/.test(p)) return "DNS"
|
||||
if (/веб|web|google|github|paypal|vk|linkedin/.test(p)) return "Веб"
|
||||
const app = applicationName(proto, dstPort, srcPort)
|
||||
@@ -71,6 +74,11 @@ function matchCidr(ip: string,rows=cidrs): CatalogCidr | null {
|
||||
return null
|
||||
}
|
||||
|
||||
function servicePurpose(value: string | undefined): string | undefined {
|
||||
const purpose = value?.trim()
|
||||
return purpose && !/^(main|default|other|прочее)$/i.test(purpose) ? purpose : undefined
|
||||
}
|
||||
|
||||
export function classifyFlowDst(
|
||||
dst: string,
|
||||
proto: number,
|
||||
@@ -80,20 +88,23 @@ export function classifyFlowDst(
|
||||
opts?: { ignoreTunnelProto?: boolean;catalog?:{cidrs:CatalogCidr[];asnPurpose:Map<number,string>} },
|
||||
): FlowClassification {
|
||||
if (!opts?.ignoreTunnelProto) {
|
||||
if (proto === 47) return { service: "GRE", category: "Туннель" }
|
||||
if (proto === 50) return { service: "ESP", category: "Туннель" }
|
||||
if (proto === 47) return { service: "GRE", category: "Туннель", basis: "port" }
|
||||
if (proto === 50) return { service: "ESP", category: "Туннель", basis: "port" }
|
||||
}
|
||||
const app = applicationName(proto, dstPort, srcPort)
|
||||
if (app === "WireGuard") return { service: "WireGuard", category: "Туннель" }
|
||||
const hit = matchCidr(dst,opts?.catalog?.cidrs)
|
||||
if ((proto === 6 || proto === 17) && (dstPort === 53 || dstPort === 853)) return { service: "DNS", category: "DNS", basis: "port" }
|
||||
if (app === "WireGuard") return { service: "WireGuard", category: "Туннель", basis: "port" }
|
||||
const prefixPurpose = servicePurpose(matchCidr(dst,opts?.catalog?.cidrs)?.purpose)
|
||||
const holder = ripe?.holder ?? ""
|
||||
const brand = resolveFlowBrand(dst, ripe?.asn ?? 0, holder, proto, dstPort, srcPort)
|
||||
const asnName = ripe?.asn ? (opts?.catalog?.asnPurpose??asnPurpose).get(ripe.asn) : undefined
|
||||
const service = (hit?.purpose || brand?.service || asnName || OTHER_SERVICE).trim() || OTHER_SERVICE
|
||||
const category = hit
|
||||
? categoryFromPurpose(hit.purpose, proto, dstPort, srcPort)
|
||||
: (brand?.category || categoryFromPurpose(asnName || "", proto, dstPort, srcPort))
|
||||
return { service, category }
|
||||
if (prefixPurpose && prefixPurpose.toLowerCase() !== brand?.operator?.toLowerCase()) {
|
||||
return { service: prefixPurpose, category: categoryFromPurpose(prefixPurpose, proto, dstPort, srcPort), basis: "catalog" }
|
||||
}
|
||||
if (brand) return { service: brand.service, category: brand.category, basis: brand.heuristic ? "heuristic" : "network" }
|
||||
const asnName = ripe?.asn ? servicePurpose((opts?.catalog?.asnPurpose??asnPurpose).get(ripe.asn)) : undefined
|
||||
const category = categoryFromPurpose(asnName || "", proto, dstPort, srcPort)
|
||||
const basis = asnName ? "catalog" : category !== OTHER_SERVICE ? "port" : "unknown"
|
||||
return { service: asnName || OTHER_SERVICE, category, basis }
|
||||
}
|
||||
|
||||
/** Copies already-observed data only; never fetches the EvoBGP catalog. */
|
||||
|
||||
@@ -142,6 +142,7 @@ assert.equal(classifyInternetBrand("8.8.8.8", 6, 443, 51234, {
|
||||
fetchedAt: Date.now(),
|
||||
})?.service, "Google")
|
||||
assert.equal(mapInternetBrand("203.0.113.50", 6, 443, 51234, null).service, "Прочее")
|
||||
assert.deepEqual(mapInternetBrand("185.246.117.91", 17, 53, 53000, null), { service: "DNS", category: "DNS", basis: "port" })
|
||||
assert.equal(mapInternetBrand("8.8.8.8", 47, 0, 0, null).service, "Прочее")
|
||||
assert.equal(mapInternetBrand("8.8.8.8", 6, 443, 51234, {
|
||||
prefix: "8.8.8.0/24",
|
||||
@@ -173,7 +174,7 @@ assert.equal(mapInternetBrand("8.8.8.8", 17, 53, 53000, {
|
||||
holder: "GOOGLE",
|
||||
ok: true,
|
||||
fetchedAt: Date.now(),
|
||||
}).service, "Google")
|
||||
}).service, "DNS")
|
||||
assert.equal(mapInternetBrand("2001:4860:4860::8888", 17, 443, 50000, {
|
||||
prefix: "2001:4860:4860::8888/128",
|
||||
asn: 15169,
|
||||
@@ -183,7 +184,7 @@ assert.equal(mapInternetBrand("2001:4860:4860::8888", 17, 443, 50000, {
|
||||
holder: "GOOGLE",
|
||||
ok: true,
|
||||
fetchedAt: Date.now(),
|
||||
}).service, "YouTube")
|
||||
}).service, "Google")
|
||||
assert.equal(mapInternetBrand("64.233.161.1", 17, 443, 50000, null).service, "YouTube")
|
||||
assert.equal(mapInternetBrand("142.250.1.10", 6, 443, 1, null).service, "YouTube")
|
||||
|
||||
|
||||
@@ -71,7 +71,7 @@ export function destCtxForIface(
|
||||
}
|
||||
}
|
||||
|
||||
const OTHER_BRAND: FlowClassification = { service: OTHER_SERVICE, category: OTHER_SERVICE }
|
||||
export const OTHER_BRAND: FlowClassification = { service: OTHER_SERVICE, category: OTHER_SERVICE, basis: "unknown" }
|
||||
|
||||
function isTunnelProto(proto: number, dstPort: number, srcPort: number): boolean {
|
||||
if (proto === 47 || proto === 50) return true
|
||||
@@ -85,7 +85,7 @@ export function classifyInternetBrand(
|
||||
dstPort: number,
|
||||
srcPort: number,
|
||||
ripe: FlowIpMeta | null,
|
||||
): FlowClassification | null {
|
||||
): Pick<FlowClassification, "service" | "category"> | null {
|
||||
if (isTunnelProto(proto, dstPort, srcPort)) return null
|
||||
const brand = resolveFlowBrand(dst, ripe?.asn ?? 0, ripe?.holder ?? "", proto, dstPort, srcPort)
|
||||
if (brand && isNamedInternetService(brand.service, brand.category)) return brand
|
||||
@@ -105,7 +105,7 @@ export function mapInternetBrand(
|
||||
if (isTunnelProto(proto, dstPort, srcPort)) return OTHER_BRAND
|
||||
const classified = classifyFlowDst(dst, proto, dstPort, srcPort, ripe, { ignoreTunnelProto: true })
|
||||
if (isNamedInternetService(classified.service, classified.category)) return classified
|
||||
return OTHER_BRAND
|
||||
return { ...classified, service: classified.category }
|
||||
}
|
||||
|
||||
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 serial from "./serial-operation.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 ifindex from "./traffic-flow-ifindex.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}),
|
||||
},
|
||||
"../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-apps.js":{applicationName:()=>"https"},
|
||||
"./traffic-flow-ripe.js":{enqueueRipeMisses:()=>{throw Error("unexpected RIPE enqueue")},pruneRipeSqlite},
|
||||
|
||||
@@ -9,7 +9,7 @@ import { createFlowFactAccumulator, type FactRow } from "./traffic-flow-fact-acc
|
||||
import { createSerialOperation } from "./serial-operation.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 { 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 { applicationName } from "./traffic-flow-apps.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 MINUTE_RETENTION_HOURS = 48
|
||||
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 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})
|
||||
const classified=destMeta.classified,country=destMeta.country
|
||||
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
|
||||
for (const rawIface of [flow.inIface, flow.outIface]) {
|
||||
const {name, index} = resolveIfaceName(serverId, rawIface)
|
||||
for (const [dim, {name, index}] of [[FLOW_IFACE_RX_DIM, ingress], [FLOW_IFACE_TX_DIM, egress]] as const) {
|
||||
if (name === "—") continue
|
||||
if (plane !== "mgmt") directions.push({ dim: dim + ":" + plane, key: name })
|
||||
if (index && name === `#${index}`) interfaceUncertain = true
|
||||
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)},
|
||||
{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)}))
|
||||
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,
|
||||
@@ -471,8 +476,9 @@ export function queueParsedFlows(serverId: number, flows: ParsedFlowInput[]): vo
|
||||
if (prev) {
|
||||
prev.bytes += flow.bytes
|
||||
prev.packets += flow.packets
|
||||
if (flow.outIface && !prev.flow.outIface) prev.flow.outIface = flow.outIface
|
||||
if (flow.nextHop && !prev.flow.nextHop) prev.flow.nextHop = flow.nextHop
|
||||
// This tuple is keyed by ingress. Only retain egress metadata shared by all its bytes.
|
||||
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.natDst && !prev.flow.natDst) prev.flow.natDst = flow.natDst
|
||||
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) {
|
||||
prev.bytes += row.bytes
|
||||
prev.packets += row.packets
|
||||
if (row.outIface && !prev.outIface) prev.outIface = row.outIface
|
||||
if (row.nextHop && !prev.nextHop) prev.nextHop = row.nextHop
|
||||
if (prev.outIface !== row.outIface) prev.outIface = ""
|
||||
if (prev.nextHop !== row.nextHop) prev.nextHop = ""
|
||||
if (row.natSrc && !prev.natSrc) prev.natSrc = row.natSrc
|
||||
if (row.natDst && !prev.natDst) prev.natDst = row.natDst
|
||||
if (row.natSrcPort && !prev.natSrcPort) prev.natSrcPort = row.natSrcPort
|
||||
@@ -959,8 +965,8 @@ async function upsertFlowBucketsBatch(rows: PendingFlowRow[]): Promise<void> {
|
||||
DO UPDATE SET
|
||||
bytes = flow_buckets.bytes + excluded.bytes,
|
||||
packets = flow_buckets.packets + excluded.packets,
|
||||
out_iface = CASE WHEN excluded.out_iface != '' THEN excluded.out_iface ELSE flow_buckets.out_iface END,
|
||||
next_hop = COALESCE(excluded.next_hop, flow_buckets.next_hop),
|
||||
out_iface = CASE WHEN flow_buckets.out_iface = excluded.out_iface THEN excluded.out_iface ELSE '' END,
|
||||
next_hop = CASE WHEN flow_buckets.next_hop = excluded.next_hop THEN excluded.next_hop END,
|
||||
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)
|
||||
THEN excluded.flow_start_ms ELSE flow_buckets.flow_start_ms END,
|
||||
|
||||
@@ -114,7 +114,7 @@ setGeoipReadersForTests({
|
||||
})
|
||||
const v6meta = resolveFlowIp("2001:4860:4860::8888")
|
||||
assert.equal(v6meta?.asn, 15169)
|
||||
assert.equal(mapInternetBrand("2001:4860:4860::8888", 17, 443, 50000, v6meta).service, "YouTube")
|
||||
assert.equal(mapInternetBrand("2001:4860:4860::8888", 17, 443, 50000, v6meta).service, "Google")
|
||||
assert.notEqual(mapInternetBrand("2001:4860:4860::8888", 17, 443, 50000, v6meta).service, "Прочее")
|
||||
const cidrYt = mapInternetBrand("64.233.161.1", 17, 443, 50000, resolveFlowIp("64.233.161.1"))
|
||||
assert.equal(cidrYt.service, "YouTube")
|
||||
|
||||
@@ -429,8 +429,8 @@ function mergeInto(map: Map<string, PendingFlowRow>, row: PendingFlowRow): void
|
||||
if (prev) {
|
||||
prev.bytes += row.bytes
|
||||
prev.packets += row.packets
|
||||
if (row.outIface && !prev.outIface) prev.outIface = row.outIface
|
||||
if (row.nextHop && !prev.nextHop) prev.nextHop = row.nextHop
|
||||
if (prev.outIface !== row.outIface) prev.outIface = ""
|
||||
if (prev.nextHop !== row.nextHop) prev.nextHop = ""
|
||||
if (row.natSrc && !prev.natSrc) prev.natSrc = row.natSrc
|
||||
if (row.natDst && !prev.natDst) prev.natDst = row.natDst
|
||||
if (row.natSrcPort && !prev.natSrcPort) prev.natSrcPort = row.natSrcPort
|
||||
|
||||
@@ -1,4 +1,10 @@
|
||||
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 { buildFlowAnalytics } from "./traffic-flow-analytics.js"
|
||||
import { readFlowClientInputs } from "./traffic-flow-catalog-read.js"
|
||||
import { rememberServerIfaces, resetIfaceCacheForTests } from "./traffic-flow-ifindex.js"
|
||||
import {
|
||||
ingestParsedFlowsForServerForTests,
|
||||
@@ -14,7 +20,7 @@ import {
|
||||
resetFlowMapHopsCacheForTests,
|
||||
} from "./traffic-flow-map-hops.js"
|
||||
import { withPgOrSkip } from "../test/pg.js"
|
||||
import { seedFlowTopologyForTests, type FlowTopology } from "./traffic-flow-topology.js"
|
||||
import { loadFlowTopology, resolveClient, seedFlowTopologyForTests, type FlowTopology } from "./traffic-flow-topology.js"
|
||||
import { disableCatalogFetchForTests, resetFlowCatalogForTests } from "./traffic-flow-classify.js"
|
||||
import {
|
||||
disableRipeEnqueueForTests,
|
||||
@@ -98,6 +104,21 @@ disableRipePersistForTests()
|
||||
resetRipeCacheForTests()
|
||||
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, nativeIndex:4, ifIndex:6, observedNextHops:[{ip:"10.200.100.54", serverId:"9"}]},
|
||||
{serverId:"7", name:"gre-client", remoteAddress:"192.0.2.77", enabled:true,nativeIndex:5,ifIndex:7},
|
||||
{serverId: "7", name: "gre-second", remoteAddress: "198.51.100.2", enabled: true, nativeIndex:12, ifIndex:4, observedNextHops:[{ip:"10.200.101.54",serverId:"10"}]},
|
||||
] })])
|
||||
|
||||
const topo: FlowTopology = {
|
||||
clientIfaces: new Map([[7, new Set(["gre-client"])]]),
|
||||
clientByIface: new Map([["7|gre-client", {
|
||||
@@ -130,7 +151,7 @@ rememberServerIfaces(3, [
|
||||
{ ".id": "*1", name: "ether1-rt" },
|
||||
])
|
||||
|
||||
ingestParsedFlowsForServerForTests(7, [
|
||||
ingestClosed(7, [
|
||||
{
|
||||
src: "10.100.1.17",
|
||||
dst: "8.8.8.8",
|
||||
@@ -177,7 +198,7 @@ ingestParsedFlowsForServerForTests(7, [
|
||||
outIface: "",
|
||||
},
|
||||
])
|
||||
ingestParsedFlowsForServerForTests(3, [
|
||||
ingestClosed(3, [
|
||||
{
|
||||
src: "192.168.1.10",
|
||||
dst: "8.8.4.4",
|
||||
@@ -288,7 +309,7 @@ rememberServerIfaces(7, [
|
||||
{ ".id": "*3", name: "gre-jh-en" },
|
||||
])
|
||||
googleRipe()
|
||||
ingestParsedFlowsForServerForTests(7, [
|
||||
ingestClosed(7, [
|
||||
payloadFlow("8.8.8.8", 600),
|
||||
payloadFlow("11.0.113.50", 9400),
|
||||
])
|
||||
@@ -320,7 +341,7 @@ try {
|
||||
assert.ok(usPath)
|
||||
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 })
|
||||
assert.equal(mixedPeer.totalBytes, 12_000)
|
||||
assert.equal(mixedPeer.namedBytes, 600, "WireGuard to the same peer is separate from the HTTPS service")
|
||||
@@ -340,7 +361,7 @@ rememberServerIfaces(7, [
|
||||
{ ".id": "*3", name: "gre-jh-en" },
|
||||
])
|
||||
googleRipe()
|
||||
ingestParsedFlowsForServerForTests(7, [
|
||||
ingestClosed(7, [
|
||||
payloadFlow("8.8.8.8", 400),
|
||||
payloadFlow("11.0.113.50", 9600),
|
||||
])
|
||||
@@ -374,7 +395,7 @@ rememberServerIfaces(7, [
|
||||
{ ".id": "*2", name: "gre-client" },
|
||||
{ ".id": "*3", name: "gre-jh-en" },
|
||||
])
|
||||
ingestParsedFlowsForServerForTests(7, [
|
||||
ingestClosed(7, [
|
||||
payloadFlow("8.8.8.8", 400),
|
||||
payloadFlow("104.18.35.51", 400),
|
||||
payloadFlow("11.0.113.50", 9200),
|
||||
@@ -407,7 +428,7 @@ rememberServerIfaces(7, [
|
||||
{ ".id": "*3", name: "gre-jh-en" },
|
||||
])
|
||||
seedRipeAsn("162.254.192.71", 32590, "VALVE-CORP")
|
||||
ingestParsedFlowsForServerForTests(7, [
|
||||
ingestClosed(7, [
|
||||
payloadFlow("162.254.192.71", 2000),
|
||||
])
|
||||
try {
|
||||
@@ -429,7 +450,7 @@ rememberServerIfaces(7, [
|
||||
{ ".id": "*2", name: "gre-client" },
|
||||
{ ".id": "*3", name: "gre-jh-en" },
|
||||
])
|
||||
ingestParsedFlowsForServerForTests(7, [
|
||||
ingestClosed(7, [
|
||||
payloadFlow("64.233.161.1", 10_000),
|
||||
payloadFlow("11.0.113.50", 20_000),
|
||||
])
|
||||
@@ -442,13 +463,13 @@ try {
|
||||
assert.equal(leak.totalBytes, 30_000)
|
||||
assert.equal(leak.namedBytes, 10_000)
|
||||
assert.equal(leak.unclassifiedBytes, 20_000)
|
||||
const yt = leak.services?.find((s) => s.id === "svc:youtube")
|
||||
const youtube = leak.services?.find((s) => s.id === "svc:youtube")
|
||||
const other = leak.services?.find((s) => s.id === "svc:other")
|
||||
assert.ok(yt, "64.233:443 без RIPE → YouTube")
|
||||
assert.ok(youtube, "YouTube по общему диапазону Google без RIPE")
|
||||
assert.ok(other, "dest без бренда → Прочее")
|
||||
assert.equal(yt.bytes, 10_000)
|
||||
assert.equal(youtube.bytes, 10_000)
|
||||
assert.equal(other.bytes, 20_000)
|
||||
assert.ok(Math.abs(yt.share - 10 / 30) < 0.01)
|
||||
assert.ok(Math.abs(youtube.share - 10 / 30) < 0.01)
|
||||
assert.ok(Math.abs(other.share - 20 / 30) < 0.01)
|
||||
assert.equal((leak.serviceEdges ?? []).reduce((n, e) => n + e.bytes, 0), hop.bytes)
|
||||
} finally {
|
||||
@@ -480,7 +501,7 @@ rememberServerIfaces(7, [
|
||||
])
|
||||
googleRipe()
|
||||
for (const b of smallBrands) seedRipeAsn(b.ip, b.asn, b.holder)
|
||||
ingestParsedFlowsForServerForTests(7, [
|
||||
ingestClosed(7, [
|
||||
payloadFlow("8.8.8.8", 5000),
|
||||
...smallBrands.map((b) => payloadFlow(b.ip, b.bytes)),
|
||||
])
|
||||
@@ -508,7 +529,7 @@ rememberServerIfaces(7, [
|
||||
{ ".id": "*2", name: "gre-client" },
|
||||
{ ".id": "*3", name: "gre-jh-en" },
|
||||
])
|
||||
ingestParsedFlowsForServerForTests(7, [
|
||||
ingestClosed(7, [
|
||||
{
|
||||
src: "203.0.113.10",
|
||||
dst: "198.51.100.1",
|
||||
@@ -544,7 +565,7 @@ rememberServerIfaces(7, [
|
||||
{ ".id": "*3", name: "gre-jh-en" },
|
||||
])
|
||||
googleRipe()
|
||||
ingestParsedFlowsForServerForTests(7, [
|
||||
ingestClosed(7, [
|
||||
{
|
||||
src: "10.100.1.17",
|
||||
dst: "8.8.8.8",
|
||||
@@ -609,7 +630,7 @@ rememberServerIfaces(7, [
|
||||
{ ".id": "*2", name: "gre-client" },
|
||||
{ ".id": "*3", name: "gre-jh-en" },
|
||||
])
|
||||
ingestParsedFlowsForServerForTests(7, [
|
||||
ingestClosed(7, [
|
||||
{
|
||||
src: "173.194.151.65",
|
||||
dst: "10.200.100.53",
|
||||
@@ -618,9 +639,9 @@ ingestParsedFlowsForServerForTests(7, [
|
||||
dstPort: 57182,
|
||||
bytes: 9_000,
|
||||
packets: 90,
|
||||
inIface: "2",
|
||||
outIface: "3",
|
||||
nextHop: "198.51.100.1",
|
||||
inIface: "3",
|
||||
outIface: "2",
|
||||
nextHop: "",
|
||||
},
|
||||
{
|
||||
src: "104.18.35.51",
|
||||
@@ -630,15 +651,15 @@ ingestParsedFlowsForServerForTests(7, [
|
||||
dstPort: 53880,
|
||||
bytes: 1_000,
|
||||
packets: 10,
|
||||
inIface: "2",
|
||||
outIface: "3",
|
||||
nextHop: "198.51.100.1",
|
||||
inIface: "3",
|
||||
outIface: "2",
|
||||
nextHop: "",
|
||||
},
|
||||
])
|
||||
try {
|
||||
resetFlowMapHopsCacheForTests()
|
||||
const rev = await buildFlowMapHops({ minutes: 5, minSharePct: 0 })
|
||||
assert.ok(rev.services?.some((s) => s.id === "svc:youtube"), "реверс googlevideo:443 → YouTube")
|
||||
assert.ok(rev.services?.some((s) => s.id === "svc:youtube"), "Ответный поток с порта 443 сети Google учитывается как YouTube")
|
||||
assert.ok(rev.services?.some((s) => s.id === "svc:cloudflare"), "реверс Cloudflare:443 → 10.x")
|
||||
assert.ok(rev.serviceEdges?.some((e) => e.toId === "svc:youtube" && e.fromId === "9"))
|
||||
} finally {
|
||||
@@ -659,7 +680,7 @@ rememberServerIfaces(7, [
|
||||
{ ".id": "*2", name: "gre-client" },
|
||||
{ ".id": "*3", name: "gre-jh-en" },
|
||||
])
|
||||
ingestParsedFlowsForServerForTests(7, [
|
||||
ingestClosed(7, [
|
||||
payloadFlow("8.8.8.8", 500),
|
||||
{
|
||||
src: "173.194.151.65",
|
||||
@@ -680,7 +701,7 @@ try {
|
||||
const googleEdge = wan.serviceEdges?.find((e) => e.toId === "svc:google")
|
||||
assert.ok(googleEdge, "Google с WAN JH")
|
||||
assert.equal(googleEdge.fromId, "9", "якорь на EN, не на JH")
|
||||
assert.ok(!(wan.serviceEdges ?? []).some((e) => e.fromId === "7"), "нет пунктира с JH")
|
||||
assert.ok(!(wan.serviceEdges ?? []).some((e) => e.fromId === "7"), "исторический снимок сопоставил GRE с Exit")
|
||||
const viaGre = wan.serviceEdges?.find((e) => e.toId === "svc:google")
|
||||
assert.ok(viaGre?.clients?.some((c) => c.name === "Alice") || viaGre?.clientName === "Alice")
|
||||
} finally {
|
||||
@@ -697,9 +718,9 @@ resetRipeCacheForTests()
|
||||
disableRipeEnqueueForTests()
|
||||
seedFlowTopologyForTests(topo)
|
||||
rememberServerIfaces(7, [
|
||||
{ ".id": "*1", name: "SWE-VEESP" },
|
||||
{ ".id": "*1", name: "ether1" },
|
||||
])
|
||||
ingestParsedFlowsForServerForTests(7, [
|
||||
ingestClosed(7, [
|
||||
{
|
||||
src: "173.194.151.65",
|
||||
dst: "10.200.100.53",
|
||||
@@ -712,20 +733,27 @@ ingestParsedFlowsForServerForTests(7, [
|
||||
outIface: "1",
|
||||
nextHop: "",
|
||||
},
|
||||
{ ...payloadFlow("1.2.3.4", 6000), proto: 17, dstPort: 53, inIface: "gre-client", outIface: "ether1", nextHop: "" },
|
||||
])
|
||||
try {
|
||||
resetFlowMapHopsCacheForTests()
|
||||
const wanOnly = await buildFlowMapHops({ minutes: 5, minSharePct: 0 })
|
||||
const googleEdge = wanOnly.serviceEdges?.find((e) => e.toId === "svc:youtube")
|
||||
assert.ok(googleEdge, "YouTube WAN без GRE payload")
|
||||
assert.equal(googleEdge.fromId, "9", "единственный EN, даже без nextHop")
|
||||
assert.ok(googleEdge.bps > 0, "скорость на hop EN→сервис")
|
||||
assert.ok(!(wanOnly.serviceEdges ?? []).some((e) => e.fromId === "7"), "нет пунктира с JH")
|
||||
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, "скорость на пути клиента")
|
||||
const youtube = wanOnly.services?.find(s => s.id === "svc:youtube")
|
||||
assert.equal(youtube?.bytes, 9000)
|
||||
assert.deepEqual(youtube.serviceEvidence, [{basis: "heuristic", bytes: 9000}])
|
||||
assert.deepEqual(youtube.trafficTypes, [{transport: "TCP", application: "HTTPS", bytes: 9000}])
|
||||
assert.deepEqual(wanOnly.services?.find(s => s.id === "svc:dns")?.trafficTypes,
|
||||
[{transport: "UDP", application: "DNS", bytes: 6000}])
|
||||
assert.deepEqual(wanOnly.services?.find(s => s.id === "svc:dns")?.serviceEvidence, [{basis: "port", bytes: 6000}])
|
||||
const dns = wanOnly.serviceEdges?.find(e => e.toId === "svc:dns")
|
||||
assert.deepEqual(dns && [dns.fromId, dns.observedOnly, dns.bytes], ["7", true, 6000])
|
||||
const dnsPath = wanOnly.servicePaths?.find(p => p.serviceId === "svc:dns")
|
||||
assert.deepEqual(dnsPath && [dnsPath.viaId, dnsPath.viaIface, dnsPath.enId, dnsPath.clientName], ["7", "ether1", "", "Alice"])
|
||||
assert.ok(wanOnly.countryEdges?.every(e => e.observedOnly && e.fromId === "7"))
|
||||
assert.ok(wanOnly.countryServiceGroups?.some(group => group.edges.some(e => e.toId.endsWith("|svc:dns"))))
|
||||
assert.deepEqual(wanOnly.nodeUsers?.["7"]?.map(u => [u.clientName, u.bytes]), [["—", 9000], ["Alice", 6000]])
|
||||
assert.equal(wanOnly.nodeUsers?.["9"], undefined)
|
||||
|
||||
} finally {
|
||||
seedFlowTopologyForTests(null)
|
||||
resetFlowRingsForTests()
|
||||
@@ -747,14 +775,14 @@ rememberServerIfaces(9, [
|
||||
{ ".id": "*1", name: "ether1" },
|
||||
])
|
||||
googleRipe()
|
||||
ingestParsedFlowsForServerForTests(7, [payloadFlow("8.8.8.8", 12_000)])
|
||||
ingestParsedFlowsForServerForTests(9, [{
|
||||
ingestClosed(7, [payloadFlow("8.8.8.8", 12_000)])
|
||||
ingestClosed(9, [{
|
||||
src: "10.100.1.17",
|
||||
dst: "8.8.8.8",
|
||||
proto: 6,
|
||||
srcPort: 51234,
|
||||
dstPort: 443,
|
||||
bytes: 12_000,
|
||||
bytes: 120_000,
|
||||
packets: 10,
|
||||
inIface: "1",
|
||||
outIface: "1",
|
||||
@@ -772,7 +800,10 @@ try {
|
||||
assert.equal(googlePaths[0]?.viaId, "7")
|
||||
const googleEdge = dual.serviceEdges?.find((e) => e.toId === "svc:google" && e.fromId === "9")
|
||||
assert.ok(googleEdge)
|
||||
assert.equal(googleEdge.bytes, 12_000)
|
||||
assert.equal(googleEdge.bytes, 120_000)
|
||||
assert.equal(dual.totalBytes, 120_000, "объём крупнейшей копии с атрибуцией маршрута JH")
|
||||
assert.equal(dual.nodeUsers?.["7"]?.find(u => u.clientName === "Alice")?.bytes, 12_000)
|
||||
assert.equal(dual.nodeUsers?.["9"]?.find(u => u.clientName === "Alice")?.bytes, 120_000)
|
||||
assert.equal(googleEdge.bps, googlePaths[0]?.bps)
|
||||
} finally {
|
||||
seedFlowTopologyForTests(null)
|
||||
@@ -792,7 +823,7 @@ rememberServerIfaces(7, [
|
||||
{ ".id": "*3", name: "gre-jh-en" },
|
||||
])
|
||||
googleRipe()
|
||||
ingestParsedFlowsForServerForTests(7, [
|
||||
ingestClosed(7, [
|
||||
payloadFlow("8.8.8.8", 8_000),
|
||||
{
|
||||
src: "8.8.8.8",
|
||||
@@ -818,6 +849,8 @@ try {
|
||||
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")
|
||||
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.bps, googlePaths[0]?.bps)
|
||||
} finally {
|
||||
@@ -848,7 +881,7 @@ seedRipeCacheForTests({
|
||||
ok: true,
|
||||
fetchedAt: Date.now(),
|
||||
})
|
||||
ingestParsedFlowsForServerForTests(7, [
|
||||
ingestClosed(7, [
|
||||
payloadFlow("8.8.8.8", 5000),
|
||||
payloadFlow("185.45.12.10", 5000),
|
||||
])
|
||||
@@ -885,7 +918,7 @@ rememberServerIfaces(7, [
|
||||
{ ".id": "*3", name: "gre-jh-en" },
|
||||
])
|
||||
googleRipe()
|
||||
ingestParsedFlowsForServerForTests(7, [
|
||||
ingestClosed(7, [
|
||||
payloadFlow("8.8.8.8", 600),
|
||||
payloadFlow("11.0.113.50", 9400),
|
||||
])
|
||||
@@ -938,7 +971,7 @@ seedRipeCacheForTests({
|
||||
ok: true,
|
||||
fetchedAt: Date.now(),
|
||||
})
|
||||
ingestParsedFlowsForServerForTests(7, [
|
||||
ingestClosed(7, [
|
||||
payloadFlow("8.8.8.8", 5000),
|
||||
payloadFlow("185.45.12.10", 5000),
|
||||
])
|
||||
@@ -974,7 +1007,7 @@ rememberServerIfaces(7, [
|
||||
])
|
||||
googleRipe()
|
||||
for (const b of smallBrands) seedRipeAsn(b.ip, b.asn, b.holder)
|
||||
ingestParsedFlowsForServerForTests(7, [
|
||||
ingestClosed(7, [
|
||||
payloadFlow("8.8.8.8", 5000),
|
||||
...smallBrands.map((b) => payloadFlow(b.ip, b.bytes)),
|
||||
])
|
||||
@@ -1005,3 +1038,215 @@ try {
|
||||
}
|
||||
|
||||
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.equal(map.services?.find(s => s.id === "svc:youtube")?.lastBucketAt, new Date(bucket).toISOString())
|
||||
assert.deepEqual(map.serviceEdges?.map(e => [e.fromId, e.bytes, Boolean(e.observedOnly)]), [["7", 9000, true], ["10", 2000, false], ["9", 1000, false]])
|
||||
assert.equal(map.servicePaths?.reduce((n, p) => n + p.bytes, 0), 12000)
|
||||
assert.equal(map.nodeUsers?.["7"]?.find(u => u.clientName === "Alice")?.bytes, 12000)
|
||||
assert.equal(map.nodeUsers?.["9"]?.find(u => u.clientName === "Alice")?.bytes, 1000)
|
||||
|
||||
const recent = await buildFlowMapHops({ serverId: 7, minutes: 1, includeCurrentMinute: true, minSharePct: 0 })
|
||||
assert.equal(recent.windowSec, 90)
|
||||
const lastMinute = new Date(bucket + 60_000).toISOString()
|
||||
assert.equal(recent.services?.find(s => s.id === "svc:youtube")?.lastBucketAt, lastMinute)
|
||||
assert.equal(recent.countryServiceGroups?.flatMap(g => g.services).find(s => s.label === "YouTube")?.lastBucketAt, lastMinute)
|
||||
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)
|
||||
const later = bucket + 150_000
|
||||
clock.mock.mockImplementation(() => later)
|
||||
ingestParsedFlowsForServerForTests(7, [{ ...flow, bytes: 0, packets: 1, outIface: "ether1" }])
|
||||
const idle = await buildFlowMapHops({ serverId: 7, minutes: 3, includeCurrentMinute: true, minSharePct: 0 })
|
||||
assert.equal(idle.services?.find(s => s.id === "svc:youtube")?.lastBucketAt, lastMinute)
|
||||
|
||||
resetFlowRingsForTests()
|
||||
resetFlowMapHopsCacheForTests()
|
||||
clock.mock.mockImplementation(() => bucket + 90_000)
|
||||
const forward = { ...flow, src:"10.10.0.1", inIface:"5", outIface:"4", nextHop:"10.200.100.54", bytes:1000 }
|
||||
const reverse = { ...forward, src:forward.dst, dst:forward.src, srcPort:forward.dstPort, dstPort:forward.srcPort, inIface:"4", outIface:"5", nextHop:"0.0.0.0", bytes:9000 }
|
||||
ingestClosed(7, [forward, reverse])
|
||||
rememberServerIfaces(7, [{".id":"*4",name:"ether1"},{".id":"*5",name:"wrong-client"}])
|
||||
const direct = await buildFlowMapHops({serverId:7, minutes:1, minSharePct:0})
|
||||
assert.equal(direct.nodeUsers?.["9"]?.find(u => u.clientName === "Alice")?.bytes, 10000)
|
||||
const own = await buildFlowMapHops({serverId:7, userId:"u1", minutes:1, minSharePct:0})
|
||||
assert.equal(own.totalBytes, 10000)
|
||||
assert.deepEqual(direct.serviceEdges?.map(e => [e.fromId,e.bytes]), [["9",10000]])
|
||||
resetFlowRingsForTests()
|
||||
resetFlowMapHopsCacheForTests()
|
||||
ingestClosed(7, [reverse, {...forward, outIface:"ether1", bytes:500}, {...forward, src:"10.10.0.2", outIface:"48", bytes:250}])
|
||||
const unproven = await buildFlowMapHops({serverId:7, minutes:1, minSharePct:0})
|
||||
assert.deepEqual(unproven.serviceEdges?.map(e => [e.fromId,e.observedOnly,e.bytes]), [["7",true,9750]])
|
||||
resetFlowRingsForTests()
|
||||
resetFlowMapHopsCacheForTests()
|
||||
ingestClosed(7, [forward, reverse, {...forward, src:"10.10.0.2", nextHop:"10.200.101.54"}])
|
||||
const ambiguous = await buildFlowMapHops({serverId:7, minutes:1, minSharePct:0})
|
||||
assert.ok(ambiguous.serviceEdges?.every(e => e.observedOnly), "conflicting paths for one raw index")
|
||||
const scoped = await buildFlowMapHops({serverId:7,userId:"u1", minutes:1,minSharePct:0})
|
||||
assert.equal(scoped.totalBytes,0, "a conflicting interface namespace cannot establish client scope")
|
||||
|
||||
resetFlowRingsForTests()
|
||||
resetFlowMapHopsCacheForTests()
|
||||
clock.mock.mockImplementation(() => bucket + 150_000)
|
||||
ingestClosed(7, [forward])
|
||||
ingestClosed(7, [reverse], bucket + 60_000)
|
||||
const otherMinute = await buildFlowMapHops({serverId:7,minutes:2,minSharePct:0})
|
||||
assert.equal(otherMinute.serviceEdges?.find(e => e.fromId === "9")?.bytes, 1000)
|
||||
assert.equal(otherMinute.serviceEdges?.find(e => e.observedOnly)?.bytes, 9000)
|
||||
|
||||
} finally { clock.mock.restore() }
|
||||
} finally {
|
||||
await dbQuery("DELETE FROM internet_path_snapshots WHERE id=?", [snapshot.id])
|
||||
resetFlowRingsForTests()
|
||||
seedFlowTopologyForTests(null)
|
||||
}
|
||||
|
||||
// A video download can arrive in an earlier receipt minute than the latest HTTPS traffic.
|
||||
seedFlowTopologyForTests(topo)
|
||||
try {
|
||||
const youtube = (bytes: number) => ({ ...payloadFlow("173.194.151.65", bytes), proto: 17 })
|
||||
ingestClosed(7, [youtube(224_932_500)], bucket - 120_000)
|
||||
ingestClosed(7, [youtube(67_500), payloadFlow("104.18.35.51", 69_075_000)], bucket)
|
||||
const clock = mock.method(Date, "now", () => bucket + 90_000)
|
||||
try {
|
||||
const query = { serverId: 7, minSharePct: 0 }
|
||||
const recent = await buildFlowMapHops({ ...query, minutes: 1, includeCurrentMinute: true })
|
||||
assert.equal(recent.services?.find(s => s.id === "svc:youtube")?.bps, 6_000)
|
||||
assert.equal(recent.services?.find(s => s.id === "svc:cloudflare")?.bps, 6_140_000)
|
||||
|
||||
const map = await buildFlowMapHops({ ...query, minutes: 5 })
|
||||
assert.equal(map.windowSec, 300)
|
||||
const video = map.services?.find(s => s.id === "svc:youtube")
|
||||
assert.equal(video?.bytes, 225_000_000)
|
||||
assert.equal(video.bps, 6_000_000)
|
||||
assert.equal(map.services?.find(s => s.id === "svc:cloudflare")?.bytes, 69_075_000)
|
||||
} finally { clock.mock.restore() }
|
||||
} finally {
|
||||
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.ok(mixed.serviceEdges?.every(e => e.observedOnly && e.fromId === String(sid)))
|
||||
assert.ok(mixed.servicePaths?.every(p => !p.enId))
|
||||
await flushEngineNow({ prune: false })
|
||||
assert.deepEqual((await dbQuery("SELECT out_iface,next_hop FROM flow_buckets WHERE server_id=? AND in_iface='mixed-lan'", [sid])).rows,
|
||||
[{out_iface: "", next_hop: null}, {out_iface: "", next_hop: null}])
|
||||
const user = await buildFlowMapHops({serverId: sid, minutes: 5, userId: "no-interface-binding"})
|
||||
assert.equal(user.interfaceTraffic, undefined)
|
||||
const alice = `map-alice-${sid}`, bob = `map-bob-${sid}`
|
||||
try {
|
||||
await dbQuery("INSERT INTO app_users(id,login,name) VALUES (?,?,'Alice'),(?,?,'Bob')", [alice, alice, bob, bob])
|
||||
await dbQuery(`
|
||||
INSERT INTO user_interface_bindings(id,user_id,server_id,interface_name,interface_type,peer_public_key)
|
||||
VALUES (?, ?, ?, 'wg-shared', 'wg', 'alice-key'), (?, ?, ?, 'wg-shared', 'wg', 'bob-key'), (?, ?, ?, 'gre-owner', 'gre', '')
|
||||
`, [alice + "-wg", alice, sid, bob + "-wg", bob, sid, alice + "-gre", alice, sid])
|
||||
seedFlowTopologyForTests(null)
|
||||
for (const topology of [await loadFlowTopology(), await loadFlowTopology([sid])]) {
|
||||
assert.equal(resolveClient(topology, sid, "wg-shared"), null, "общий WG не присваивается одному пользователю")
|
||||
assert.equal(resolveClient(topology, sid, "gre-owner")?.userId, alice)
|
||||
}
|
||||
const flow = { ...payloadFlow("8.8.8.8", 1000), inIface: "gre-owner", outIface: "uplink-a" }
|
||||
ingestClosed(sid, [flow, { ...flow, inIface: "wg-shared", srcPort: 49151 }], bucket - 60_000)
|
||||
const aliceMap = await buildFlowMapHops({serverId: sid, minutes: 5, userId: alice})
|
||||
const aliceTraffic = await buildFlowAnalytics({serverId: sid, minutes: 5, userId: alice})
|
||||
const bobTraffic = await buildFlowAnalytics({serverId: sid, minutes: 5, userId: bob})
|
||||
assert.equal(aliceMap.totalBytes, 1000)
|
||||
assert.equal(aliceTraffic.bytes, aliceMap.totalBytes)
|
||||
assert.equal(bobTraffic.bytes, 0)
|
||||
|
||||
await dbQuery(`INSERT INTO user_interface_bindings(id,user_id,server_id,interface_name,interface_type,peer_public_key)
|
||||
VALUES (?, ?, ?, 'wg-exclusive', 'wg', 'alice-exclusive')`, [alice + "-exclusive", alice, sid])
|
||||
assert.equal(resolveClient(await loadFlowTopology([sid]), sid, "wg-exclusive"), null)
|
||||
await dbQuery("UPDATE servers SET enabled=true WHERE id=?", [sid])
|
||||
const sampledAt = new Date().toISOString()
|
||||
await dbQuery(`INSERT INTO traffic_samples(server_id,interface_name,peer_public_key,sampled_at)
|
||||
VALUES (?, 'wg-exclusive', 'alice-exclusive', ?)`, [sid, sampledAt])
|
||||
await dbQuery(`INSERT INTO traffic_collection_state(server_id,server_updated_at,last_attempt_at,last_succeeded_at,status)
|
||||
SELECT id,updated_at,?,?,'ok' FROM servers WHERE id=?`, [sampledAt, sampledAt, sid])
|
||||
seedFlowTopologyForTests(null)
|
||||
assert.equal(resolveClient(await loadFlowTopology([sid]), sid, "wg-exclusive")?.userId, alice)
|
||||
const {users} = await readFlowClientInputs(5, {serverIds: [sid], allowedServerIds: [sid], offset: 0, limit: 10})
|
||||
assert.equal(users.find(u => u.id === alice)?.bindings.find(b => b.interfaceName === "wg-exclusive")?.attributable, true)
|
||||
ingestClosed(sid, [{ ...flow, inIface: "wg-exclusive", bytes: 2000, srcPort: 49155 }], bucket - 60_000)
|
||||
resetFlowMapHopsCacheForTests()
|
||||
assert.equal((await buildFlowMapHops({serverId: sid, minutes: 5, userId: alice})).totalBytes, 3000)
|
||||
assert.equal((await buildFlowAnalytics({serverId: sid, minutes: 5, userId: alice})).bytes, 3000)
|
||||
await dbQuery(`INSERT INTO traffic_samples(server_id,interface_name,peer_public_key,sampled_at)
|
||||
VALUES (?, 'wg-exclusive', 'unbound-peer', ?)`, [sid, sampledAt])
|
||||
seedFlowTopologyForTests(null)
|
||||
assert.equal(resolveClient(await loadFlowTopology([sid]), sid, "wg-exclusive"), null, "второй peer виден даже без привязки в приложении")
|
||||
} finally {
|
||||
await dbQuery("DELETE FROM app_users WHERE id IN (?,?)", [alice, bob])
|
||||
}
|
||||
console.log("CHR NetFlow v5 through PostgreSQL and map: GRE A RX / GRE B TX both 192 B, 3 packets; Top-200 and GRE encapsulation verified")
|
||||
} finally {
|
||||
await dbQuery("DELETE FROM servers WHERE id=?", [sid])
|
||||
resetFlowRingsForTests()
|
||||
seedFlowTopologyForTests(null)
|
||||
resetIfaceCacheForTests()
|
||||
}
|
||||
@@ -1,23 +1,26 @@
|
||||
import { FlowSourceWindowTooLarge, FlowSqlSourceTooLarge } from "./traffic-flow-read-window.js"
|
||||
import { flowReadDbAll } from "./traffic-flow-read-policy.js"
|
||||
import { isDeepStrictEqual } from "node:util"
|
||||
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, FlowServiceBasis } from "@mmapp/contracts/traffic-flow"
|
||||
import type { ScopedFlowAnalyticsRead } from "./traffic-flow-analytics.js"
|
||||
import type { FlowMapCountryServiceGroup, FlowMapHop, FlowMapHopsDto, FlowMapService, FlowMapServiceEdge, FlowMapServicePath } from "@mmapp/contracts/traffic-flow"
|
||||
import { flowRowMatchesFilter } from "./traffic-flow-apps.js"
|
||||
import { flowPortApplication, flowRowMatchesFilter } from "./traffic-flow-apps.js"
|
||||
import { OTHER_SERVICE, isNamedInternetService, mapCountryNodeId, mapCountryServiceNodeId, mapServiceNodeId, resolveRipeCountry } from "./traffic-flow-brands.js"
|
||||
import type { FlowIpMeta } from "./traffic-flow-ripe.js"
|
||||
import { refreshFlowCatalogInBackground } from "./traffic-flow-classify.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 { classifyFlowPlane, shouldKeepPlane } from "./traffic-flow-planes.js"
|
||||
import { destCtxForIface, flowRateDirection, mapInternetBrand } from "./traffic-flow-dest.js"
|
||||
import { destCtxForIface, flowRateDirection, mapInternetBrand, OTHER_BRAND } from "./traffic-flow-dest.js"
|
||||
import { protoName } from "./traffic-flow-parse.js"
|
||||
import { resolveFlowEndpoints } from "./traffic-flow-ip.js"
|
||||
import { geoipReadersStatus, resolveFlowIp } from "./traffic-flow-geoip.js"
|
||||
import { getTrafficFlowSettingsRow } from "./traffic-flow-settings.js"
|
||||
import { loadFlowTopology, resolveClient, resolveEn, getServerCatalog, type FlowTopology } from "./traffic-flow-topology.js"
|
||||
import { flowDataEpoch } from "./traffic-flow-engine.js"
|
||||
import { loadFlowTopology, resolveFlowClient, flowClientInterfaces, getServerCatalog, type FlowClientBinding } from "./traffic-flow-topology.js"
|
||||
import { flowDataEpoch, FLOW_IFACE_RX_DIM, FLOW_IFACE_TX_DIM, minuteBucketIso } from "./traffic-flow-engine.js"
|
||||
|
||||
export const DEFAULT_MAP_SERVICE_MIN_SHARE_PCT = 5
|
||||
export const MAP_SERVICE_NODE_CAP = 20
|
||||
@@ -32,6 +35,7 @@ const HOPS_CACHE_TTL_MS = 2000
|
||||
|
||||
export interface FlowMapHopsQuery {
|
||||
minutes: number
|
||||
includeCurrentMinute?: boolean
|
||||
serverId?: number
|
||||
userId?: string
|
||||
iface?: string
|
||||
@@ -60,6 +64,10 @@ interface ClientAcc {
|
||||
}
|
||||
|
||||
interface FromAcc {
|
||||
exporterId: string
|
||||
enId: string
|
||||
viaIface?: string
|
||||
reverseBytes: number
|
||||
bytes: number
|
||||
clients: Map<string, ClientAcc>
|
||||
}
|
||||
@@ -67,9 +75,11 @@ interface FromAcc {
|
||||
interface DstAcc {
|
||||
dst: string
|
||||
bytes: number
|
||||
lastBucketAt: string
|
||||
proto: number
|
||||
dstPort: number
|
||||
srcPort: number
|
||||
application: string | null
|
||||
fromBytes: Map<string, FromAcc>
|
||||
}
|
||||
|
||||
@@ -77,6 +87,9 @@ interface DestTotal {
|
||||
label: string
|
||||
category: string
|
||||
bytes: number
|
||||
lastBucketAt: string
|
||||
trafficTypes?: Map<string, NonNullable<FlowMapService["trafficTypes"]>[number]>
|
||||
serviceEvidence?: Map<FlowServiceBasis, number>
|
||||
}
|
||||
|
||||
interface DestEdgeAcc {
|
||||
@@ -86,6 +99,7 @@ interface DestEdgeAcc {
|
||||
bytesFwd: number
|
||||
bytesRev: number
|
||||
clients: Map<string, string>
|
||||
observedOnly?: true
|
||||
}
|
||||
|
||||
interface DestPathAcc {
|
||||
@@ -93,6 +107,7 @@ interface DestPathAcc {
|
||||
clientName: string
|
||||
viaId: string
|
||||
viaName: string
|
||||
viaIface?: string
|
||||
enId: string
|
||||
enName: string
|
||||
serviceId: string
|
||||
@@ -110,16 +125,13 @@ function bumpClient(clients: Map<string, ClientAcc>, bytes: number, client: { us
|
||||
clients.set(id, { name, bytes })
|
||||
}
|
||||
|
||||
function bumpFrom(acc: DstAcc, exporterId: string, bytes: number, client: { userId: string; name: string } | null): void {
|
||||
const prev = acc.fromBytes.get(exporterId)
|
||||
if (prev) {
|
||||
prev.bytes += bytes
|
||||
bumpClient(prev.clients, bytes, client)
|
||||
return
|
||||
}
|
||||
const clients = new Map<string, ClientAcc>()
|
||||
bumpClient(clients, bytes, client)
|
||||
acc.fromBytes.set(exporterId, { bytes, clients })
|
||||
function bumpFrom(acc: DstAcc, exporterId: string, enId: string, viaIface: string | undefined, bytes: number, reverse: boolean, client: FlowClientBinding | null | undefined): void {
|
||||
const key = JSON.stringify([exporterId, enId, viaIface])
|
||||
const from = acc.fromBytes.get(key) ?? { exporterId, enId, viaIface, bytes: 0, reverseBytes: 0, clients: new Map<string, ClientAcc>() }
|
||||
from.bytes += bytes
|
||||
if (reverse) from.reverseBytes += bytes
|
||||
bumpClient(from.clients, bytes, client ?? null)
|
||||
acc.fromBytes.set(key, from)
|
||||
}
|
||||
|
||||
let hopsCache: { key: string; at: number; dto: FlowMapHopsDto } | null = null
|
||||
@@ -150,13 +162,22 @@ export function pickMapServices(
|
||||
.slice(0, cap)
|
||||
}
|
||||
|
||||
function bumpDestTotal(totals: Map<string, DestTotal>, id: string, label: string, category: string, bytes: number): void {
|
||||
const prev = totals.get(id)
|
||||
if (prev) {
|
||||
prev.bytes += bytes
|
||||
return
|
||||
function bumpDestTotal(totals: Map<string, DestTotal>, id: string, label: string, category: string, bytes: number, lastBucketAt: string,
|
||||
detail?: { transport: string; application: string | null; basis: FlowServiceBasis }): void {
|
||||
const total = totals.get(id) ?? { label, category, bytes: 0, lastBucketAt }
|
||||
total.bytes += bytes
|
||||
if (lastBucketAt > total.lastBucketAt) total.lastBucketAt = lastBucketAt
|
||||
if (detail && bytes > 0) {
|
||||
const { transport, application, basis } = detail
|
||||
const types = total.trafficTypes ??= new Map()
|
||||
const key = JSON.stringify([transport, application])
|
||||
const type = types.get(key) ?? { transport, application, bytes: 0 }
|
||||
type.bytes += bytes
|
||||
types.set(key, type)
|
||||
const evidence = total.serviceEvidence ??= new Map()
|
||||
evidence.set(basis, (evidence.get(basis) ?? 0) + bytes)
|
||||
}
|
||||
totals.set(id, { label, category, bytes })
|
||||
totals.set(id, total)
|
||||
}
|
||||
|
||||
function bumpDestFrom(
|
||||
@@ -169,7 +190,7 @@ function bumpDestFrom(
|
||||
enName: string,
|
||||
viaName: string,
|
||||
/** fromId ребра, если отличается от EN (вложенный слой: страна → сервис). */
|
||||
edgeFromId: string = fromId,
|
||||
edgeFromId: string = fromId || exporterId,
|
||||
): void {
|
||||
const edgeKey = `${edgeFromId}|${toId}`
|
||||
const prevEdge = edges.get(edgeKey)
|
||||
@@ -179,27 +200,25 @@ function bumpDestFrom(
|
||||
}
|
||||
if (prevEdge) {
|
||||
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)
|
||||
} else {
|
||||
edges.set(edgeKey, {
|
||||
fromId: edgeFromId,
|
||||
toId,
|
||||
bytes: from.bytes,
|
||||
bytesFwd: from.bytes,
|
||||
bytesRev: 0,
|
||||
bytesFwd: from.bytes - from.reverseBytes,
|
||||
bytesRev: from.reverseBytes,
|
||||
clients: namedClients,
|
||||
...(!fromId && edgeFromId === exporterId ? { observedOnly: true as const } : {}),
|
||||
})
|
||||
}
|
||||
for (const [clientId, c] of from.clients) {
|
||||
const pathKey = `${clientId}|${fromId}|${toId}`
|
||||
const pathKey = JSON.stringify([clientId, exporterId, fromId, toId, from.viaIface])
|
||||
const prevPath = paths.get(pathKey)
|
||||
if (prevPath) {
|
||||
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
|
||||
} else {
|
||||
paths.set(pathKey, {
|
||||
@@ -207,6 +226,7 @@ function bumpDestFrom(
|
||||
clientName: c.name,
|
||||
viaId: exporterId,
|
||||
viaName,
|
||||
...(from.viaIface ? { viaIface: from.viaIface } : {}),
|
||||
enId: fromId,
|
||||
enName,
|
||||
serviceId: toId,
|
||||
@@ -233,8 +253,11 @@ function finalizeDestLayer(
|
||||
label: s.label,
|
||||
category: s.category,
|
||||
bytes: s.bytes,
|
||||
...(s.lastBucketAt ? { lastBucketAt: minuteBucketIso(Date.parse(s.lastBucketAt)) } : {}),
|
||||
bps: (s.bytes * 8) / windowSec,
|
||||
share: shareBase > 0 ? s.bytes / shareBase : 0,
|
||||
...(s.trafficTypes ? { trafficTypes: [...s.trafficTypes.values()].sort((a, b) => b.bytes - a.bytes).slice(0, 5) } : {}),
|
||||
...(s.serviceEvidence ? { serviceEvidence: [...s.serviceEvidence].map(([basis, bytes]) => ({ basis, bytes })).sort((a, b) => b.bytes - a.bytes) } : {}),
|
||||
}))
|
||||
.sort((a, b) => b.bytes - a.bytes),
|
||||
minSharePct,
|
||||
@@ -254,6 +277,7 @@ function finalizeDestLayer(
|
||||
bps: (e.bytes * 8) / windowSec,
|
||||
bpsFwd: (e.bytesFwd * 8) / windowSec,
|
||||
bpsRev: (e.bytesRev * 8) / windowSec,
|
||||
...(e.observedOnly ? { observedOnly: e.observedOnly } : {}),
|
||||
...(first ? { clientId: first.id, clientName: first.name } : {}),
|
||||
...(clients.length ? { clients } : {}),
|
||||
}
|
||||
@@ -266,6 +290,7 @@ function finalizeDestLayer(
|
||||
clientName: p.clientName,
|
||||
viaId: p.viaId,
|
||||
viaName: p.viaName,
|
||||
...(p.viaIface ? { viaIface: p.viaIface } : {}),
|
||||
enId: p.enId,
|
||||
enName: p.enName,
|
||||
serviceId: p.serviceId,
|
||||
@@ -331,6 +356,7 @@ function hopsQueryKey(q: FlowMapHopsQuery, minSharePct: number): string {
|
||||
return JSON.stringify({
|
||||
epoch: flowDataEpoch(),
|
||||
minutes: q.minutes,
|
||||
includeCurrentMinute: q.includeCurrentMinute === true,
|
||||
serverId: q.serverId ?? null,
|
||||
userId: q.userId ?? null,
|
||||
iface: q.iface ?? null,
|
||||
@@ -341,32 +367,10 @@ function hopsQueryKey(q: FlowMapHopsQuery, minSharePct: number): string {
|
||||
})
|
||||
}
|
||||
|
||||
async function userIfaceAllow(userId: string): Promise<Map<number, Set<string>> | null> {
|
||||
if (!userId) return null
|
||||
const binds = await flowReadDbAll<{serverId:number;interfaceName:string}>('SELECT server_id AS "serverId",interface_name AS "interfaceName" FROM user_interface_bindings WHERE user_id=?',[userId])
|
||||
const allow = new Map<number, Set<string>>()
|
||||
for (const b of binds) {
|
||||
const set = allow.get(b.serverId) ?? new Set<string>()
|
||||
set.add(b.interfaceName)
|
||||
allow.set(b.serverId, set)
|
||||
}
|
||||
return allow
|
||||
}
|
||||
|
||||
function ifaceUsable(name: string): boolean {
|
||||
return Boolean(name) && name !== "—"
|
||||
}
|
||||
|
||||
function resolveMapClient(
|
||||
topo: FlowTopology,
|
||||
serverId: number,
|
||||
inName: string,
|
||||
outName: string,
|
||||
) {
|
||||
return resolveClient(topo, serverId, inName)
|
||||
?? (ifaceUsable(outName) ? resolveClient(topo, serverId, outName) : null)
|
||||
}
|
||||
|
||||
function bump(acc: Map<string, HopAcc>, key: string, seed: Omit<HopAcc, "bytes" | "bytesFwd" | "bytesRev">, bytes: number, dir: "fwd" | "rev" | "both"): void {
|
||||
const prev = acc.get(key)
|
||||
const addFwd = dir === "fwd" || dir === "both" ? bytes : 0
|
||||
@@ -411,14 +415,145 @@ 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; nextHop: string }[]) {
|
||||
const peers = new Map<string, Map<string, string>>()
|
||||
const nextHops = new Map<string, { serverId: number; iface: string; native: number | null; explicit: number | null } | null>()
|
||||
const ingress = new Map<string, { serverId: number; iface: string } | null>()
|
||||
const names = new Map<string, string>()
|
||||
const namespace = new Map<string, number>()
|
||||
const keyFor = (bucket: string, server: number | string) => JSON.stringify([bucket, String(server)])
|
||||
const ifaceName = (row: typeof rows[number], raw: string) => {
|
||||
const key = keyFor(row.bucketAt, row.serverId)
|
||||
const mode = namespace.get(key)
|
||||
const cached = resolveIfaceName(row.serverId, raw).name
|
||||
if (!/^[1-9][0-9]*$/.test(raw)) return cached
|
||||
const native = names.get(JSON.stringify([key, 1, Number(raw)]))
|
||||
const explicit = names.get(JSON.stringify([key, 2, Number(raw)]))
|
||||
if (mode === 1 || mode === 2) {
|
||||
const exact = mode === 1 ? native : explicit
|
||||
if (exact !== undefined) return exact || "#" + raw
|
||||
if (native !== undefined || explicit !== undefined) return "#" + raw
|
||||
}
|
||||
// The current alias cache cannot resolve conflicting historical interface identities.
|
||||
if ([native, explicit].some(name => name !== undefined && name !== cached)) return "#" + raw
|
||||
return cached
|
||||
}
|
||||
if (!rows.length) return { peers, nextHops, ingress, ifaceName }
|
||||
const buckets = new Set<string>()
|
||||
for (const row of rows) {
|
||||
buckets.add(row.bucketAt)
|
||||
}
|
||||
const targets = new Set<string>()
|
||||
const hops = new Set<string>()
|
||||
for (const row of rows) {
|
||||
for (const raw of [row.inIface, row.outIface]) {
|
||||
targets.add(row.serverId + "|" + raw)
|
||||
targets.add(row.serverId + "|" + resolveIfaceName(row.serverId, raw).name)
|
||||
}
|
||||
if (row.nextHop && row.nextHop !== "0.0.0.0" && row.nextHop !== "::") hops.add(row.serverId + "|" + row.nextHop)
|
||||
}
|
||||
const bindings = await flowReadDbAll<{ bucket: string; key: string; remote: string; owner: string; iface: string; native: number | null; explicit: number | null; next_hops: Array<{ip: string; serverId: string}> }>(`
|
||||
SELECT b.bucket, (t->>'serverId') || '|' || (t->>'name') AS key, t->>'remoteAddress' AS remote,
|
||||
t->>'serverId' AS owner, t->>'name' AS iface, t->'nativeIndex' AS native, t->'ifIndex' AS explicit,
|
||||
(SELECT COALESCE(jsonb_agg(p), '[]'::jsonb) FROM jsonb_array_elements(CASE WHEN jsonb_typeof(t->'observedNextHops')='array'
|
||||
THEN t->'observedNextHops' ELSE '[]'::jsonb END) AS p
|
||||
WHERE p->>'serverId' ~ '^[1-9][0-9]*$' AND p->>'ip' <> '') AS next_hops
|
||||
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 (EXISTS (SELECT 1 FROM unnest(ARRAY[t->>'name',t->>'nativeIndex',t->>'ifIndex']) AS idx
|
||||
WHERE (t->>'serverId') || '|' || idx = ANY(?::text[]))
|
||||
OR EXISTS (SELECT 1 FROM jsonb_array_elements(CASE WHEN jsonb_typeof(t->'observedNextHops')='array'
|
||||
THEN t->'observedNextHops' ELSE '[]'::jsonb END) AS p WHERE (t->>'serverId') || '|' || (p->>'ip') = ANY(?::text[])))
|
||||
AND t->>'enabled'='true' AND t->>'name'<>'' AND t->>'remoteAddress'<>''
|
||||
`, [[...buckets], [...targets], [...hops]]).catch(error => {
|
||||
if (error instanceof FlowSqlSourceTooLarge) throw new FlowSourceWindowTooLarge()
|
||||
throw error
|
||||
})
|
||||
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)
|
||||
const ownerKey = keyFor(row.bucket, row.owner)
|
||||
for (const [mode, index] of [[1, row.native], [2, row.explicit]] as const) {
|
||||
if (!index) continue
|
||||
const key = JSON.stringify([ownerKey, mode, index])
|
||||
names.set(key, names.has(key) ? "" : row.iface)
|
||||
}
|
||||
for (const peer of row.next_hops) {
|
||||
const key = JSON.stringify([row.bucket, row.owner, peer.ip])
|
||||
nextHops.set(key, nextHops.has(key) ? null : { serverId: Number(peer.serverId), iface: row.iface, native: row.native, explicit: row.explicit })
|
||||
}
|
||||
}
|
||||
// Bind raw IPFIX indexes only to a directly observed next hop for this exporter and minute.
|
||||
for (const row of rows) {
|
||||
if (!/^[1-9][0-9]*$/.test(row.outIface)) continue
|
||||
const peer = nextHops.get(JSON.stringify([row.bucketAt, String(row.serverId), row.nextHop]))
|
||||
if (peer === undefined) continue
|
||||
const key = JSON.stringify([row.bucketAt, row.serverId, row.outIface])
|
||||
const prev = ingress.get(key)
|
||||
const mode = (peer?.native === Number(row.outIface) ? 1 : 0) | (peer?.explicit === Number(row.outIface) ? 2 : 0)
|
||||
const ownerKey = keyFor(row.bucketAt, row.serverId)
|
||||
namespace.set(ownerKey, (namespace.get(ownerKey) ?? 3) & mode)
|
||||
ingress.set(key, !peer || !mode || prev === null || prev && (prev.serverId !== peer.serverId || prev.iface !== peer.iface) ? null : peer)
|
||||
}
|
||||
return { peers, nextHops, ingress, ifaceName }
|
||||
}
|
||||
|
||||
async function buildFlowMapHopsUncached(q: FlowMapHopsQuery, minSharePct: number, scope?: ScopedFlowAnalyticsRead): Promise<FlowMapHopsDto> {
|
||||
const authorize = scope?.authorize ?? (async () => {})
|
||||
if (!scope) refreshFlowCatalogInBackground()
|
||||
await authorize()
|
||||
const limits = scope ? await readFlowMapSourceLimits() : undefined
|
||||
const windowSec = Math.max(60, q.minutes * 60)
|
||||
const now = Date.now()
|
||||
const completeUntil = Math.floor(now / 60_000) * 60_000
|
||||
const startMs = completeUntil - Math.max(1, q.minutes) * 60_000
|
||||
const end = q.includeCurrentMinute ? now : completeUntil
|
||||
const windowSec = (end - startMs) / 1000
|
||||
await authorize()
|
||||
const 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("Строка карты вне выбранного сервера")
|
||||
await authorize()
|
||||
const catalog = await getServerCatalog(scope?.serverIds)
|
||||
@@ -429,40 +564,36 @@ async function buildFlowMapHopsUncached(q: FlowMapHopsQuery, minSharePct: number
|
||||
const excludeOverlay = q.excludeOverlay !== false
|
||||
await authorize()
|
||||
const topo = await loadFlowTopology(scope?.serverIds, authorize)
|
||||
let allow: Map<number, Set<string>> | null = null
|
||||
if (q.userId) {
|
||||
if (!scope) allow = await userIfaceAllow(q.userId)
|
||||
else {
|
||||
allow = new Map()
|
||||
for (const binding of topo.clientByIface.values()) if (binding.userId === q.userId) {
|
||||
const names = allow.get(binding.serverId) ?? new Set<string>(); names.add(binding.interfaceName); allow.set(binding.serverId, names)
|
||||
}
|
||||
if (!allow.size) throw new Error("Пользователь не найден в разрешённой топологии")
|
||||
}
|
||||
const allow = q.userId ? flowClientInterfaces(topo, q.userId) : null
|
||||
if (scope && allow && !allow.size) throw new Error("Пользователь не найден в разрешённой топологии")
|
||||
|
||||
const { peers, nextHops, ingress, ifaceName } = await readMapGrePeers(raw)
|
||||
|
||||
function rowClient(r: (typeof raw)[number]) {
|
||||
return resolveFlowClient(topo, r.serverId, ifaceName(r, r.inIface), ifaceName(r, r.outIface))
|
||||
}
|
||||
|
||||
const matches = (serverId: number, iface: string) =>
|
||||
flowRowMatchesFilter({ serverId, inIface: iface }, resolveIfaceName(serverId, iface).name, q, allow)
|
||||
const selected = raw.filter(r => matches(r.serverId, r.inIface) || matches(r.serverId, r.outIface))
|
||||
const matches = (r: (typeof raw)[number], iface: string) =>
|
||||
flowRowMatchesFilter({ serverId: r.serverId, inIface: iface }, ifaceName(r, iface), q, allow)
|
||||
const selected = raw.filter(r => (!q.userId || rowClient(r)?.userId === q.userId) &&
|
||||
(matches(r, r.inIface) || matches(r, r.outIface)))
|
||||
const { rows } = collapseGreEspRows(selected, r => {
|
||||
if (ifaceFilter) {
|
||||
const ingress = matches(r.serverId, r.inIface), egress = matches(r.serverId, r.outIface)
|
||||
const ingress = matches(r, r.inIface), egress = matches(r, r.outIface)
|
||||
return ingress === egress ? null : ingress ? "rx" : "tx"
|
||||
}
|
||||
return flowRateDirection(r.serverId, r, topo, catalog.byId.get(r.serverId)?.host)
|
||||
})
|
||||
const matched = []
|
||||
for (const r of rows) {
|
||||
const resolved = resolveIfaceName(r.serverId, r.inIface)
|
||||
const outResolved = resolveIfaceName(r.serverId, r.outIface)
|
||||
const plane = classifyFlowPlane({
|
||||
src: r.src,
|
||||
dst: r.dst,
|
||||
proto: r.proto,
|
||||
srcPort: r.srcPort,
|
||||
dstPort: r.dstPort,
|
||||
inIface: resolved.name,
|
||||
outIface: outResolved.name,
|
||||
inIface: ifaceName(r, r.inIface),
|
||||
outIface: ifaceName(r, r.outIface),
|
||||
}, topo.plane)
|
||||
if (!shouldKeepPlane(plane, { excludeMesh, excludeOverlay })) continue
|
||||
matched.push(r)
|
||||
@@ -472,30 +603,26 @@ async function buildFlowMapHopsUncached(q: FlowMapHopsQuery, minSharePct: number
|
||||
if (scope) flowCounterSum(working.map(row => row.bytes))
|
||||
const hops = new Map<string, HopAcc>()
|
||||
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 observed = new Map<(typeof working)[number], {
|
||||
endpoints: ReturnType<typeof resolveFlowEndpoints>; exitId?: number; viaIface?: string; reverse: boolean
|
||||
client: ReturnType<typeof rowClient>; nodeBytes: Map<number, number>
|
||||
}>()
|
||||
const nodeUsers = new Map<number, Map<string, ClientAcc>>()
|
||||
const enIds = new Set(topo.enNodes.map((n) => n.id))
|
||||
let totalBytes = 0
|
||||
|
||||
function rowClient(r: (typeof working)[number]) {
|
||||
const inName = resolveIfaceName(r.serverId, r.inIface).name
|
||||
const outName = resolveIfaceName(r.serverId, r.outIface).name
|
||||
return resolveMapClient(topo, r.serverId, inName, outName)
|
||||
}
|
||||
|
||||
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) {
|
||||
const inRes = resolveIfaceName(r.serverId, r.inIface)
|
||||
const outRes = resolveIfaceName(r.serverId, r.outIface)
|
||||
const inName = inRes.name
|
||||
const outName = outRes.name
|
||||
const inName = ifaceName(r, r.inIface)
|
||||
const outName = ifaceName(r, r.outIface)
|
||||
const fromId = String(r.serverId)
|
||||
const fromLabel = nameById.get(r.serverId) ?? fromId
|
||||
const wanSet = topo.wanIfaces.get(r.serverId)
|
||||
@@ -535,20 +662,49 @@ async function buildFlowMapHopsUncached(q: FlowMapHopsQuery, minSharePct: number
|
||||
}
|
||||
}
|
||||
|
||||
const enOut = ifaceUsable(outName) ? resolveEn(topo, r.nextHop, outName) : null
|
||||
const enIn = ifaceUsable(inName) ? resolveEn(topo, "", inName) : null
|
||||
const en = (enOut && enOut.id !== r.serverId ? enOut : null)
|
||||
?? (enIn && enIn.id !== r.serverId ? enIn : null)
|
||||
if (en) {
|
||||
jhToEn.set(r.serverId, en.id)
|
||||
const toId = String(en.id)
|
||||
const dir: "fwd" | "rev" = enOut && enOut.id === en.id ? "fwd" : "rev"
|
||||
const greIface = dir === "fwd" && ifaceUsable(outName) ? outName : (ifaceUsable(inName) ? inName : undefined)
|
||||
bump(hops, `gre|${fromId}|${toId}`, {
|
||||
const bindings = peers.get(r.bucketAt)
|
||||
const outPeer = bindings?.get(fromId + "|" + outName)
|
||||
const nextHop = nextHops.get(JSON.stringify([r.bucketAt, fromId, r.nextHop]))
|
||||
const verifiedOutput = nextHop && (r.outIface === nextHop.iface || ingress.get(JSON.stringify([r.bucketAt, r.serverId, r.outIface]))?.iface === nextHop.iface)
|
||||
const outId = nextHop === undefined ? (outPeer === undefined ? hostIds.get(r.nextHop) : hostIds.get(outPeer))
|
||||
: verifiedOutput && enIds.has(nextHop.serverId) ? nextHop.serverId : undefined
|
||||
const input = ingress.get(JSON.stringify([r.bucketAt, r.serverId, r.inIface]))
|
||||
const inId = input === undefined ? hostIds.get(bindings?.get(fromId + "|" + inName) ?? "")
|
||||
: input && enIds.has(input.serverId) ? input.serverId : undefined
|
||||
const peerId = outId && inId && outId !== inId ? null : outId ?? inId
|
||||
const endpoints = resolveFlowEndpoints({
|
||||
src: r.src,
|
||||
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) : undefined
|
||||
const exitId = enIds.has(r.serverId) ? r.serverId : serviceSide ?? undefined
|
||||
const serviceIface = reverse ? inName : outName
|
||||
const otherIface = reverse ? outName : inName
|
||||
const viaIface = exitId === undefined
|
||||
? ifaceUsable(serviceIface) ? serviceIface : ifaceUsable(otherIface) ? otherIface : undefined
|
||||
: undefined
|
||||
const nodeBytes = new Map([[r.serverId, r.bytes]])
|
||||
if (exitId !== undefined) nodeBytes.set(exitId, r.bytes)
|
||||
observed.set(r, { endpoints, exitId, viaIface, reverse, client: resolveFlowClient(topo, r.serverId, inName, outName), nodeBytes })
|
||||
if (peerId && peerId !== r.serverId) {
|
||||
const toId = String(peerId)
|
||||
const dir = outId === peerId ? "fwd" : "rev"
|
||||
const greIface = dir === "fwd" ? nextHop?.iface ?? (ifaceUsable(outName) ? outName : undefined) : input?.iface ?? (ifaceUsable(inName) ? inName : undefined)
|
||||
bump(hops, JSON.stringify(["gre", fromId, toId, greIface]), {
|
||||
fromId,
|
||||
fromLabel,
|
||||
toId,
|
||||
toLabel: en.name,
|
||||
toLabel: nodeName(toId),
|
||||
kind: "gre",
|
||||
iface: greIface,
|
||||
}, r.bytes, dir)
|
||||
@@ -578,44 +734,50 @@ async function buildFlowMapHopsUncached(q: FlowMapHopsQuery, minSharePct: number
|
||||
}
|
||||
}
|
||||
|
||||
for (const r of payloadRows) {
|
||||
const inName = resolveIfaceName(r.serverId, r.inIface).name
|
||||
const outName = resolveIfaceName(r.serverId, r.outIface).name
|
||||
totalBytes += r.bytes
|
||||
const ep = resolveFlowEndpoints({
|
||||
src: r.src,
|
||||
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 payloadBytes = new Map<(typeof working)[number], number>()
|
||||
const payloadRows = wantDedup
|
||||
? dedupFlowRowsAcrossExporters(working, (a, b) => {
|
||||
const observationA = observed.get(a)!
|
||||
const observationB = observed.get(b)!
|
||||
const aRouted = observationA.exitId !== undefined
|
||||
const bRouted = observationB.exitId !== undefined
|
||||
const aCli = Boolean(observationA.client)
|
||||
const bCli = Boolean(observationB.client)
|
||||
const attributed = aRouted !== bRouted ? (aRouted ? a : b)
|
||||
: aCli !== bCli ? (aCli ? a : b)
|
||||
: a.bytes >= b.bytes ? a : b
|
||||
// Route/client evidence and the largest byte observation can come from different exporters.
|
||||
payloadBytes.set(attributed, Math.max(payloadBytes.get(a) ?? a.bytes, b.bytes))
|
||||
const clientA = observationA.client, clientB = observationB.client
|
||||
const chosen = observed.get(attributed)!
|
||||
chosen.client = clientA === null || clientB === null || (clientA && clientB && clientA.userId !== clientB.userId)
|
||||
? null : clientA ?? clientB
|
||||
for (const [id, bytes] of (attributed === a ? observationB : observationA).nodeBytes) {
|
||||
chosen.nodeBytes.set(id, Math.max(chosen.nodeBytes.get(id) ?? 0, bytes))
|
||||
}
|
||||
return attributed
|
||||
})
|
||||
: working
|
||||
|
||||
for (const r of payloadRows) {
|
||||
const bytes = payloadBytes.get(r) ?? r.bytes
|
||||
totalBytes += bytes
|
||||
const { endpoints: ep, exitId, viaIface, reverse, client, nodeBytes } = observed.get(r)!
|
||||
for (const [id, observedBytes] of nodeBytes) {
|
||||
const users = nodeUsers.get(id) ?? new Map<string, ClientAcc>()
|
||||
bumpClient(users, observedBytes, client ?? null)
|
||||
nodeUsers.set(id, users)
|
||||
}
|
||||
const dst = ep.internetPeer
|
||||
const dstPort = ep.peerPort || r.dstPort
|
||||
const srcPort = ep.otherPort || r.srcPort
|
||||
const destKey = dst ? JSON.stringify([dst, r.proto, dstPort, srcPort]) : ""
|
||||
const client = resolveMapClient(topo, r.serverId, inName, outName)
|
||||
const prevDst = dstAcc.get(destKey)
|
||||
if (prevDst) {
|
||||
prevDst.bytes += r.bytes
|
||||
bumpFrom(prevDst, String(r.serverId), r.bytes, client)
|
||||
} 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 application = flowPortApplication(r.proto, dstPort) ?? flowPortApplication(r.proto, srcPort)
|
||||
const destKey = dst ? JSON.stringify([dst, r.proto, dstPort, srcPort]) : JSON.stringify([r.proto, application])
|
||||
const acc = dstAcc.get(destKey) ?? { dst, bytes: 0, lastBucketAt: "", proto: r.proto, dstPort, srcPort, application, fromBytes: new Map<string, FromAcc>() }
|
||||
acc.bytes += bytes
|
||||
if (bytes > 0 && r.bucketAt > acc.lastBucketAt) acc.lastBucketAt = r.bucketAt
|
||||
bumpFrom(acc, String(r.serverId), exitId === undefined ? "" : String(exitId), viaIface, bytes, reverse, client)
|
||||
dstAcc.set(destKey, acc)
|
||||
}
|
||||
|
||||
const svcTotals = new Map<string, DestTotal>()
|
||||
@@ -628,25 +790,6 @@ async function buildFlowMapHopsUncached(q: FlowMapHopsQuery, minSharePct: number
|
||||
const nestedEdges = new Map<string, DestEdgeAcc>()
|
||||
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 {
|
||||
const n = Number(id)
|
||||
if (Number.isFinite(n)) {
|
||||
@@ -663,16 +806,16 @@ async function buildFlowMapHopsUncached(q: FlowMapHopsQuery, minSharePct: number
|
||||
const ripe = dst ? resolveFlowIp(dst) : null
|
||||
const classified = dst
|
||||
? mapInternetBrand(dst, acc.proto, acc.dstPort, acc.srcPort, ripe)
|
||||
: { service: OTHER_SERVICE, category: OTHER_SERVICE }
|
||||
: OTHER_BRAND
|
||||
const svcId = mapServiceNodeId(classified.service)
|
||||
bumpDestTotal(svcTotals, svcId, classified.service, classified.category, acc.bytes)
|
||||
const detail = { transport: protoName(acc.proto), application: acc.application, basis: classified.basis }
|
||||
bumpDestTotal(svcTotals, svcId, classified.service, classified.category, acc.bytes, acc.lastBucketAt, detail)
|
||||
const country = countryDestFromRipe(ripe, dst)
|
||||
bumpDestTotal(ccTotals, country.id, country.label, country.category, acc.bytes)
|
||||
bumpDestTotal(ccTotals, country.id, country.label, country.category, acc.bytes, acc.lastBucketAt)
|
||||
const nestedId = mapCountryServiceNodeId(country.id, svcId)
|
||||
bumpDestTotal(nestedTotals, nestedId, classified.service, classified.category, acc.bytes)
|
||||
for (const [exporterId, from] of acc.fromBytes) {
|
||||
const fromId = anchorEnId(exporterId)
|
||||
if (!fromId) continue
|
||||
bumpDestTotal(nestedTotals, nestedId, classified.service, classified.category, acc.bytes, acc.lastBucketAt, detail)
|
||||
for (const from of acc.fromBytes.values()) {
|
||||
const { exporterId, enId: fromId } = from
|
||||
const enName = nodeName(fromId)
|
||||
const viaName = nodeName(exporterId)
|
||||
bumpDestFrom(svcEdges, svcPaths, svcId, from, exporterId, fromId, enName, viaName)
|
||||
@@ -702,12 +845,20 @@ async function buildFlowMapHopsUncached(q: FlowMapHopsQuery, minSharePct: number
|
||||
await authorize()
|
||||
if (scope && (!isDeepStrictEqual(topo, await loadFlowTopology(scope.serverIds, authorize)) || !isDeepStrictEqual(limits, await readFlowMapSourceLimits()))) throw new Error("Топология или пределы карты NetFlow изменились во время чтения")
|
||||
await authorize()
|
||||
// Whole-interface counters must never be exposed as per-user payload or added to totalBytes.
|
||||
const interfaceTraffic = q.userId ? undefined : await readInterfaceTraffic(q.serverId ? [q.serverId] : [...catalog.byId.keys()], ifaceFilter, q, start, end)
|
||||
await authorize()
|
||||
return {
|
||||
...(interfaceTraffic ? { interfaceTraffic } : {}),
|
||||
nodeUsers: Object.fromEntries([...nodeUsers].map(([id, users]) => [id, [...users].map(([clientId, { name, bytes }]) => (
|
||||
{ clientId, clientName: name, bytes, bps: bytes * 8 / windowSec }
|
||||
)).sort((a, b) => b.bytes - a.bytes)])),
|
||||
hops: [...hops.values()]
|
||||
.map((a) => toHop(a, windowSec))
|
||||
.sort((a, b) => a.bytes === b.bytes ? 0 : b.bytes - a.bytes),
|
||||
live: listener.bound,
|
||||
rangeMinutes: q.minutes,
|
||||
...(q.includeCurrentMinute ? { includesCurrentMinute: true as const } : {}),
|
||||
windowSec,
|
||||
totalBytes,
|
||||
namedBytes,
|
||||
|
||||
@@ -7,7 +7,7 @@ export const PLANE_LABEL: Record<FlowPlane, string> = {
|
||||
mgmt: "mgmt",
|
||||
}
|
||||
|
||||
const WG_PORTS = new Set([51820, 13232, 51821])
|
||||
const WG_PORTS = new Set([51820, 13231, 13232, 51821])
|
||||
const FLOW_PORTS = new Set([4739, 2055])
|
||||
|
||||
export function isRfc1918(ip: string): boolean {
|
||||
|
||||
@@ -165,6 +165,21 @@ try{
|
||||
assert.equal(series.rxSeries.reduce((sum,value)=>sum+value,0),50*8/60/1e6)
|
||||
assert.equal(series.txSeries.reduce((sum,value)=>sum+value,0),100*8/60/1e6)
|
||||
}
|
||||
const tuple = await client.callTool({name:'mm_netflow_analytics_report_get',arguments:{
|
||||
serverId:1, minutes:5, srcIp:'::ffff:198.18.1.1', dstIp:'8.8.8.8', srcPort:1, dstPort:443, protocol:6, limit:1,
|
||||
}})
|
||||
assert.ok(!tuple.isError,JSON.stringify(tuple))
|
||||
const filtered = (tuple.structuredContent as {result:{
|
||||
analytics:{bytes:number;admittedTotals?:unknown}; sourceWindow:unknown;
|
||||
pages:{conversationsList:{total:number;nextOffset:number|null}};
|
||||
historicalDetail:{rowLimitAppliedBeforeFilters:boolean;exactTupleTotalsVerified:boolean};
|
||||
}}).result
|
||||
assert.equal(filtered.analytics.bytes,100)
|
||||
assert.equal(filtered.analytics.admittedTotals,undefined)
|
||||
assert.deepEqual(filtered.pages.conversationsList,{total:1,nextOffset:null})
|
||||
assert.deepEqual(filtered.sourceWindow,{requestedMinutes:5,effectiveMinutes:5,incomplete:false})
|
||||
assert.equal(filtered.historicalDetail.rowLimitAppliedBeforeFilters,true)
|
||||
assert.equal(filtered.historicalDetail.exactTupleTotalsVerified,false)
|
||||
} finally {
|
||||
applyHeartbeatForTests(heartbeat)
|
||||
invalidateFlowAnalyticsCache()
|
||||
|
||||
@@ -42,6 +42,27 @@ export interface ServerCatalogEntry {
|
||||
|
||||
const CATALOG_TTL_MS = 5_000
|
||||
|
||||
// The latest completed RouterOS wave records all observed peers, including disabled peers.
|
||||
export const flowBindingAttributionSql = `
|
||||
NOT EXISTS (
|
||||
SELECT 1 FROM user_interface_bindings conflict
|
||||
WHERE conflict.server_id=b.server_id AND conflict.interface_name=b.interface_name AND conflict.id<>b.id
|
||||
) AND (b.peer_public_key='' OR (b.interface_type='wg' AND EXISTS (
|
||||
SELECT 1 FROM traffic_collection_state state
|
||||
JOIN servers source ON source.id=state.server_id AND source.enabled AND source.updated_at=state.server_updated_at
|
||||
JOIN traffic_samples peer ON peer.server_id=state.server_id AND peer.sampled_at=state.last_succeeded_at
|
||||
AND peer.interface_name=b.interface_name AND peer.peer_public_key=b.peer_public_key
|
||||
WHERE state.server_id=b.server_id AND state.status IN ('ok','pending')
|
||||
AND state.last_succeeded_at >= now() - make_interval(secs => 5 * greatest(5, COALESCE(
|
||||
(SELECT interval_sec FROM traffic_settings WHERE id=1), 30)))
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM traffic_samples sibling
|
||||
WHERE sibling.server_id=peer.server_id AND sibling.sampled_at=peer.sampled_at
|
||||
AND sibling.interface_name=peer.interface_name AND sibling.peer_public_key NOT IN ('',peer.peer_public_key)
|
||||
)
|
||||
)))
|
||||
`
|
||||
|
||||
let seeded: FlowTopology | null = null
|
||||
let topologyCache: { at: number; topo: FlowTopology } | null = null
|
||||
let serverCatalogCache: { at: number; list: ServerCatalogEntry[]; byId: Map<number, ServerCatalogEntry> } | null = null
|
||||
@@ -124,11 +145,17 @@ export async function loadFlowTopology(serverIds?: readonly number[], authorize:
|
||||
AND NOT EXISTS(SELECT 1 FROM user_interface_bindings hidden WHERE hidden.user_id=u.id AND NOT(hidden.server_id=ANY(?::bigint[]))) LIMIT 1001
|
||||
`, [serverIds, serverIds])
|
||||
await authorize()
|
||||
const binds = serverIds === undefined ? await flowReadDbAll<{userId:string;serverId:number;interfaceName:string}>('SELECT user_id AS "userId",server_id AS "serverId",interface_name AS "interfaceName" FROM user_interface_bindings') : await flowReadDbAll<{ userId: string; serverId: number; interfaceName: string }>(`
|
||||
SELECT b.user_id AS "userId",b.server_id AS "serverId",b.interface_name AS "interfaceName" FROM user_interface_bindings b
|
||||
WHERE b.server_id=ANY(?::bigint[]) AND b.peer_public_key='' AND NOT EXISTS(SELECT 1 FROM user_interface_bindings hidden WHERE hidden.user_id=b.user_id AND NOT(hidden.server_id=ANY(?::bigint[]))) ORDER BY b.id
|
||||
LIMIT 1001
|
||||
`, [serverIds, serverIds])
|
||||
const binds = await flowReadDbAll<{ userId: string; serverId: number; interfaceName: string; attributable: boolean }>(`
|
||||
SELECT b.user_id AS "userId",b.server_id AS "serverId",b.interface_name AS "interfaceName",
|
||||
(${flowBindingAttributionSql}) AS attributable
|
||||
FROM user_interface_bindings b
|
||||
WHERE (?::bigint[] IS NULL OR (
|
||||
b.server_id=ANY(?::bigint[]) AND ${flowBindingAttributionSql}
|
||||
AND NOT EXISTS(SELECT 1 FROM user_interface_bindings hidden WHERE hidden.user_id=b.user_id AND NOT(hidden.server_id=ANY(?::bigint[])))
|
||||
))
|
||||
ORDER BY b.id
|
||||
LIMIT ?
|
||||
`, [serverIds ?? null, serverIds ?? null, serverIds ?? null, serverIds === undefined ? null : 1001])
|
||||
if (serverIds !== undefined && (binds.length > 1000 || users.length > 1000)) throw new Error("Превышен предел топологии NetFlow")
|
||||
const loginById = new Map(users.map((u) => [u.id, u]))
|
||||
const clientIfaces = new Map<number, Set<string>>()
|
||||
@@ -139,6 +166,7 @@ export async function loadFlowTopology(serverIds?: readonly number[], authorize:
|
||||
set.add(b.interfaceName)
|
||||
clientIfaces.set(b.serverId, set)
|
||||
allClientNames.add(b.interfaceName)
|
||||
if (!b.attributable) continue
|
||||
const user = loginById.get(b.userId)
|
||||
clientByIface.set(ifaceKey(b.serverId, b.interfaceName), {
|
||||
userId: b.userId,
|
||||
@@ -213,6 +241,24 @@ export function resolveClient(
|
||||
return topo.clientByIface.get(ifaceKey(serverId, inIfaceName)) ?? null
|
||||
}
|
||||
|
||||
/** null represents conflicting ownership; undefined means no attributable interface. */
|
||||
export function resolveFlowClient(topo: FlowTopology, serverId: number, inIface: string, outIface: string) {
|
||||
const ingress = resolveClient(topo, serverId, inIface)
|
||||
const egress = resolveClient(topo, serverId, outIface)
|
||||
if (ingress && egress && ingress.userId !== egress.userId) return null
|
||||
return ingress ?? egress ?? undefined
|
||||
}
|
||||
|
||||
export function flowClientInterfaces(topo: FlowTopology, userId: string) {
|
||||
const interfaces = new Map<number, Set<string>>()
|
||||
for (const binding of topo.clientByIface.values()) if (binding.userId === userId) {
|
||||
const names = interfaces.get(binding.serverId) ?? new Set<string>()
|
||||
names.add(binding.interfaceName)
|
||||
interfaces.set(binding.serverId, names)
|
||||
}
|
||||
return interfaces
|
||||
}
|
||||
|
||||
export function resolveEn(
|
||||
topo: FlowTopology,
|
||||
nextHop: string,
|
||||
|
||||
@@ -47,10 +47,18 @@ else {
|
||||
assert.equal(sample.headers["cache-control"], "no-store")
|
||||
assert.deepEqual(sample.json(), { rxMbps: 0, txMbps: 0, at: sample.json().at, timestampKind: "backend-receipt" })
|
||||
assert.equal(nativeRequests, beforeSample + 1)
|
||||
assert.equal((await app.inject(sampleUrl + "&ifaces=ether1,ether1")).statusCode, 400)
|
||||
assert.equal((await app.inject(sampleUrl + "&ifaces=ether1,ether2&iface=ether1")).statusCode, 400)
|
||||
assert.equal(nativeRequests, beforeSample + 1)
|
||||
const batch = await app.inject(sampleUrl + "&ifaces=ether1,ether2")
|
||||
assert.equal(batch.statusCode, 200)
|
||||
assert.equal(batch.headers["cache-control"], "no-store")
|
||||
assert.deepEqual(Object.keys(batch.json().interfaces), ["ether1", "ether2"])
|
||||
assert.equal(nativeRequests, beforeSample + 2)
|
||||
mode = "malformed"
|
||||
assert.equal((await app.inject(sampleUrl + "&iface=ether1")).statusCode, 503)
|
||||
mode = "zero"
|
||||
cases += 3
|
||||
cases += 6
|
||||
let stream=await open(),event=await stream.next();assert.equal(event?.event,"sample");assert.equal(event?.data.rxMbps,0);assert.equal(event?.data.timestampKind,"backend-receipt");stream.close();cases++
|
||||
for(const kind of ["empty","malformed","partial"]){mode=kind;two=kind==="partial";stream=await open();event=await stream.next();assert.equal(event?.event,"error");stream.close();cases++}
|
||||
mode="fallback";two=true;stream=await open();event=await stream.next();assert.equal(event?.event,"sample");assert.equal(event?.data.rxMbps,0);stream.close();cases++
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import assert from "node:assert/strict"
|
||||
import { parseMonitorTraffic, rateBpsFromDelta, bpsToMbps } from "./traffic-rate.js"
|
||||
import { readTrafficLiveSample, TrafficLiveSourceChanged } from "./traffic-live.js"
|
||||
import { readTrafficLiveInterfaces, readTrafficLiveSample, TrafficLiveSourceChanged } from "./traffic-live.js"
|
||||
import { MikrotikError, type MikrotikClient } from "./mikrotik.js"
|
||||
const point=(name="ether1",rx:unknown="0",tx:unknown="0")=>({name,"rx-bits-per-second":rx,"tx-bits-per-second":tx})
|
||||
for(const raw of [[],{},null,[null],[{...point(),"rx-bits-per-second":undefined}], [point("ether1","12bad")],[point("ether1",-1)], [point("ether1"),point("ether1")]]) {
|
||||
@@ -34,4 +34,18 @@ const many={get:async()=>Array.from({length:10},(_,i)=>({name:`ether${i}`,runnin
|
||||
}} as unknown as Pick<MikrotikClient,"get"|"post">
|
||||
const bounded=await readTrafficLiveSample(many,undefined,{names:[],joinedFailed:false},new AbortController().signal,async()=>{})
|
||||
assert.equal(bounded.rxMbps,0);assert.equal(maximum,4)
|
||||
|
||||
const batch = (testClient = cast) =>
|
||||
readTrafficLiveInterfaces(testClient, ["ether1", "ether2"], new AbortController().signal, async () => {})
|
||||
const joined = { ...cast, post: async () => [point("ether2", "0", "80000000"), point("ether1", "1300000", "0")] } as typeof cast
|
||||
const measurements = await batch(joined)
|
||||
assert.equal(measurements.ether1.rxMbps, 1.3)
|
||||
assert.equal(measurements.ether2.txMbps, 80)
|
||||
assert.equal(measurements.ether1.at, measurements.ether2.at)
|
||||
mode = "partial"
|
||||
assert.deepEqual(Object.keys(await batch()), ["ether1"])
|
||||
mode = "fallback"
|
||||
assert.deepEqual(Object.keys(await batch()), ["ether1", "ether2"])
|
||||
mode = "auth"
|
||||
await assert.rejects(batch(), /401/)
|
||||
console.log("traffic live completeness/fallback/auth/source/abort/positive-small-rate tests ok")
|
||||
@@ -1,14 +1,15 @@
|
||||
import { MikrotikError, type MikrotikClient } from "./mikrotik.js"
|
||||
import { isLoopbackName, parseMonitorTraffic, type MonitorLiveSample } from "./traffic-rate.js"
|
||||
import { isLoopbackName, parseMonitorTraffic, parseMonitorTrafficInterfaces, type MonitorLiveSample } from "./traffic-rate.js"
|
||||
|
||||
const TIMEOUT_MS = 4000
|
||||
export class TrafficLiveSourceChanged extends Error {}
|
||||
export interface TrafficLiveCache { names: string[]; joinedFailed: boolean }
|
||||
type Client = Pick<MikrotikClient, "get" | "post">
|
||||
type Monitor = (names: string) => Promise<unknown>
|
||||
|
||||
/** Never emit a partial sum, and check the source before every new native request. */
|
||||
export async function readTrafficLiveSample(client: Client, onlyInterface: string | undefined,
|
||||
cache: TrafficLiveCache, signal: AbortSignal, assertSource: () => Promise<void>): Promise<MonitorLiveSample> {
|
||||
/** Check the source before every new native request. */
|
||||
async function withTrafficMonitor<T>(client: Client, signal: AbortSignal, assertSource: () => Promise<void>,
|
||||
read: (monitor: Monitor, ensure: () => Promise<void>) => Promise<T>): Promise<T> {
|
||||
const parentSignal = signal, wave = new AbortController()
|
||||
const onAbort = () => wave.abort(parentSignal.reason)
|
||||
parentSignal.addEventListener("abort", onAbort, { once: true })
|
||||
@@ -16,52 +17,12 @@ export async function readTrafficLiveSample(client: Client, onlyInterface: strin
|
||||
const timeout = setTimeout(() => wave.abort(new Error("Не успели получить полный live-срез за 8 секунд. Выберите отдельный интерфейс")), 8000)
|
||||
signal = wave.signal
|
||||
try {
|
||||
const ensure = async () => { signal.throwIfAborted(); await assertSource(); signal.throwIfAborted() }
|
||||
const monitor = async (name: string) => {
|
||||
await ensure()
|
||||
return client.post<unknown>("/interface/monitor-traffic", { interface: name, once: "" }, TIMEOUT_MS, signal)
|
||||
}
|
||||
if (onlyInterface) {
|
||||
const raw = await monitor(onlyInterface)
|
||||
await ensure()
|
||||
return parseMonitorTraffic(raw, { onlyInterface })
|
||||
}
|
||||
await ensure()
|
||||
const raw = await client.get<unknown>("/interface", TIMEOUT_MS)
|
||||
if (!Array.isArray(raw)) throw new Error("Не получен каталог интерфейсов live")
|
||||
const names: string[] = []
|
||||
const flag = (value: unknown) => {
|
||||
if (value === true || value === "true" || value === "yes") return true
|
||||
if (value === false || value === "false" || value === "no") return false
|
||||
throw new Error("Неизвестное состояние интерфейса live")
|
||||
}
|
||||
for (const row of raw) {
|
||||
if (!row || typeof row !== "object" || Array.isArray(row) || typeof row.name !== "string" || !row.name.trim()) throw new Error("Некорректный каталог интерфейсов live")
|
||||
if (flag(row.running) && !flag(row.disabled) && !isLoopbackName(row.name)) names.push(row.name)
|
||||
}
|
||||
if (!names.length || new Set(names).size !== names.length) throw new Error("Нет достоверного набора активных интерфейсов live")
|
||||
if ([...names].sort().join("\0") !== [...cache.names].sort().join("\0")) cache.joinedFailed = false
|
||||
cache.names = names
|
||||
if (!cache.joinedFailed) {
|
||||
try {
|
||||
const result = await monitor(names.join(","))
|
||||
const ensure = async () => { signal.throwIfAborted(); await assertSource(); signal.throwIfAborted() }
|
||||
const monitor = async (name: string) => {
|
||||
await ensure()
|
||||
return parseMonitorTraffic(result, { expectedInterfaces: names })
|
||||
} catch (error) {
|
||||
// Unsupported joined command may fall back; auth/transport/invalid payload cannot become partial zero.
|
||||
if (!(error instanceof MikrotikError) || error.statusCode !== 400 || names.length < 2) throw error
|
||||
cache.joinedFailed = true
|
||||
return client.post<unknown>("/interface/monitor-traffic", { interface: name, once: "" }, TIMEOUT_MS, signal)
|
||||
}
|
||||
}
|
||||
const results: MonitorLiveSample[] = []
|
||||
for (let i = 0; i < names.length; i += 4) {
|
||||
results.push(...await Promise.all(names.slice(i, i + 4).map(async name =>
|
||||
parseMonitorTraffic(await monitor(name), { onlyInterface: name }))))
|
||||
}
|
||||
await ensure()
|
||||
const rxMbps = results.reduce((sum, r) => sum + r.rxMbps, 0), txMbps = results.reduce((sum, r) => sum + r.txMbps, 0)
|
||||
if (![rxMbps, txMbps].every(n => Number.isFinite(n) && n <= Number.MAX_SAFE_INTEGER / 1_000_000)) throw new Error("Суммарная live-скорость вне допустимого диапазона")
|
||||
return { rxMbps, txMbps, at: new Date().toISOString(), timestampKind: "backend-receipt" }
|
||||
return await read(monitor, ensure)
|
||||
} catch (error) {
|
||||
if (signal.aborted && !parentSignal.aborted && signal.reason instanceof Error) throw signal.reason
|
||||
throw error
|
||||
@@ -71,3 +32,71 @@ export async function readTrafficLiveSample(client: Client, onlyInterface: strin
|
||||
wave.abort()
|
||||
}
|
||||
}
|
||||
|
||||
export function readTrafficLiveInterfaces(client: Client, names: readonly string[], signal: AbortSignal, assertSource: () => Promise<void>) {
|
||||
return withTrafficMonitor(client, signal, assertSource, async (monitor, ensure) => {
|
||||
let raw: unknown
|
||||
try {
|
||||
raw = await monitor(names.join(","))
|
||||
} catch (error) {
|
||||
if (!(error instanceof MikrotikError) || error.statusCode !== 400 || names.length < 2) throw error
|
||||
const samples = []
|
||||
for (let offset = 0; offset < names.length; offset += 4) {
|
||||
const reads = await Promise.allSettled(names.slice(offset, offset + 4).map(async name =>
|
||||
[name, parseMonitorTraffic(await monitor(name), { onlyInterface: name })] as const))
|
||||
for (const read of reads) if (read.status === "fulfilled") samples.push(read.value)
|
||||
}
|
||||
await ensure()
|
||||
return Object.fromEntries(samples)
|
||||
}
|
||||
await ensure()
|
||||
return parseMonitorTrafficInterfaces(raw, names)
|
||||
})
|
||||
}
|
||||
|
||||
export function readTrafficLiveSample(client: Client, onlyInterface: string | undefined,
|
||||
cache: TrafficLiveCache, signal: AbortSignal, assertSource: () => Promise<void>): Promise<MonitorLiveSample> {
|
||||
return withTrafficMonitor(client, signal, assertSource, async (monitor, ensure) => {
|
||||
if (onlyInterface) {
|
||||
const raw = await monitor(onlyInterface)
|
||||
await ensure()
|
||||
return parseMonitorTraffic(raw, { onlyInterface })
|
||||
}
|
||||
await ensure()
|
||||
const raw = await client.get<unknown>("/interface", TIMEOUT_MS)
|
||||
if (!Array.isArray(raw)) throw new Error("Не получен каталог интерфейсов live")
|
||||
const names: string[] = []
|
||||
const flag = (value: unknown) => {
|
||||
if (value === true || value === "true" || value === "yes") return true
|
||||
if (value === false || value === "false" || value === "no") return false
|
||||
throw new Error("Неизвестное состояние интерфейса live")
|
||||
}
|
||||
for (const row of raw) {
|
||||
if (!row || typeof row !== "object" || Array.isArray(row) || typeof row.name !== "string" || !row.name.trim()) throw new Error("Некорректный каталог интерфейсов live")
|
||||
if (flag(row.running) && !flag(row.disabled) && !isLoopbackName(row.name)) names.push(row.name)
|
||||
}
|
||||
if (!names.length || new Set(names).size !== names.length) throw new Error("Нет достоверного набора активных интерфейсов live")
|
||||
if ([...names].sort().join("\0") !== [...cache.names].sort().join("\0")) cache.joinedFailed = false
|
||||
cache.names = names
|
||||
if (!cache.joinedFailed) {
|
||||
try {
|
||||
const result = await monitor(names.join(","))
|
||||
await ensure()
|
||||
return parseMonitorTraffic(result, { expectedInterfaces: names })
|
||||
} catch (error) {
|
||||
// Unsupported joined command may fall back; auth/transport/invalid payload cannot become partial zero.
|
||||
if (!(error instanceof MikrotikError) || error.statusCode !== 400 || names.length < 2) throw error
|
||||
cache.joinedFailed = true
|
||||
}
|
||||
}
|
||||
const results: MonitorLiveSample[] = []
|
||||
for (let i = 0; i < names.length; i += 4) {
|
||||
results.push(...await Promise.all(names.slice(i, i + 4).map(async name =>
|
||||
parseMonitorTraffic(await monitor(name), { onlyInterface: name }))))
|
||||
}
|
||||
await ensure()
|
||||
const rxMbps = results.reduce((sum, r) => sum + r.rxMbps, 0), txMbps = results.reduce((sum, r) => sum + r.txMbps, 0)
|
||||
if (![rxMbps, txMbps].every(n => Number.isFinite(n) && n <= Number.MAX_SAFE_INTEGER / 1_000_000)) throw new Error("Суммарная live-скорость вне допустимого диапазона")
|
||||
return { rxMbps, txMbps, at: new Date().toISOString(), timestampKind: "backend-receipt" }
|
||||
})
|
||||
}
|
||||
@@ -360,14 +360,11 @@ export function mergeBuiltTraffic(parts: BuiltTrafficSeries[]): BuiltTrafficSeri
|
||||
} } : acc,waves)
|
||||
}
|
||||
|
||||
export function parseMonitorTraffic(
|
||||
raw: unknown,
|
||||
opts?: { onlyInterface?: string; expectedInterfaces?: readonly string[] },
|
||||
): MonitorLiveSample {
|
||||
type MonitorTrafficSelection = { onlyInterface?: string; expectedInterfaces?: readonly string[]; allowMissing?: boolean }
|
||||
|
||||
function monitorTrafficRates(raw: unknown, opts?: MonitorTrafficSelection) {
|
||||
const items = Array.isArray(raw) ? raw : raw != null ? [raw] : []
|
||||
let rxBps = 0
|
||||
let txBps = 0
|
||||
const seen = new Set<string>()
|
||||
const samples = new Map<string, { rxBps: number; txBps: number }>()
|
||||
const expected = opts?.expectedInterfaces ? new Set(opts.expectedInterfaces) : null
|
||||
const rate = (raw: unknown) => {
|
||||
if (typeof raw !== "number" && (typeof raw !== "string" || !/^(?:\d+(?:\.\d+)?|\.\d+)$/.test(raw.trim()))) throw new Error("Некорректная скорость monitor-traffic")
|
||||
@@ -382,21 +379,33 @@ export function parseMonitorTraffic(
|
||||
if (typeof name !== "string" || !name.trim()) throw new Error("Не указан интерфейс monitor-traffic")
|
||||
if (opts?.onlyInterface) {
|
||||
if (name !== opts.onlyInterface) throw new Error("Ответ monitor-traffic относится к другому интерфейсу")
|
||||
} else if (isLoopbackName(name)) {
|
||||
} else if (isLoopbackName(name) && !expected?.has(name)) {
|
||||
continue
|
||||
}
|
||||
if (seen.has(name) || expected && !expected.has(name)) throw new Error("Некорректный набор интерфейсов monitor-traffic")
|
||||
seen.add(name)
|
||||
rxBps += rate(rec["rx-bits-per-second"])
|
||||
txBps += rate(rec["tx-bits-per-second"])
|
||||
}
|
||||
if (!seen.size || expected && (expected.size !== opts!.expectedInterfaces!.length ||
|
||||
[...expected].some(name => !seen.has(name)))) throw new Error("Не получены все live-измерения интерфейсов")
|
||||
if (![rxBps, txBps].every(n => Number.isFinite(n) && n <= Number.MAX_SAFE_INTEGER)) throw new Error("Суммарная live-скорость вне допустимого диапазона")
|
||||
return {
|
||||
rxMbps: rxBps / 1_000_000,
|
||||
txMbps: txBps / 1_000_000,
|
||||
at: new Date().toISOString(),
|
||||
timestampKind: "backend-receipt",
|
||||
if (samples.has(name) || expected && !expected.has(name)) throw new Error("Некорректный набор интерфейсов monitor-traffic")
|
||||
samples.set(name, {
|
||||
rxBps: rate(rec["rx-bits-per-second"]),
|
||||
txBps: rate(rec["tx-bits-per-second"]),
|
||||
})
|
||||
}
|
||||
if (!opts?.allowMissing && (!samples.size || expected && (expected.size !== opts!.expectedInterfaces!.length ||
|
||||
samples.size !== expected.size))) throw new Error("Не получены все live-измерения интерфейсов")
|
||||
return samples
|
||||
}
|
||||
|
||||
export function parseMonitorTrafficInterfaces(raw: unknown, expectedInterfaces: readonly string[]): Record<string, MonitorLiveSample> {
|
||||
const at = new Date().toISOString()
|
||||
return Object.fromEntries([...monitorTrafficRates(raw, { expectedInterfaces, allowMissing: true })].map(([name, sample]) =>
|
||||
[name, { rxMbps: sample.rxBps / 1_000_000, txMbps: sample.txBps / 1_000_000, at, timestampKind: "backend-receipt" }]))
|
||||
}
|
||||
|
||||
export function parseMonitorTraffic(
|
||||
raw: unknown,
|
||||
opts?: { onlyInterface?: string; expectedInterfaces?: readonly string[] },
|
||||
): MonitorLiveSample {
|
||||
const samples = [...monitorTrafficRates(raw, opts).values()]
|
||||
const rxBps = samples.reduce((sum, row) => sum + row.rxBps, 0)
|
||||
const txBps = samples.reduce((sum, row) => sum + row.txBps, 0)
|
||||
if (![rxBps, txBps].every(n => Number.isFinite(n) && n <= Number.MAX_SAFE_INTEGER)) throw new Error("Суммарная live-скорость вне допустимого диапазона")
|
||||
return { rxMbps: rxBps / 1_000_000, txMbps: txBps / 1_000_000, at: new Date().toISOString(), timestampKind: "backend-receipt" }
|
||||
}
|
||||
@@ -72,7 +72,7 @@ export async function getSettings() {
|
||||
retentionDays: 14,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
})
|
||||
}).onConflictDoNothing({ target: uptimeSettings.id })
|
||||
return (await db.select().from(uptimeSettings).where(eq(uptimeSettings.id, 1)).limit(1))[0]
|
||||
}
|
||||
|
||||
|
||||
@@ -48,6 +48,17 @@ export async function verifyMcpFlowAnalytics(actor: AuthUser) {
|
||||
assert.equal((await read({offset:1,limit:1})).analytics.conversationsList.length,1)
|
||||
assert.equal((await read({interface:"analytics-in"})).analytics.bytes,100)
|
||||
assert.equal((await read({userId:users[0]})).analytics.bytes,100)
|
||||
const tuple = { srcIp: "::ffff:198.18.241.2", dstIp: "8.8.8.8", srcPort: 12345, dstPort: 443, protocol: 6 }
|
||||
result = await read({ ...tuple, limit: 1 })
|
||||
assert.equal(result.analytics.bytes, 200)
|
||||
assert.equal(result.analytics.admittedTotals, undefined)
|
||||
assert.equal(result.pages.conversationsList.total, 1)
|
||||
assert.equal(result.pages.conversationsList.nextOffset, null)
|
||||
assert.equal((await read({ ...tuple, offset: 1 })).analytics.conversationsList.length, 0)
|
||||
for (const mismatch of [{ srcIp: "198.18.241.9" }, { dstIp: "8.8.4.4" }, { srcPort: 12346 }, { dstPort: 0 }, { protocol: 17 }]) {
|
||||
assert.equal((await read({ ...tuple, ...mismatch })).analytics.bytes, 0)
|
||||
}
|
||||
for (const invalid of [{ srcIp: "198.18.241.0/24" }, { dstPort: 65536 }, { protocol: 256 }]) await assert.rejects(read(invalid))
|
||||
await put(110,"analytics-duplicate-in",50,"198.18.241.1")
|
||||
assert.equal((await read()).analytics.bytes,300)
|
||||
assert.equal((await read({dedup:false,excludeMesh:false,excludeOverlay:false})).analytics.bytes,350)
|
||||
|
||||
@@ -61,7 +61,18 @@ export async function verifyMcpTerminalDiagnostics(actor: AuthUser, app: Fastify
|
||||
assert.equal(fixture.requests.length, beforeDenied)
|
||||
await pool.query("UPDATE servers SET enabled=true WHERE id=$1", [sourceId])
|
||||
const interfaces = fixture.payloads["/interface"], logs = fixture.payloads["/log"], resource = fixture.payloads["/system/resource"]
|
||||
fixture.payloads["/interface"] = [{ ".id": "*1", name: "private-fixture", comment: `password=${password} token=NEVER_LOG_TOKEN`, type: "ether" }]
|
||||
fixture.payloads["/interface"] = [{ ".id": "*1", name: "private-fixture", comment: `password=${password} token=NEVER_LOG_TOKEN`, type: "ether", "rx-error": "7", "link-downs": "0" }]
|
||||
const typed = await invoke({ diagnostic: "interface_counters", interface: "private-fixture", limit: 1 }) as unknown as {
|
||||
interfaceCounters: { rows: { name: string; counters: { rxErrors: string; linkDowns: string } }[]; routerUptime: string; resetHistoryAvailable: boolean }
|
||||
}
|
||||
assert.equal(typed.interfaceCounters.rows[0].name, "private-fixture")
|
||||
assert.equal(typed.interfaceCounters.rows[0].counters.rxErrors, "7")
|
||||
assert.equal(typed.interfaceCounters.rows[0].counters.linkDowns, "0")
|
||||
assert.equal(typed.interfaceCounters.resetHistoryAvailable, false)
|
||||
assert.ok(typed.interfaceCounters.routerUptime)
|
||||
assert.ok(!JSON.stringify(typed).includes(password))
|
||||
await assert.rejects(invoke({ diagnostic: "interface_counters", count: 1 }))
|
||||
await assert.rejects(invoke({ diagnostic: "interfaces", interface: "private-fixture" }))
|
||||
const redacted = await invoke({ diagnostic: "interfaces" })
|
||||
assert.ok(!redacted.output.includes(password)); assert.ok(!redacted.output.includes("NEVER_LOG_TOKEN")); assert.ok(redacted.output.includes("[redacted]"))
|
||||
fixture.payloads["/log"] = [{ ".id": "*1", time: "0", topics: "system,info", message: `${password} password=NEVER_PRINT_LOG_PASSWORD token=NEVER_PRINT_LOG_TOKEN` }]
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
import assert from "node:assert/strict"
|
||||
import { randomUUID } from "node:crypto"
|
||||
import { routeAiProfileSchema } from "@mmapp/contracts/mcp-routing"
|
||||
import { pool } from "../db/index.js"
|
||||
import { PATH_PROOF_VERSION, pathProofTag } from "../modules/mcp/path-proof-purpose.js"
|
||||
import { fingerprint, privateFingerprinter } from "../modules/mcp/security.js"
|
||||
|
||||
export async function assertSignedResilienceHistory({ connectionId, foreignConnectionId, serverId, callReport }: {
|
||||
connectionId: string
|
||||
foreignConnectionId?: string
|
||||
serverId: number
|
||||
callReport: (input: Record<string, unknown>) => Promise<unknown>
|
||||
}) {
|
||||
const profileId = randomUUID()
|
||||
const profile = routeAiProfileSchema.parse({
|
||||
name: "Failover acceptance", serverId, community: "65000:911", family: "ipv4",
|
||||
candidates: ["primary", "backup"].map(id => ({
|
||||
id, wanInterface: id + "-wan", downstreamInterface: id + "-down", jumpHostId: serverId, exitNodeId: serverId,
|
||||
gateway: "192.0.2.1", gatewayRef: { resource: "ipv4_route", id: "*a" },
|
||||
controlProbe: { targetInterface: id + "-exit", expectedHops: [{ serverId, interface: id + "-exit" }] },
|
||||
})),
|
||||
})
|
||||
const profileHash = fingerprint(profile)
|
||||
const sign = await privateFingerprinter("route-control-path-context-v1")
|
||||
const base = Date.now() - 60000
|
||||
const time = (offset: number) => new Date(base + offset).toISOString()
|
||||
const window = { from: time(0), outageAt: time(10000), restoreAt: time(20000), to: time(30000) }
|
||||
const run = () => callReport({
|
||||
target: { kind: "route-ai", profileId },
|
||||
controlProbe: { primaryCandidateId: "primary", backupCandidateId: "backup" },
|
||||
window, targetFailoverMs: 1500, targetFailbackMs: 1500,
|
||||
})
|
||||
const fixtureIds: string[] = []
|
||||
async function store(candidateId: string, status: "passed" | "failed", started: number, ended: number, owner = connectionId, epoch = "1") {
|
||||
const id = randomUUID()
|
||||
const dependencyProof = "f".repeat(64)
|
||||
const payload = {
|
||||
id, connectionId: owner, profileHash, candidateId, status, dependencyProof,
|
||||
proofPurpose: "control-path", proofVersion: PATH_PROOF_VERSION,
|
||||
startedAt: time(started), observedAt: time(ended), sourceProofs: [{ serverId, proof: epoch.repeat(64) }],
|
||||
}
|
||||
const proof = sign(pathProofTag("control-path") + fingerprint({ dependencyProof, value: payload }))
|
||||
await pool.query(
|
||||
"INSERT INTO mcp_path_checks(id,connection_id,profile_hash,candidate_id,status,evidence,created_at) VALUES ($1,$2,$3,$4,$5,$6::jsonb,$7)",
|
||||
[id, owner, profileHash, candidateId, status, JSON.stringify({ ...payload, proof }), payload.observedAt],
|
||||
)
|
||||
fixtureIds.push(id)
|
||||
return id
|
||||
}
|
||||
try {
|
||||
await pool.query(
|
||||
"INSERT INTO mcp_routing_profiles(id,connection_id,config,grant_expires_at) VALUES ($1,$2,$3::jsonb,$4)",
|
||||
[profileId, connectionId, JSON.stringify(profile), time(30000)],
|
||||
)
|
||||
const baseline = await store("primary", "passed", 8000, 9000)
|
||||
await store("primary", "failed", 10100, 10400)
|
||||
const firstGood = await store("backup", "passed", 10500, 11000)
|
||||
await store("primary", "passed", 20400, 20900)
|
||||
if (foreignConnectionId) await store("backup", "failed", 16000, 16500, foreignConnectionId)
|
||||
const passed = await run() as { status: string; baseline: { id: string }; failover: { firstGood: { id: string }; upperBoundMs: number }; serviceFailover: string; https: string; managementSsh: string }
|
||||
assert.equal(passed.status, "passed")
|
||||
assert.equal(passed.baseline.id, baseline)
|
||||
assert.equal(passed.failover.firstGood.id, firstGood)
|
||||
assert.equal(passed.failover.upperBoundMs, 1000)
|
||||
assert.equal(passed.serviceFailover, "inconclusive")
|
||||
assert.equal(passed.https, "inconclusive")
|
||||
assert.equal(passed.managementSsh, "inconclusive")
|
||||
|
||||
const moved = await store("backup", "passed", 13000, 13500, connectionId, "2")
|
||||
const changed = await run() as { status: string; reason: string }
|
||||
assert.equal(changed.status, "inconclusive")
|
||||
assert.equal(changed.reason, "SOURCE_IDENTITY_CHANGED")
|
||||
await pool.query("DELETE FROM mcp_path_checks WHERE id=$1", [moved])
|
||||
|
||||
await pool.query("UPDATE mcp_path_checks SET evidence=evidence-'proofPurpose' WHERE id=$1", [firstGood])
|
||||
const tampered = await run() as { status: string; reason: string }
|
||||
assert.equal(tampered.status, "inconclusive")
|
||||
assert.equal(tampered.reason, "INVALID_CONTROL_PATH_EVIDENCE")
|
||||
} finally {
|
||||
await pool.query("DELETE FROM mcp_path_checks WHERE id=ANY($1::uuid[])", [fixtureIds])
|
||||
await pool.query("DELETE FROM mcp_routing_profiles WHERE id=$1", [profileId])
|
||||
}
|
||||
}
|
||||
+21
-81
@@ -1,7 +1,7 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import { NavMain, type NavGroup } from "@/components/nav-main"
|
||||
import { NavMain, type NavGroup, type NavItem } from "@/components/nav-main"
|
||||
import { AppSwitcher } from "@/components/app-switcher"
|
||||
import { NavUser } from "@/components/nav-user"
|
||||
import {
|
||||
@@ -12,103 +12,43 @@ import {
|
||||
} from "@/components/ui/sidebar"
|
||||
import { navigationGroups } from "@/lib/navigation"
|
||||
import { useDataSource } from "@/lib/data-source"
|
||||
import { can,ensureAuthConfig } from "@/lib/auth"
|
||||
import { useEvoBGP } from "@/lib/evobgp-context"
|
||||
import {getSidebarCounts,getSidebarGreCount} from "@/shared/api/sidebar-counts"
|
||||
import {
|
||||
formatSidebarBadgeCount,
|
||||
mockSidebarBadgesByUrl,
|
||||
type SidebarCountsDto,
|
||||
} from "@/lib/sidebar-badges"
|
||||
import { pingProbes, servers } from "@/lib/data"
|
||||
|
||||
type LiveSidebarCounts = Partial<SidebarCountsDto> & {
|
||||
greTunnels?: number
|
||||
certificates?: number
|
||||
wireguard?: number
|
||||
ipsec?: number
|
||||
users?: number
|
||||
bgpSessions?: number
|
||||
vxlan?: number
|
||||
containers?: number
|
||||
/**
|
||||
* Точки проблем у разделов. В демо — из моков; живой источник проблем по разделам API пока не отдаёт,
|
||||
* поэтому в live-режиме точек нет (неизвестное не выдаём за «всё в норме» и не рисуем ложные сбои).
|
||||
*/
|
||||
function demoProblems(): Record<string, NavItem["problem"]> {
|
||||
const offline = servers.filter((s) => s.enabled && s.status === "offline").length
|
||||
const degraded = servers.filter((s) => s.enabled && s.status === "degraded").length
|
||||
const down = pingProbes.filter((p) => p.enabled && p.status === "down").length
|
||||
const warn = pingProbes.filter((p) => p.enabled && p.status === "warn").length
|
||||
return {
|
||||
"/servers": offline ? { tone: "er", label: `Не в сети: ${offline}` } : degraded ? { tone: "wn", label: `С ухудшением: ${degraded}` } : undefined,
|
||||
"/uptime": down ? { tone: "er", label: `Проверок с ошибкой: ${down}` } : warn ? { tone: "wn", label: `Проверок с предупреждением: ${warn}` } : undefined,
|
||||
}
|
||||
}
|
||||
|
||||
/** Боковое меню общего макета v2 и EvoBGP: переключатель приложений, поиск ⌘K, закреплённые, группы, профиль. */
|
||||
export function AppSidebar({ ...props }: React.ComponentProps<typeof Sidebar>) {
|
||||
const { mode, backendUrl, prefsHydrated } = useDataSource()
|
||||
const evo = useEvoBGP()
|
||||
const [mounted, setMounted] = React.useState(false)
|
||||
const [snapshot, setSnapshot] = React.useState<{source:string;counts:LiveSidebarCounts}|null>(null)
|
||||
const source=JSON.stringify([mode,backendUrl]),liveCounts=snapshot?.source===source?snapshot.counts:null
|
||||
const countsAllowed=can("mm:dashboard:read"),greAllowed=can("mm:filters:read")
|
||||
|
||||
const mockBadges = React.useMemo(() => mockSidebarBadgesByUrl(), [])
|
||||
|
||||
React.useEffect(() => {
|
||||
let cancelled=false
|
||||
void ensureAuthConfig().then(()=>{if(!cancelled)setMounted(true)})
|
||||
return()=>{cancelled=true}
|
||||
}, [])
|
||||
|
||||
React.useEffect(() => {
|
||||
if(!mounted||!prefsHydrated||mode!=="live")return
|
||||
let cancelled=false,revision=0,controller:AbortController|null=null
|
||||
const load=async()=>{
|
||||
controller?.abort();controller=new AbortController();const request=++revision,signal=AbortSignal.any([controller.signal,AbortSignal.timeout(30_000)])
|
||||
const publish=(counts:LiveSidebarCounts)=>{if(cancelled||request!==revision)return;setSnapshot(previous=>({source,counts:{...(previous?.source===source?previous.counts:{}),...counts}}))}
|
||||
await Promise.allSettled([
|
||||
can("mm:dashboard:read")?getSidebarCounts(backendUrl,signal).then(counts=>{if(can("mm:dashboard:read"))publish(counts)}):Promise.resolve(),
|
||||
can("mm:filters:read")?getSidebarGreCount(backendUrl,signal).then(greTunnels=>{if(can("mm:filters:read"))publish({greTunnels})}):Promise.resolve(),
|
||||
])
|
||||
}
|
||||
void load();const timer=window.setInterval(load,120_000)
|
||||
return()=>{cancelled=true;revision++;controller?.abort();window.clearInterval(timer)}
|
||||
},[mounted,mode,backendUrl,prefsHydrated,source,countsAllowed,greAllowed])
|
||||
const { mode, prefsHydrated } = useDataSource()
|
||||
|
||||
const navGroups = React.useMemo((): NavGroup[] => {
|
||||
function badgeFor(url: string): string | undefined {
|
||||
if (mode !== "live") return mockBadges[url]
|
||||
|
||||
if (url === "/domains" || url === "/ip-ranges" || url === "/asns") {
|
||||
if (!evo.settingsLoaded || !evo.enabled || !can("mm:settings:admin")) return undefined
|
||||
if (!evo.snapshot) return undefined
|
||||
if (url === "/domains") return formatSidebarBadgeCount(evo.snapshot.domains.length)
|
||||
if (url === "/ip-ranges") return formatSidebarBadgeCount(evo.snapshot.ipRanges.length)
|
||||
return formatSidebarBadgeCount(evo.snapshot.asns.length)
|
||||
}
|
||||
|
||||
if (!liveCounts||(!countsAllowed&&url!=="/gre")) return undefined
|
||||
const permission=({"/servers":"mm:servers:read","/users":"mm:users:read","/filters":"mm:filters:read","/uptime":"mm:uptime:read","/gre":"mm:filters:read","/certificates":"mm:certificates:read","/wireguard":"mm:network:read","/ipsec":"mm:network:read","/bgp":"mm:bgp:read","/vxlan":"mm:network:read","/containers":"mm:dashboard:read"} as Record<string,string>)[url]
|
||||
if(permission&&!can(permission))return undefined
|
||||
const format=(value:number|undefined)=>value===undefined?undefined:formatSidebarBadgeCount(value)
|
||||
|
||||
if (url === "/servers") return format(liveCounts.servers)
|
||||
if (url === "/users") return format(liveCounts.users )
|
||||
if (url === "/filters") return format(liveCounts.filterRules)
|
||||
if (url === "/uptime") return format(liveCounts.monitoringItems)
|
||||
if (url === "/gre") return format(liveCounts.greTunnels )
|
||||
if (url === "/certificates") return format(liveCounts.certificates )
|
||||
if (url === "/wireguard") return format(liveCounts.wireguard )
|
||||
if (url === "/ipsec") return format(liveCounts.ipsec )
|
||||
if (url === "/bgp") return format(liveCounts.bgpSessions )
|
||||
if (url === "/vxlan") return format(liveCounts.vxlan )
|
||||
if (url === "/containers") return format(liveCounts.containers )
|
||||
|
||||
return undefined
|
||||
}
|
||||
|
||||
const problems = prefsHydrated && mode !== "live" ? demoProblems() : {}
|
||||
return navigationGroups.map((g) => ({
|
||||
label: g.label,
|
||||
items: g.items.map((it) => ({
|
||||
title: it.title,
|
||||
url: it.url,
|
||||
icon: React.createElement(it.icon, { "aria-hidden": true }),
|
||||
badge: mounted ? badgeFor(it.url) : undefined,
|
||||
problem: problems[it.url],
|
||||
})),
|
||||
}))
|
||||
}, [mounted, mode, liveCounts, countsAllowed, mockBadges, evo.settingsLoaded, evo.enabled, evo.snapshot])
|
||||
}, [mode, prefsHydrated])
|
||||
|
||||
return (
|
||||
<Sidebar collapsible="icon" {...props}>
|
||||
<SidebarHeader>
|
||||
<SidebarHeader className="pb-1.5">
|
||||
<AppSwitcher />
|
||||
</SidebarHeader>
|
||||
<SidebarContent>
|
||||
|
||||
@@ -5,6 +5,7 @@ import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuShortcut,
|
||||
DropdownMenuTrigger,
|
||||
} from "@/components/ui/dropdown-menu"
|
||||
@@ -17,6 +18,7 @@ import {
|
||||
import {
|
||||
APP_SWITCHER_ICONS,
|
||||
CURRENT_APP_ID,
|
||||
authPortalBaseUrl,
|
||||
getCurrentApp,
|
||||
} from "@/lib/app-switcher-config"
|
||||
import { useAppSwitcherConfig } from "@/hooks/use-app-switcher"
|
||||
@@ -26,6 +28,8 @@ export function AppSwitcher() {
|
||||
const { isMobile } = useSidebar()
|
||||
const { config, isLoading } = useAppSwitcherConfig()
|
||||
const current = getCurrentApp(config)
|
||||
const portalBase = authPortalBaseUrl()
|
||||
const portalAppsUrl = portalBase ? `${portalBase}/admin/apps` : null
|
||||
const CurrentIcon = APP_SWITCHER_ICONS[current.icon] ?? APP_SWITCHER_ICONS.server
|
||||
|
||||
return (
|
||||
@@ -34,7 +38,7 @@ export function AppSwitcher() {
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger
|
||||
render={
|
||||
<SidebarMenuButton size="lg" className="aria-expanded:bg-muted" />
|
||||
<SidebarMenuButton size="lg" aria-label={`Переключатель приложений: ${current.name}`} className="aria-expanded:bg-muted" />
|
||||
}
|
||||
>
|
||||
<div
|
||||
@@ -89,6 +93,12 @@ export function AppSwitcher() {
|
||||
</DropdownMenuItem>
|
||||
)
|
||||
})}
|
||||
{portalAppsUrl ? (
|
||||
<>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem render={<a href={portalAppsUrl} />}>Настроить на портале</DropdownMenuItem>
|
||||
</>
|
||||
) : null}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</SidebarMenuItem>
|
||||
|
||||
@@ -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>
|
||||
)
|
||||
}
|
||||
@@ -6,6 +6,13 @@ import { navigationGroups } from "@/lib/navigation"
|
||||
import { Command, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList } from "@/components/ui/command"
|
||||
import { Dialog, DialogContent, DialogDescription, DialogTitle } from "@/components/ui/dialog"
|
||||
|
||||
const OPEN_EVENT = "mm:open-command-palette"
|
||||
|
||||
/** Открыть палитру из кнопки «Поиск и команды» (сайдбар) или поиска в шапке на телефоне. */
|
||||
export function openCommandPalette() {
|
||||
window.dispatchEvent(new Event(OPEN_EVENT))
|
||||
}
|
||||
|
||||
/** Keyboard search from the App Shell 12 composition, using installed Base UI primitives. */
|
||||
export function CommandPalette() {
|
||||
const [open, setOpen] = useState(false)
|
||||
@@ -26,8 +33,18 @@ export function CommandPalette() {
|
||||
setOpen(!open)
|
||||
}
|
||||
}
|
||||
function onOpen() {
|
||||
if (open) return
|
||||
returnFocusRef.current = document.activeElement instanceof HTMLElement ? document.activeElement : null
|
||||
setQuery("")
|
||||
setOpen(true)
|
||||
}
|
||||
window.addEventListener("keydown", onKey)
|
||||
return () => window.removeEventListener("keydown", onKey)
|
||||
window.addEventListener(OPEN_EVENT, onOpen)
|
||||
return () => {
|
||||
window.removeEventListener("keydown", onKey)
|
||||
window.removeEventListener(OPEN_EVENT, onOpen)
|
||||
}
|
||||
}, [open])
|
||||
|
||||
useEffect(() => {
|
||||
|
||||
@@ -1,39 +0,0 @@
|
||||
"use client"
|
||||
|
||||
import { Alert, AlertDescription, AlertTitle } from "@/components/reui/alert"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { DASHBOARD_SOURCES, type DashboardSource, type DashboardSources } from "@/lib/dashboard-source-state"
|
||||
|
||||
export function DashboardDataStatus({ sources, refreshing, onRefresh }: {
|
||||
sources: DashboardSources
|
||||
refreshing: boolean
|
||||
onRefresh: () => void
|
||||
}) {
|
||||
const failed = Object.values(sources).filter(source => source.error)
|
||||
const summary = failed.length ? `Не обновлены источники: ${failed.length}` : "Состояние источников"
|
||||
return <div className="flex flex-col gap-2">
|
||||
{failed.length > 0 && <Alert variant="destructive">
|
||||
<AlertTitle>{summary}</AlertTitle>
|
||||
<AlertDescription>Последние полученные данные сохранены. Если источник ещё не загрузился, его показатели неизвестны.</AlertDescription>
|
||||
</Alert>}
|
||||
<div className="flex flex-wrap items-start justify-between gap-2">
|
||||
<details className="min-w-0 text-sm" open={failed.length > 0 || undefined}>
|
||||
<summary className="cursor-pointer">Источники и время получения</summary>
|
||||
<ul className="mt-2 flex flex-col gap-1 text-xs">
|
||||
{(Object.keys(DASHBOARD_SOURCES) as DashboardSource[]).map(key => {
|
||||
const source = sources[key]
|
||||
return <li key={key} data-source={key} className={`break-words ${source?.error ? "text-destructive" : "text-muted-foreground"}`}>
|
||||
{DASHBOARD_SOURCES[key]}: {source?.error ? `ошибка обновления — ${source.error}. ` : ""}
|
||||
{source?.receivedAt != null ? <>Получено <time dateTime={new Date(source.receivedAt).toISOString()}>{new Date(source.receivedAt).toLocaleString("ru-RU")}</time>{source.error ? " · данные могут быть устаревшими" : ""}</> : "Успешных загрузок ещё нет"}
|
||||
{source?.sampledAt && Number.isFinite(Date.parse(source.sampledAt)) && <> · замер <time dateTime={source.sampledAt}>{new Date(source.sampledAt).toLocaleString("ru-RU")}</time></>}
|
||||
</li>
|
||||
})}
|
||||
</ul>
|
||||
</details>
|
||||
<div className="flex items-center gap-2">
|
||||
<span role="status" className="text-xs text-muted-foreground">{refreshing ? "Обновление данных…" : "Обновление завершено"}</span>
|
||||
<Button type="button" size="sm" variant="outline" onClick={onRefresh} disabled={refreshing}>Обновить данные</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
@@ -1,90 +0,0 @@
|
||||
"use client"
|
||||
|
||||
import Link from "next/link"
|
||||
import {
|
||||
Timeline,
|
||||
TimelineContent,
|
||||
TimelineDate,
|
||||
TimelineHeader,
|
||||
TimelineIndicator,
|
||||
TimelineItem,
|
||||
TimelineSeparator,
|
||||
TimelineTitle,
|
||||
} from "@/components/reui/timeline"
|
||||
import { Alert, AlertDescription, AlertTitle } from "@/components/reui/alert"
|
||||
import { cn } from "@/lib/utils"
|
||||
import type { EventItem } from "@mmapp/contracts/events"
|
||||
|
||||
function formatEventAge(iso: string): string {
|
||||
const ts = Date.parse(iso)
|
||||
if (!Number.isFinite(ts)) return "—"
|
||||
const diffMs = Math.max(0, Date.now() - ts)
|
||||
const minutes = Math.floor(diffMs / 60_000)
|
||||
if (minutes < 1) return "сейчас"
|
||||
if (minutes < 60) return `${minutes}м`
|
||||
const hours = Math.floor(minutes / 60)
|
||||
if (hours < 24) return `${hours}ч`
|
||||
const days = Math.floor(hours / 24)
|
||||
return `${days}д`
|
||||
}
|
||||
|
||||
const LEVEL_DOT: Record<EventItem["level"], string> = {
|
||||
critical: "border-destructive bg-destructive/20 group-data-completed/timeline-item:border-destructive",
|
||||
warning: "border-warning bg-warning/20 group-data-completed/timeline-item:border-warning",
|
||||
info: "border-info bg-info/20 group-data-completed/timeline-item:border-info",
|
||||
}
|
||||
|
||||
/**
|
||||
* Compact activity timeline.
|
||||
* Preview: https://reui.io/preview/base/timeline-3
|
||||
* Docs: https://reui.io/docs/components/base/timeline
|
||||
*/
|
||||
export function DashboardEventsTimeline({
|
||||
events,
|
||||
loading,
|
||||
error,
|
||||
}: {
|
||||
events: EventItem[]
|
||||
loading?: boolean
|
||||
error?: string | null
|
||||
}) {
|
||||
if (loading && events.length === 0) {
|
||||
return <p className="text-muted-foreground px-5 py-6 text-sm">Загрузка событий…</p>
|
||||
}
|
||||
if (error && events.length === 0) {
|
||||
return (
|
||||
<div className="px-5 py-4">
|
||||
<Alert variant="destructive">
|
||||
<AlertTitle>События недоступны</AlertTitle>
|
||||
<AlertDescription>{error}</AlertDescription>
|
||||
</Alert>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
if (events.length === 0) {
|
||||
return (
|
||||
<p className="text-muted-foreground px-5 py-6 text-sm">
|
||||
Событий пока нет.{" "}
|
||||
<Link href="/alerts" className="underline underline-offset-2">
|
||||
Оповещения
|
||||
</Link>
|
||||
</p>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<Timeline defaultValue={events.length} className="px-5 py-4">
|
||||
{events.map((event, index) => (
|
||||
<TimelineItem key={event.id} step={index + 1}>
|
||||
<TimelineHeader>
|
||||
<TimelineSeparator />
|
||||
<TimelineDate>{formatEventAge(event.createdAt)}</TimelineDate>
|
||||
<TimelineTitle className="text-[13px] leading-tight">{event.title}</TimelineTitle>
|
||||
<TimelineIndicator className={cn(LEVEL_DOT[event.level])} />
|
||||
</TimelineHeader>
|
||||
<TimelineContent className="text-xs leading-snug">{event.message}</TimelineContent>
|
||||
</TimelineItem>
|
||||
))}
|
||||
</Timeline>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,245 @@
|
||||
"use client"
|
||||
|
||||
import { useState, type ReactNode } from "react"
|
||||
import Link from "next/link"
|
||||
import { SearchIcon, TableIcon } from "lucide-react"
|
||||
import { Button, buttonVariants } from "@/components/ui/button"
|
||||
import { FramePanel } from "@/components/reui/frame"
|
||||
import { Alert, AlertDescription, AlertTitle } from "@/components/reui/alert"
|
||||
import { SectionFrame, ToneBadge, ToneDot, TONE_COLOR, type Tone } from "@/components/reui-kit/ops-blocks"
|
||||
import { cn } from "@/lib/utils"
|
||||
import type { EventItem } from "@mmapp/contracts/events"
|
||||
|
||||
export type HealthFactor = { label: string; value: string; ratio: number | null }
|
||||
|
||||
function factorTone(ratio: number): Tone {
|
||||
return ratio >= 0.85 ? "ok" : ratio >= 0.6 ? "wn" : "er"
|
||||
}
|
||||
|
||||
/**
|
||||
* Здоровье сети (блок health макета v3): кольцо сводного индекса и факторы.
|
||||
* Индекс — среднее долей исправных по факторам с известными данными.
|
||||
*/
|
||||
export function DashboardHealth({ factors }: { factors: HealthFactor[] }) {
|
||||
const known = factors.filter((f): f is HealthFactor & { ratio: number } => f.ratio != null)
|
||||
const score = known.length ? Math.round((known.reduce((sum, f) => sum + f.ratio, 0) / known.length) * 100) : null
|
||||
const tone: Tone = score == null ? "mu" : factorTone(score / 100)
|
||||
const badge = score == null ? "Нет данных" : tone === "ok" ? "В норме" : tone === "wn" ? "С замечаниями" : "Требует внимания"
|
||||
const circumference = 2 * Math.PI * 52
|
||||
return (
|
||||
<SectionFrame
|
||||
title="Здоровье сети"
|
||||
description="Сводный индекс — среднее долей исправных: пробы, задержка, свежесть данных, серверы и туннели"
|
||||
actions={<ToneBadge tone={tone} size="lg">{badge}</ToneBadge>}
|
||||
panelClassName="grid grid-cols-1 items-center gap-6 p-5 md:grid-cols-[200px_minmax(0,1fr)]"
|
||||
>
|
||||
<div className="flex flex-col items-center gap-1.5">
|
||||
<div className="relative size-[150px]">
|
||||
<svg viewBox="0 0 140 140" width="150" height="150" role="img" aria-label={score == null ? "Индекс здоровья сети неизвестен" : `Индекс здоровья сети ${score} из 100`}>
|
||||
<circle cx="70" cy="70" r="52" fill="none" stroke="var(--muted)" strokeWidth="12" />
|
||||
{score != null ? (
|
||||
<circle cx="70" cy="70" r="52" fill="none" stroke={TONE_COLOR[tone]} strokeWidth="12" strokeLinecap="round" strokeDasharray={`${(circumference * score) / 100} ${circumference}`} transform="rotate(-90 70 70)" />
|
||||
) : null}
|
||||
</svg>
|
||||
<div className="absolute inset-0 flex flex-col items-center justify-center">
|
||||
<b className="text-[34px] leading-none font-semibold tabular-nums">{score ?? "—"}</b>
|
||||
<span className="text-muted-foreground mt-0.5 text-xs">из 100</span>
|
||||
</div>
|
||||
</div>
|
||||
<span className="text-muted-foreground text-xs">{known.length} из {factors.length} факторов с данными</span>
|
||||
</div>
|
||||
<div className="flex flex-col gap-2.5">
|
||||
{factors.map((factor) => (
|
||||
<div key={factor.label} className="grid grid-cols-[130px_minmax(0,1fr)_auto] items-center gap-2.5 text-[13px]">
|
||||
<span>{factor.label}</span>
|
||||
<span aria-hidden="true" className="bg-muted h-1.5 overflow-hidden rounded-[3px]">
|
||||
{factor.ratio != null ? (
|
||||
<i className="block h-full rounded-[3px]" style={{ width: `${Math.round(factor.ratio * 100)}%`, background: TONE_COLOR[factorTone(factor.ratio)] }} />
|
||||
) : null}
|
||||
</span>
|
||||
<span className="min-w-11 text-right font-mono">{factor.value}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</SectionFrame>
|
||||
)
|
||||
}
|
||||
|
||||
const LEVEL: Record<EventItem["level"], { tone: Tone; label: string }> = {
|
||||
critical: { tone: "er", label: "Сбой" },
|
||||
warning: { tone: "wn", label: "Внимание" },
|
||||
info: { tone: "in", label: "Инфо" },
|
||||
}
|
||||
|
||||
function hhmm(iso: string) {
|
||||
const ts = Date.parse(iso)
|
||||
return Number.isFinite(ts) ? new Date(ts).toLocaleTimeString("ru-RU", { hour: "2-digit", minute: "2-digit" }) : "—"
|
||||
}
|
||||
|
||||
/** Лента инцидентов (блок timeline макета v3) из последних событий системы. */
|
||||
export function DashboardIncidents({ events, loading, error }: { events: EventItem[]; loading?: boolean; error?: string | null }) {
|
||||
let body: ReactNode
|
||||
if (loading && events.length === 0) body = <p className="text-muted-foreground px-4 py-6 text-sm">Загрузка событий…</p>
|
||||
else if (error && events.length === 0) {
|
||||
body = (
|
||||
<div className="p-4">
|
||||
<Alert variant="destructive">
|
||||
<AlertTitle>События недоступны</AlertTitle>
|
||||
<AlertDescription>{error}</AlertDescription>
|
||||
</Alert>
|
||||
</div>
|
||||
)
|
||||
} else if (events.length === 0) body = <p className="text-muted-foreground px-4 py-6 text-sm">Событий пока нет.</p>
|
||||
else {
|
||||
body = (
|
||||
<ol className="py-1.5">
|
||||
{events.map((event, index) => {
|
||||
const level = LEVEL[event.level] ?? LEVEL.info
|
||||
return (
|
||||
<li key={event.id} className="grid grid-cols-[62px_16px_minmax(0,1fr)] items-start gap-2.5 px-4 py-2 text-[13px]">
|
||||
<time dateTime={event.createdAt} className="text-muted-foreground pt-px font-mono text-xs">{hhmm(event.createdAt)}</time>
|
||||
<span aria-hidden="true" className="flex h-full flex-col items-center">
|
||||
<i className="mt-1 size-[9px] rounded-full" style={{ background: TONE_COLOR[level.tone] }} />
|
||||
{index < events.length - 1 ? <u className="bg-border mt-0.5 min-h-[18px] w-px flex-1" /> : null}
|
||||
</span>
|
||||
<span className="min-w-0">
|
||||
<ToneBadge tone={level.tone} mark={false} className="mr-2">{level.label}</ToneBadge>
|
||||
<b className="font-medium">{event.title}</b>
|
||||
{event.message ? <span className="text-muted-foreground mt-0.5 block text-xs">{event.message}</span> : null}
|
||||
</span>
|
||||
</li>
|
||||
)
|
||||
})}
|
||||
</ol>
|
||||
)
|
||||
}
|
||||
return (
|
||||
<SectionFrame
|
||||
title="Лента инцидентов"
|
||||
description="Последние события · причины и связанные объекты"
|
||||
actions={<Link href="/alerts" className={buttonVariants({ variant: "outline", size: "sm" })}>Все события</Link>}
|
||||
>
|
||||
{body}
|
||||
</SectionFrame>
|
||||
)
|
||||
}
|
||||
|
||||
export type AttentionGridRow = {
|
||||
id: string
|
||||
title: string
|
||||
kind: "Сервер" | "Туннель" | "Проверка"
|
||||
hint: string
|
||||
href: string
|
||||
tone: Tone
|
||||
/** Подтверждённая проблема; false — состояние неизвестно. */
|
||||
confirmed: boolean
|
||||
}
|
||||
|
||||
const PAGE = 50
|
||||
|
||||
/**
|
||||
* Требует внимания (блок grid макета v3): вкладки, поиск и строки-ссылки на объект.
|
||||
* Пустые категории перечислены в подвале, чтобы «нет проблем» не путалось с «нет данных».
|
||||
*/
|
||||
export function DashboardAttentionGrid({ rows, emptyNotes }: { rows: AttentionGridRow[]; emptyNotes: string[] }) {
|
||||
const [view, setView] = useState<"all" | "confirmed">("all")
|
||||
const [query, setQuery] = useState("")
|
||||
const [visible, setVisible] = useState(PAGE)
|
||||
const confirmed = rows.filter((row) => row.confirmed)
|
||||
const q = query.trim().toLowerCase()
|
||||
const shown = (view === "all" ? rows : confirmed).filter((row) => !q || `${row.title} ${row.kind} ${row.hint}`.toLowerCase().includes(q))
|
||||
const tabs = [
|
||||
{ id: "all" as const, label: "Все", count: rows.length },
|
||||
{ id: "confirmed" as const, label: "С проблемами", count: confirmed.length },
|
||||
]
|
||||
return (
|
||||
<SectionFrame title="Требует внимания" description="Серверы · Туннели · Проверки" icon={<TableIcon />} bare>
|
||||
<div role="tablist" aria-label="Виды" className="flex flex-wrap gap-x-1 border-b px-2.5">
|
||||
{tabs.map((tab) => (
|
||||
<button
|
||||
key={tab.id}
|
||||
type="button"
|
||||
role="tab"
|
||||
aria-selected={view === tab.id}
|
||||
onClick={() => { setView(tab.id); setVisible(PAGE) }}
|
||||
className={cn(
|
||||
"text-muted-foreground hover:text-foreground -mb-px inline-flex h-[38px] items-center gap-1.5 border-b-2 border-transparent px-2 text-[13px] font-medium transition-colors",
|
||||
view === tab.id && "border-foreground text-foreground",
|
||||
)}
|
||||
>
|
||||
{tab.label}{" "}
|
||||
<em className={cn("bg-muted text-muted-foreground inline-flex h-5 min-w-5 items-center justify-center rounded-md px-1.5 font-mono text-xs not-italic", view === tab.id && "bg-foreground/12 text-foreground")}>{tab.count}</em>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<div className="flex flex-wrap items-center gap-2 px-2.5 py-2">
|
||||
<label className="border-input bg-input/30 text-muted-foreground focus-within:border-ring flex h-8 min-w-[180px] flex-[0_1_320px] items-center gap-2 rounded-lg border px-2.5 transition-colors">
|
||||
<SearchIcon aria-hidden="true" className="size-3.5 shrink-0" />
|
||||
<input value={query} onChange={(event) => { setQuery(event.target.value); setVisible(PAGE) }} placeholder="Поиск по имени и полям…" aria-label="Поиск в таблице" className="text-foreground placeholder:text-muted-foreground min-w-0 flex-1 bg-transparent text-[13px] outline-none" />
|
||||
</label>
|
||||
{q ? <span className="text-muted-foreground ml-auto text-xs tabular-nums">{shown.length} из {rows.length}</span> : null}
|
||||
</div>
|
||||
<FramePanel className="max-h-[560px] overflow-auto p-0">
|
||||
<div className="min-w-[640px]">
|
||||
<div aria-hidden="true" className="bg-muted/55 text-muted-foreground sticky top-0 z-[1] grid h-10 grid-cols-[minmax(200px,2fr)_112px_minmax(120px,1fr)_minmax(160px,2fr)] items-center gap-x-3 border-b px-3.5 text-xs font-medium">
|
||||
<span>Объект</span>
|
||||
<span>Статус</span>
|
||||
<span>Тип</span>
|
||||
<span>Сообщение</span>
|
||||
</div>
|
||||
{shown.length === 0 ? (
|
||||
<p className="text-muted-foreground px-4 py-8 text-center text-sm">{rows.length === 0 ? "Проблем не обнаружено" : "Ничего не найдено"}</p>
|
||||
) : (
|
||||
shown.slice(0, visible).map((row) => (
|
||||
<Link
|
||||
key={`${row.kind}:${row.id}`}
|
||||
href={row.href}
|
||||
className="hover:bg-muted/45 focus-visible:ring-ring grid min-h-[52px] grid-cols-[minmax(200px,2fr)_112px_minmax(120px,1fr)_minmax(160px,2fr)] items-center gap-x-3 border-b px-3.5 transition-colors outline-none last:border-b-0 focus-visible:ring-2 focus-visible:ring-inset"
|
||||
>
|
||||
<span className="flex min-w-0 items-center gap-2 py-2">
|
||||
<ToneDot tone={row.tone} />
|
||||
<span className="min-w-0">
|
||||
<span className="block truncate font-mono text-[13px] font-medium">{row.title}</span>
|
||||
<span className="text-muted-foreground block font-mono text-xs">{row.kind}</span>
|
||||
</span>
|
||||
</span>
|
||||
<span><ToneBadge tone={row.tone}>{row.tone === "er" ? "Сбой" : row.confirmed ? "Внимание" : "Неизвестно"}</ToneBadge></span>
|
||||
<span className="font-mono text-[12.5px]">{row.kind}</span>
|
||||
<span className="min-w-0 font-mono text-[12.5px] wrap-anywhere">{row.hint}</span>
|
||||
</Link>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
{shown.length > visible ? (
|
||||
<div className="flex justify-center border-t p-2">
|
||||
<Button type="button" variant="ghost" size="sm" onClick={() => setVisible((count) => count + PAGE)}>Показать ещё {Math.min(PAGE, shown.length - visible)}</Button>
|
||||
</div>
|
||||
) : null}
|
||||
</FramePanel>
|
||||
{emptyNotes.length ? (
|
||||
<div className="text-muted-foreground flex flex-wrap gap-x-3 gap-y-1 px-4 py-2 text-xs">
|
||||
{emptyNotes.map((note) => <span key={note}>{note}</span>)}
|
||||
</div>
|
||||
) : null}
|
||||
</SectionFrame>
|
||||
)
|
||||
}
|
||||
|
||||
export type QuickLink = { id: string; title: string; description: string; href: string }
|
||||
|
||||
/** Быстрые переходы (блок cards макета v3). */
|
||||
export function DashboardQuickLinks({ links }: { links: QuickLink[] }) {
|
||||
return (
|
||||
<SectionFrame title="Быстрые переходы" description="Другие разделы управления сетью" panelClassName="grid grid-cols-[repeat(auto-fit,minmax(260px,1fr))] gap-3 p-3">
|
||||
{links.map((link) => (
|
||||
<Link key={link.id} href={link.href} className="bg-muted/25 hover:bg-muted/50 focus-visible:ring-ring rounded-lg border p-3.5 transition-colors outline-none focus-visible:ring-2">
|
||||
<div className="flex items-center justify-between gap-2">
|
||||
<b className="text-sm font-semibold">{link.title}</b>
|
||||
<ToneBadge tone="in" mark={false}>Открыть</ToneBadge>
|
||||
</div>
|
||||
<div className="text-muted-foreground mt-1.5 text-[13px]">{link.description}</div>
|
||||
</Link>
|
||||
))}
|
||||
</SectionFrame>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
"use client"
|
||||
|
||||
import type { ReactNode } from "react"
|
||||
import { ActivityIcon, BellIcon, BoxIcon, ChartColumnIcon, DatabaseIcon, GlobeIcon, LinkIcon, LockIcon, RouteIcon, ServerIcon } from "lucide-react"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { FramePanel } from "@/components/reui/frame"
|
||||
import { IconTile } from "@/components/reui/icon-tile"
|
||||
import { SectionFrame, ToneBadge, TONE_COLOR, type Tone } from "@/components/reui-kit/ops-blocks"
|
||||
import { DASHBOARD_SOURCES, type DashboardSource, type DashboardSources } from "@/lib/dashboard-source-state"
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
const SOURCE_ICON: Record<DashboardSource, ReactNode> = {
|
||||
servers: <ServerIcon />, probes: <ActivityIcon />, bgp: <RouteIcon />, gre: <LinkIcon />, wg: <LockIcon />,
|
||||
vxlan: <BoxIcon />, traffic: <ChartColumnIcon />, internetPath: <GlobeIcon />, events: <BellIcon />,
|
||||
}
|
||||
|
||||
export type SourceRow = {
|
||||
key: DashboardSource
|
||||
name: string
|
||||
tone: Tone
|
||||
label: string
|
||||
receivedAt: number | null
|
||||
sampledAt: string | null
|
||||
error: string | null
|
||||
}
|
||||
|
||||
/** Состояние каждого источника дашборда: обновлён, устарел (ошибка после успеха), нет загрузок или ожидание. */
|
||||
export function dashboardSourceRows(sources: DashboardSources): SourceRow[] {
|
||||
return (Object.keys(DASHBOARD_SOURCES) as DashboardSource[]).map((key) => {
|
||||
const source = sources[key]
|
||||
const receivedAt = source?.receivedAt ?? null
|
||||
const error = source?.error ?? null
|
||||
const sampledAt = source?.sampledAt && Number.isFinite(Date.parse(source.sampledAt)) ? source.sampledAt : null
|
||||
const tone: Tone = error ? (receivedAt != null ? "wn" : "er") : receivedAt != null ? "ok" : "mu"
|
||||
const label = error ? (receivedAt != null ? "Устарел" : "Нет загрузок") : receivedAt != null ? "Обновлён" : "Ожидание"
|
||||
return { key, name: DASHBOARD_SOURCES[key], tone, label, receivedAt, sampledAt, error }
|
||||
})
|
||||
}
|
||||
|
||||
function Clock({ at }: { at: number | string | null }) {
|
||||
if (at == null) return <b className="text-foreground font-mono font-medium">—</b>
|
||||
const date = new Date(at)
|
||||
return (
|
||||
<time dateTime={typeof at === "string" ? at : date.toISOString()} className="text-foreground font-mono font-medium">
|
||||
{date.toLocaleTimeString("ru-RU")}
|
||||
</time>
|
||||
)
|
||||
}
|
||||
|
||||
export function sourceErrorText(row: SourceRow) {
|
||||
if (!row.error) return null
|
||||
return row.receivedAt != null
|
||||
? `Ошибка обновления — ${row.error} · данные могут быть устаревшими`
|
||||
: `Ошибка обновления — ${row.error} · успешных загрузок ещё нет`
|
||||
}
|
||||
|
||||
/**
|
||||
* Сводка источников дашборда (блок sources макета v3): итог слева, плитки источников справа.
|
||||
* @see https://reui.io/docs/components/base/frame
|
||||
*/
|
||||
export function DashboardSourcesSummary({ rows, refreshing, onRefresh }: {
|
||||
rows: SourceRow[]
|
||||
refreshing: boolean
|
||||
onRefresh: () => void
|
||||
}) {
|
||||
const count = (tone: Tone) => rows.filter((row) => row.tone === tone).length
|
||||
const ok = count("ok")
|
||||
const segments = ([
|
||||
["ok", "Обновлены", count("ok")],
|
||||
["wn", "С ошибкой", count("wn")],
|
||||
["er", "Нет загрузок", count("er")],
|
||||
["mu", "Ожидание", count("mu")],
|
||||
] as const).filter(([, , n]) => n > 0)
|
||||
const sub = [
|
||||
count("wn") ? `${count("wn")} с ошибкой — показаны прошлые данные` : null,
|
||||
count("er") ? `${count("er")} без успешных загрузок` : null,
|
||||
count("mu") ? `${count("mu")} ожидают первой загрузки` : null,
|
||||
].filter(Boolean).join(" · ") || "Все источники получены"
|
||||
|
||||
return (
|
||||
<SectionFrame
|
||||
title="Сводка источников"
|
||||
description="Время получения и замера по каждому источнику дашборда · подробности — на вкладке «Источники и время получения»"
|
||||
icon={<DatabaseIcon />}
|
||||
bare
|
||||
actions={
|
||||
<>
|
||||
<span role="status" className="text-muted-foreground text-xs">{refreshing ? "Обновление данных…" : "Обновление завершено"}</span>
|
||||
<Button type="button" size="sm" variant="outline" onClick={onRefresh} disabled={refreshing} aria-label="Обновить данные источников">Обновить данные</Button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<FramePanel className="grid grid-cols-1 p-0 min-[1100px]:grid-cols-[260px_minmax(0,1fr)]">
|
||||
<div className="flex min-w-0 flex-col gap-2 border-b px-[18px] py-4 min-[1100px]:border-r min-[1100px]:border-b-0">
|
||||
<div className="text-muted-foreground text-[0.8rem]">Источники обновлены</div>
|
||||
<div className="flex items-baseline gap-0.5">
|
||||
<span className="text-[30px] leading-tight font-semibold tracking-tight tabular-nums">{ok}</span>
|
||||
<span className="text-muted-foreground ml-0.5 text-base">/ {rows.length}</span>
|
||||
</div>
|
||||
<div className="text-muted-foreground text-xs">{sub}</div>
|
||||
<div role="img" aria-label={segments.map(([, label, n]) => `${label}: ${n}`).join(", ")} className="mt-1.5 flex h-2 gap-[3px]">
|
||||
{segments.map(([tone, label, n]) => (
|
||||
<i key={label} className="block h-full min-w-1.5 rounded-full" style={{ flex: n, background: TONE_COLOR[tone] }} />
|
||||
))}
|
||||
</div>
|
||||
<div className="text-muted-foreground grid grid-cols-2 gap-x-3.5 gap-y-1.5 text-xs">
|
||||
{segments.map(([tone, label, n]) => (
|
||||
<span key={label} className="flex min-w-0 items-center gap-1.5">
|
||||
<i aria-hidden="true" className="size-2 shrink-0 rounded-full" style={{ background: TONE_COLOR[tone] }} />
|
||||
{label}
|
||||
<b className="text-foreground ml-auto font-medium tabular-nums">{n}</b>
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
<p className="text-muted-foreground mt-auto border-t border-dashed pt-2.5 text-xs leading-snug">
|
||||
Последние полученные данные сохранены. Если источник ещё не загрузился, его показатели неизвестны.
|
||||
</p>
|
||||
</div>
|
||||
<ul className="grid grid-cols-2 min-[1100px]:grid-cols-3">
|
||||
{rows.map((row) => {
|
||||
const error = sourceErrorText(row)
|
||||
return (
|
||||
<li
|
||||
key={row.key}
|
||||
data-source={row.key}
|
||||
className="flex min-w-0 flex-col gap-2 border-r border-b px-3.5 py-3 max-[1099px]:even:border-r-0 min-[1100px]:[&:nth-child(3n)]:border-r-0 min-[1100px]:[&:nth-last-child(-n+3)]:border-b-0"
|
||||
>
|
||||
<div className="flex min-w-0 items-center gap-2.5">
|
||||
<IconTile variant="outline" size="sm" aria-hidden="true" style={{ color: row.tone === "ok" || row.tone === "mu" ? "var(--muted-foreground)" : TONE_COLOR[row.tone] }}>
|
||||
{SOURCE_ICON[row.key]}
|
||||
</IconTile>
|
||||
<span className="min-w-0 flex-1 truncate text-sm font-medium">{row.name}</span>
|
||||
<ToneBadge tone={row.tone} size="default">{row.label}</ToneBadge>
|
||||
</div>
|
||||
<div className="text-muted-foreground flex flex-wrap gap-x-3.5 gap-y-1 text-xs">
|
||||
<span>Получено <Clock at={row.receivedAt} /></span>
|
||||
<span>Замер <Clock at={row.sampledAt} /></span>
|
||||
</div>
|
||||
{error ? (
|
||||
<p className={cn("text-xs leading-snug", row.tone === "wn" ? "text-warning-foreground" : "text-destructive-foreground")}>{error}</p>
|
||||
) : null}
|
||||
</li>
|
||||
)
|
||||
})}
|
||||
</ul>
|
||||
</FramePanel>
|
||||
</SectionFrame>
|
||||
)
|
||||
}
|
||||
@@ -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>
|
||||
)
|
||||
}
|
||||
@@ -1,35 +1,62 @@
|
||||
"use client"
|
||||
|
||||
import { useEffect, useState } from "react"
|
||||
import Link from "next/link"
|
||||
import { ChevronDownIcon } from "lucide-react"
|
||||
import { OpsPanel } from "@/components/ops-panel"
|
||||
import { Alert, AlertDescription, AlertTitle } from "@/components/reui/alert"
|
||||
import { buttonVariants } from "@/components/ui/button"
|
||||
import {
|
||||
Collapsible,
|
||||
CollapsibleContent,
|
||||
CollapsibleTrigger,
|
||||
} from "@/components/ui/collapsible"
|
||||
import { cn } from "@/lib/utils"
|
||||
import { Alert, AlertDescription, AlertTitle } from "@/components/reui/alert"
|
||||
import { SectionFrame, TONE_COLOR, type Tone } from "@/components/reui-kit/ops-blocks"
|
||||
import type { InternetPathViewModel } from "@/lib/dashboard-internet-path"
|
||||
import { InternetPathMapCanvas } from "@/components/dashboard/internet-path-map"
|
||||
import type { ServerStatus } from "@/lib/data"
|
||||
import { InternetPathSummary } from "@/components/dashboard/internet-path-summary"
|
||||
|
||||
const PATH_MAP_OPEN_LS = "mm:dashboard-path-map-open"
|
||||
const STATUS_TONE: Record<ServerStatus, Tone> = { online: "ok", degraded: "wn", offline: "er", unknown: "mu" }
|
||||
const X = [13, 37, 62, 86]
|
||||
|
||||
function readMapOpen(): boolean {
|
||||
if (typeof window === "undefined") return true
|
||||
try {
|
||||
const raw = localStorage.getItem(PATH_MAP_OPEN_LS)
|
||||
if (raw === "0") return false
|
||||
if (raw === "1") return true
|
||||
} catch {
|
||||
/* ignore */
|
||||
type TopoNode = { label: string; sub: string; tone: Tone }
|
||||
|
||||
/** Схема пути Home → WAN → JH → Exit (блок topo макета v3); участок WAN→JH — модель связности, пунктиром. */
|
||||
function InternetPathTopo({ model }: { model: InternetPathViewModel | null }) {
|
||||
const hop = model?.currentHop ?? model?.primaryHop ?? null
|
||||
const wan = hop?.wan ?? model?.activeWanUplink ?? null
|
||||
const jh = hop?.jumpHost ?? model?.fallbackJumpHost ?? null
|
||||
const exit = hop?.exitNode ?? model?.fallbackExitNode ?? null
|
||||
if (!model || !jh || !exit) {
|
||||
return <p className="text-muted-foreground flex h-[300px] items-center justify-center text-sm">Нет полного набора узлов для схемы пути</p>
|
||||
}
|
||||
return true
|
||||
const nodes: TopoNode[] = [
|
||||
{ label: model.homeRouter.name, sub: "Home Router", tone: STATUS_TONE[model.homeRouter.status] },
|
||||
{ label: wan ? wan.isp || wan.name : "WAN", sub: wan ? `WAN-аплинк ${wan.iface}` : "WAN не определён", tone: wan ? "ok" : "mu" },
|
||||
{ label: jh.name, sub: "JumpHost", tone: STATUS_TONE[jh.status] },
|
||||
{ label: exit.name, sub: `Exit Node${exit.country ? ` · ${exit.country}` : ""}`, tone: STATUS_TONE[exit.status] },
|
||||
]
|
||||
const links: Array<{ label: string | null; dashed: boolean }> = [
|
||||
{ label: null, dashed: false },
|
||||
{ label: hop?.wanJhMetrics.pingMs != null ? String(hop.wanJhMetrics.pingMs) : null, dashed: true },
|
||||
{ label: hop?.jhExitMetrics.pingMs != null ? String(hop.jhExitMetrics.pingMs) : null, dashed: false },
|
||||
]
|
||||
return (
|
||||
<div className="relative h-[300px]" role="img" aria-label={`Путь: ${nodes.map((n) => n.label).join(" → ")}`}>
|
||||
<svg className="absolute inset-0 size-full" aria-hidden="true">
|
||||
{links.map((link, i) => (
|
||||
<line key={i} x1={`${X[i]}%`} y1="50%" x2={`${X[i + 1]}%`} y2="50%" stroke={link.dashed ? "var(--warning)" : "var(--success)"} strokeWidth="1.5" strokeDasharray={link.dashed ? "5 5" : undefined} />
|
||||
))}
|
||||
</svg>
|
||||
{links.map((link, i) => link.label ? (
|
||||
<span key={i} className="bg-card absolute -translate-1/2 rounded-[5px] border px-2 py-0.5 font-mono text-xs" style={{ left: `${(X[i] + X[i + 1]) / 2}%`, top: "50%" }}>{link.label}</span>
|
||||
) : null)}
|
||||
{nodes.map((node, i) => (
|
||||
<div key={i} className="bg-card absolute flex min-w-[132px] -translate-1/2 items-center gap-2 rounded-[9px] border-[1.5px] py-1.5 pr-3 pl-2.5" style={{ left: `${X[i]}%`, top: "50%", borderColor: TONE_COLOR[node.tone] }}>
|
||||
<span className="size-2 shrink-0 rounded-full" style={{ background: TONE_COLOR[node.tone] }} />
|
||||
<span className="min-w-0">
|
||||
<b className="block text-[13px] font-semibold whitespace-nowrap">{node.label}</b>
|
||||
<span className="text-muted-foreground block text-xs whitespace-nowrap">{node.sub}</span>
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/** Internet path и Сводка маршрута — два блока макета v3 (topo и kv). */
|
||||
export function InternetPathPanel({
|
||||
model,
|
||||
loading,
|
||||
@@ -39,59 +66,30 @@ export function InternetPathPanel({
|
||||
loading?: boolean
|
||||
error?: string | null
|
||||
}) {
|
||||
const [open, setOpen] = useState(true)
|
||||
const [hydrated, setHydrated] = useState(false)
|
||||
|
||||
useEffect(() => {
|
||||
queueMicrotask(() => {
|
||||
setOpen(readMapOpen())
|
||||
setHydrated(true)
|
||||
})
|
||||
}, [])
|
||||
|
||||
function handleOpenChange(next: boolean) {
|
||||
setOpen(next)
|
||||
try {
|
||||
localStorage.setItem(PATH_MAP_OPEN_LS, next ? "1" : "0")
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<OpsPanel
|
||||
title="Internet path"
|
||||
description="Home → WAN → JH → Exit"
|
||||
headerRight={
|
||||
<Link href="/network-map" className={cn(buttonVariants({ variant: "outline", size: "sm" }), "h-7 text-xs")}>
|
||||
Карта сети →
|
||||
</Link>
|
||||
}
|
||||
contentClassName="flex flex-col gap-3 px-5 pb-4"
|
||||
>
|
||||
{error ? (
|
||||
<Alert variant="destructive">
|
||||
<AlertTitle>Не удалось загрузить путь</AlertTitle>
|
||||
<AlertDescription>{error}</AlertDescription>
|
||||
</Alert>
|
||||
) : null}
|
||||
{loading && !model ? (
|
||||
<div className="h-20 animate-pulse rounded-md bg-muted/40" />
|
||||
) : (
|
||||
<InternetPathSummary model={model} />
|
||||
)}
|
||||
|
||||
<Collapsible open={hydrated ? open : true} onOpenChange={handleOpenChange}>
|
||||
<CollapsibleTrigger
|
||||
className={cn(buttonVariants({ variant: "ghost", size: "sm" }), "h-7 w-fit gap-1.5 text-xs")}
|
||||
>
|
||||
<ChevronDownIcon className={cn("size-3.5 transition-transform", open && "rotate-180")} />
|
||||
{open ? "Скрыть карту" : "Показать карту"}
|
||||
</CollapsibleTrigger>
|
||||
<CollapsibleContent>
|
||||
<InternetPathMapCanvas model={model} />
|
||||
</CollapsibleContent>
|
||||
</Collapsible>
|
||||
</OpsPanel>
|
||||
<>
|
||||
<SectionFrame
|
||||
title="Internet path"
|
||||
description="Home → WAN → JH → Exit · пунктир WAN→JH — модель связности, маршрут не подтверждён"
|
||||
actions={<Link href="/network-map" className={buttonVariants({ variant: "outline", size: "sm" })}>Карта сети →</Link>}
|
||||
panelClassName="overflow-x-auto bg-[radial-gradient(var(--border)_1px,transparent_1px)] bg-size-[20px_20px]"
|
||||
>
|
||||
{error ? (
|
||||
<Alert variant="destructive" className="m-3 w-auto">
|
||||
<AlertTitle>Не удалось загрузить путь</AlertTitle>
|
||||
<AlertDescription>{error}</AlertDescription>
|
||||
</Alert>
|
||||
) : null}
|
||||
<div className="min-w-[720px]">
|
||||
{loading && !model ? <div className="bg-muted/40 m-4 h-[268px] animate-pulse rounded-md" /> : <InternetPathTopo model={model} />}
|
||||
</div>
|
||||
</SectionFrame>
|
||||
<SectionFrame
|
||||
title="Сводка маршрута"
|
||||
description={`Модель связности; маршрут не подтверждён. ${model?.currentPath?.reason ?? "Текущий маршрут не подтверждён"}`}
|
||||
>
|
||||
{loading && !model ? <div className="bg-muted/40 m-4 h-20 animate-pulse rounded-md" /> : <InternetPathSummary model={model} />}
|
||||
</SectionFrame>
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -3,13 +3,10 @@
|
||||
import type { ReactNode } from "react"
|
||||
import Link from "next/link"
|
||||
import { Badge } from "@/components/reui/badge"
|
||||
import { IconTile } from "@/components/reui/icon-tile"
|
||||
import { StatusBadge } from "@/components/status-badge"
|
||||
import { Flag } from "@/components/flag"
|
||||
import type { InternetPathViewModel } from "@/lib/dashboard-internet-path"
|
||||
import type { ServerStatus } from "@/lib/data"
|
||||
import { cn } from "@/lib/utils"
|
||||
import { ArrowRightIcon, HomeIcon, RadioIcon, ServerIcon, GlobeIcon } from "lucide-react"
|
||||
|
||||
function pathStateToServerStatus(state: InternetPathViewModel["pathState"]): ServerStatus {
|
||||
if (state === "healthy") return "online"
|
||||
@@ -17,44 +14,32 @@ function pathStateToServerStatus(state: InternetPathViewModel["pathState"]): Ser
|
||||
return "unknown"
|
||||
}
|
||||
|
||||
function HopChip({
|
||||
label,
|
||||
name,
|
||||
country,
|
||||
icon,
|
||||
iconClassName,
|
||||
}: {
|
||||
label: string
|
||||
name: string
|
||||
country?: string
|
||||
icon: ReactNode
|
||||
iconClassName?: string
|
||||
}) {
|
||||
function Kv({ label, children }: { label: string; children: ReactNode }) {
|
||||
return (
|
||||
<div className="flex min-w-0 items-center gap-2 rounded-md border border-border/60 px-2 py-1.5">
|
||||
<IconTile variant="elevated" size="sm" className={cn("shrink-0", iconClassName)} aria-hidden="true">
|
||||
{icon}
|
||||
</IconTile>
|
||||
<div className="min-w-0">
|
||||
<p className="text-muted-foreground text-[10px] font-medium uppercase tracking-wide">{label}</p>
|
||||
<p className="flex items-center gap-1 truncate text-sm font-medium">
|
||||
{country ? <Flag code={country} className="shrink-0" /> : null}
|
||||
<span className="truncate">{name}</span>
|
||||
</p>
|
||||
</div>
|
||||
<div className="min-w-0">
|
||||
<small className="text-muted-foreground block text-xs">{label}</small>
|
||||
<b className="mt-0.5 flex min-w-0 items-center gap-1.5 font-mono text-[13px] font-medium">{children}</b>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function Node({ name, country }: { name: string; country?: string }) {
|
||||
return (
|
||||
<>
|
||||
{country ? <Flag code={country} className="shrink-0" /> : null}
|
||||
<span className="truncate">{name}</span>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Compact live path strip (Frame-friendly). Canvas lives separately.
|
||||
* Preview: https://reui.io/preview/base/stats-12
|
||||
* Docs: https://reui.io/docs/components/base/icon-tile
|
||||
* Сводка маршрута (блок kv макета v3): узлы пути и последние подтверждённые метрики участка WAN → JH.
|
||||
* Docs: https://reui.io/docs/components/base/frame
|
||||
*/
|
||||
export function InternetPathSummary({ model }: { model: InternetPathViewModel | null }) {
|
||||
if (!model) {
|
||||
return (
|
||||
<p className="text-muted-foreground text-sm">
|
||||
<p className="text-muted-foreground px-4 py-3.5 text-sm">
|
||||
Недостаточно данных для пути. Добавьте home-router и проверьте{" "}
|
||||
<Link href="/network-map" className="underline underline-offset-2">
|
||||
карту сети
|
||||
@@ -71,61 +56,21 @@ export function InternetPathSummary({ model }: { model: InternetPathViewModel |
|
||||
const dl = hop?.wanJhMetrics.dlMbps
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-3">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<StatusBadge status={pathStateToServerStatus(model.pathState)} />
|
||||
{model.pathState === "failover" ? (
|
||||
<Badge variant="warning-light" size="sm">failover</Badge>
|
||||
) : null}
|
||||
{ping != null ? (
|
||||
<Badge variant="outline" size="sm" className="tabular-nums">
|
||||
{ping} мс
|
||||
</Badge>
|
||||
) : null}
|
||||
{dl != null ? (
|
||||
<Badge variant="outline" size="sm" className="tabular-nums">
|
||||
{Math.round(dl)} ↓ Мбит/с
|
||||
</Badge>
|
||||
) : null}
|
||||
<div className="flex flex-col gap-3 px-4 py-3.5">
|
||||
<div className="grid grid-cols-1 gap-x-3.5 gap-y-3 sm:grid-cols-2">
|
||||
<Kv label="Маршрут">Home → WAN → JH → Exit</Kv>
|
||||
<Kv label="Состояние">
|
||||
<StatusBadge status={pathStateToServerStatus(model.pathState)} />
|
||||
{model.pathState === "failover" ? <Badge variant="warning-light" size="sm">failover</Badge> : null}
|
||||
</Kv>
|
||||
<Kv label="RTT WAN → JH">{ping != null ? <span className="tabular-nums">{`${ping} мс`}</span> : "—"}</Kv>
|
||||
<Kv label="Загрузка WAN → JH">{dl != null ? <span className="tabular-nums">{`${Math.round(dl)} ↓ Мбит/с`}</span> : "—"}</Kv>
|
||||
<Kv label="Home"><Node name={model.homeRouter.name} country={model.homeRouter.country} /></Kv>
|
||||
<Kv label="Активный WAN"><span className="truncate">{`${wanName} · ${wanIsp}`}</span></Kv>
|
||||
<Kv label="JumpHost"><Node name={hop?.jumpHost.name ?? model.fallbackJumpHost?.name ?? "—"} country={hop?.jumpHost.country ?? model.fallbackJumpHost?.country} /></Kv>
|
||||
<Kv label="Exit"><Node name={hop?.exitNode.name ?? model.fallbackExitNode?.name ?? "—"} country={hop?.exitNode.country ?? model.fallbackExitNode?.country} /></Kv>
|
||||
</div>
|
||||
|
||||
<p className="text-muted-foreground text-xs">JH/Exit — схема кандидатов. Default route подтверждает только WAN. Метрики — последние подтверждённые пробы участков.</p>
|
||||
<div className="flex flex-col gap-2 @3xl:flex-row @3xl:items-center">
|
||||
<HopChip
|
||||
label="Home"
|
||||
name={model.homeRouter.name}
|
||||
country={model.homeRouter.country}
|
||||
icon={<HomeIcon />}
|
||||
iconClassName="text-success"
|
||||
/>
|
||||
<ArrowRightIcon className="text-muted-foreground hidden size-4 shrink-0 @3xl:block" aria-hidden="true" />
|
||||
<HopChip
|
||||
label="WAN"
|
||||
name={`${wanName} · ${wanIsp}`}
|
||||
icon={<RadioIcon />}
|
||||
iconClassName="text-info"
|
||||
/>
|
||||
<ArrowRightIcon className="text-muted-foreground hidden size-4 shrink-0 @3xl:block" aria-hidden="true" />
|
||||
<HopChip
|
||||
label="JH"
|
||||
name={hop?.jumpHost.name ?? model.fallbackJumpHost?.name ?? "—"}
|
||||
country={hop?.jumpHost.country ?? model.fallbackJumpHost?.country}
|
||||
icon={<ServerIcon />}
|
||||
iconClassName="text-primary"
|
||||
/>
|
||||
<ArrowRightIcon className="text-muted-foreground hidden size-4 shrink-0 @3xl:block" aria-hidden="true" />
|
||||
<HopChip
|
||||
label="Exit"
|
||||
name={hop?.exitNode.name ?? model.fallbackExitNode?.name ?? "—"}
|
||||
country={hop?.exitNode.country ?? model.fallbackExitNode?.country}
|
||||
icon={<GlobeIcon />}
|
||||
iconClassName="text-muted-foreground"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<p className="text-muted-foreground text-xs leading-relaxed">
|
||||
{model.currentPath?.reason ?? "Текущий маршрут не подтверждён"}
|
||||
</p>
|
||||
<p className="text-muted-foreground border-t border-dashed pt-2.5 text-xs">JH/Exit — схема кандидатов. Default route подтверждает только WAN. Метрики — последние подтверждённые пробы участков.</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -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
@@ -1,22 +1,30 @@
|
||||
"use client"
|
||||
|
||||
import { useEffect, useState } from "react"
|
||||
import Link from "next/link"
|
||||
import { usePathname } from "next/navigation"
|
||||
import { ChevronDownIcon, SearchIcon, StarIcon } from "lucide-react"
|
||||
import {
|
||||
SidebarGroup,
|
||||
SidebarGroupContent,
|
||||
SidebarGroupLabel,
|
||||
SidebarMenu,
|
||||
SidebarMenuAction,
|
||||
SidebarMenuButton,
|
||||
SidebarMenuItem,
|
||||
SidebarSeparator,
|
||||
useSidebar,
|
||||
} from "@/components/ui/sidebar"
|
||||
import { Kbd } from "@/components/ui/kbd"
|
||||
import { cn } from "@/lib/utils"
|
||||
import { openCommandPalette } from "@/components/command-palette"
|
||||
|
||||
export interface NavItem {
|
||||
title: string
|
||||
url: string
|
||||
icon?: React.ReactNode
|
||||
/** Если `undefined` — счётчик не показываем (нет данных или раздел без live-источника). */
|
||||
badge?: string
|
||||
/** Точка проблемы у пункта: сбой (er) или внимание (wn); без данных — не показываем. */
|
||||
problem?: { tone: "er" | "wn"; label: string }
|
||||
}
|
||||
|
||||
export interface NavGroup {
|
||||
@@ -24,36 +32,144 @@ export interface NavGroup {
|
||||
items: NavItem[]
|
||||
}
|
||||
|
||||
export function NavMain({ groups }: { groups: NavGroup[] }) {
|
||||
const PINS_KEY = "mm:sidebar-pins"
|
||||
const CLOSED_KEY = "mm:sidebar-closed-groups"
|
||||
const DOT_CLASS = { er: "bg-destructive", wn: "bg-warning" } as const
|
||||
|
||||
function readList(key: string): string[] {
|
||||
try {
|
||||
const raw = JSON.parse(localStorage.getItem(key) ?? "[]")
|
||||
return Array.isArray(raw) ? raw.filter((v): v is string => typeof v === "string") : []
|
||||
} catch {
|
||||
return []
|
||||
}
|
||||
}
|
||||
|
||||
function writeList(key: string, list: string[]) {
|
||||
try {
|
||||
localStorage.setItem(key, JSON.stringify(list))
|
||||
} catch {
|
||||
/* хранилище недоступно — настройка действует до перезагрузки */
|
||||
}
|
||||
}
|
||||
|
||||
function NavEntry({ item, pinned, onTogglePin }: { item: NavItem; pinned: boolean; onTogglePin: () => void }) {
|
||||
const pathname = usePathname()
|
||||
const { setOpenMobile } = useSidebar()
|
||||
const active = pathname === item.url || pathname.startsWith(`${item.url}/`)
|
||||
return (
|
||||
<SidebarMenuItem>
|
||||
<SidebarMenuButton
|
||||
isActive={active}
|
||||
tooltip={item.problem ? `${item.title} · ${item.problem.label}` : item.title}
|
||||
className="relative pr-8 group-data-[collapsible=icon]:pr-2!"
|
||||
render={<Link href={item.url} aria-current={active ? "page" : undefined} onNavigate={() => setOpenMobile(false)} />}
|
||||
>
|
||||
{item.icon}
|
||||
<span>{item.title}</span>
|
||||
{item.problem ? (
|
||||
<span
|
||||
role="img"
|
||||
aria-label={item.problem.label}
|
||||
className={cn(
|
||||
"ml-auto size-2 shrink-0 rounded-full group-data-[collapsible=icon]:absolute group-data-[collapsible=icon]:top-1 group-data-[collapsible=icon]:right-1 group-data-[collapsible=icon]:ml-0 group-data-[collapsible=icon]:size-1.5 group-data-[collapsible=icon]:ring-2 group-data-[collapsible=icon]:ring-sidebar",
|
||||
DOT_CLASS[item.problem.tone],
|
||||
)}
|
||||
/>
|
||||
) : null}
|
||||
</SidebarMenuButton>
|
||||
<SidebarMenuAction
|
||||
showOnHover={!pinned}
|
||||
aria-label={pinned ? `Открепить ${item.title}` : `Закрепить ${item.title}`}
|
||||
aria-pressed={pinned}
|
||||
onClick={onTogglePin}
|
||||
>
|
||||
<StarIcon className={cn(pinned && "fill-current")} aria-hidden />
|
||||
</SidebarMenuAction>
|
||||
</SidebarMenuItem>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Навигация общего макета v2 (как в EvoBGP): поиск ⌘K, «Закреплённые», сворачиваемые группы,
|
||||
* точки проблем у разделов.
|
||||
*/
|
||||
export function NavMain({ groups }: { groups: NavGroup[] }) {
|
||||
const [pins, setPins] = useState<string[]>([])
|
||||
const [closed, setClosed] = useState<string[]>([])
|
||||
useEffect(() => {
|
||||
queueMicrotask(() => {
|
||||
setPins(readList(PINS_KEY))
|
||||
setClosed(readList(CLOSED_KEY))
|
||||
})
|
||||
}, [])
|
||||
|
||||
const items = groups.flatMap((g) => g.items)
|
||||
const pinned = pins.map((url) => items.find((i) => i.url === url)).filter((i): i is NavItem => Boolean(i))
|
||||
const togglePin = (url: string) => setPins((prev) => {
|
||||
const next = prev.includes(url) ? prev.filter((u) => u !== url) : [...prev, url]
|
||||
writeList(PINS_KEY, next)
|
||||
return next
|
||||
})
|
||||
const toggleGroup = (label: string) => setClosed((prev) => {
|
||||
const next = prev.includes(label) ? prev.filter((l) => l !== label) : [...prev, label]
|
||||
writeList(CLOSED_KEY, next)
|
||||
return next
|
||||
})
|
||||
|
||||
return (
|
||||
<nav aria-label="Основная навигация">
|
||||
{groups.map((group) => (
|
||||
<SidebarGroup key={group.label}>
|
||||
<SidebarGroupLabel>{group.label}</SidebarGroupLabel>
|
||||
<SidebarMenu>
|
||||
{group.items.map((item) => (
|
||||
<SidebarMenuItem key={item.title}>
|
||||
<SidebarMenuButton
|
||||
isActive={pathname === item.url}
|
||||
tooltip={item.title}
|
||||
render={<Link href={item.url} aria-current={pathname === item.url ? "page" : undefined} onNavigate={() => setOpenMobile(false)} />}
|
||||
>
|
||||
{item.icon}
|
||||
<span>{item.title}</span>
|
||||
{item.badge != null && item.badge !== "" && (
|
||||
<span className="ml-auto text-[10.5px] font-mono tabular-nums text-sidebar-foreground/50 group-data-[collapsible=icon]:hidden">
|
||||
{item.badge}
|
||||
</span>
|
||||
)}
|
||||
</SidebarMenuButton>
|
||||
</SidebarMenuItem>
|
||||
))}
|
||||
</SidebarMenu>
|
||||
<nav aria-label="Основная навигация" className="flex flex-col">
|
||||
<SidebarGroup className="pb-1">
|
||||
<SidebarMenu>
|
||||
<SidebarMenuItem>
|
||||
<SidebarMenuButton
|
||||
tooltip="Поиск и команды"
|
||||
onClick={openCommandPalette}
|
||||
className="border-sidebar-border text-sidebar-foreground/70 border"
|
||||
>
|
||||
<SearchIcon aria-hidden />
|
||||
<span>Поиск и команды</span>
|
||||
<Kbd className="ml-auto group-data-[collapsible=icon]:hidden">⌘K</Kbd>
|
||||
</SidebarMenuButton>
|
||||
</SidebarMenuItem>
|
||||
</SidebarMenu>
|
||||
</SidebarGroup>
|
||||
|
||||
{pinned.length > 0 ? (
|
||||
<SidebarGroup className="py-0 group-data-[collapsible=icon]:hidden">
|
||||
<SidebarGroupLabel className="text-xs font-semibold tracking-wide uppercase">Закреплённые</SidebarGroupLabel>
|
||||
<SidebarGroupContent>
|
||||
<SidebarMenu className="gap-px">
|
||||
{pinned.map((item) => <NavEntry key={item.url} item={item} pinned onTogglePin={() => togglePin(item.url)} />)}
|
||||
</SidebarMenu>
|
||||
</SidebarGroupContent>
|
||||
</SidebarGroup>
|
||||
))}
|
||||
) : null}
|
||||
|
||||
{groups.map((group, gi) => {
|
||||
const isClosed = closed.includes(group.label)
|
||||
return (
|
||||
<div key={group.label} className="flex flex-col">
|
||||
{gi > 0 ? <SidebarSeparator className="mx-2 my-1 hidden h-px shrink-0 group-data-[collapsible=icon]:block" /> : null}
|
||||
<SidebarGroup className="py-0">
|
||||
<SidebarGroupLabel
|
||||
render={<button type="button" aria-expanded={!isClosed} onClick={() => toggleGroup(group.label)} />}
|
||||
className="h-7 cursor-pointer justify-between text-xs font-semibold tracking-wide uppercase"
|
||||
>
|
||||
{group.label}
|
||||
<ChevronDownIcon className={cn("size-3.5 transition-transform", isClosed && "-rotate-90")} aria-hidden />
|
||||
</SidebarGroupLabel>
|
||||
<SidebarGroupContent className={cn(isClosed && "hidden group-data-[collapsible=icon]:block")}>
|
||||
<SidebarMenu className="gap-px">
|
||||
{group.items.map((item) => (
|
||||
<NavEntry key={item.url} item={item} pinned={pins.includes(item.url)} onTogglePin={() => togglePin(item.url)} />
|
||||
))}
|
||||
</SidebarMenu>
|
||||
</SidebarGroupContent>
|
||||
</SidebarGroup>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</nav>
|
||||
)
|
||||
}
|
||||
Loaded 100 of 173 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user