diff --git a/app/(main)/ix/ix-view.tsx b/app/(main)/ix/ix-view.tsx new file mode 100644 index 00000000..9969ac11 --- /dev/null +++ b/app/(main)/ix/ix-view.tsx @@ -0,0 +1,159 @@ +"use client" + +import { useMemo } from "react" +import { type ColumnDef, useTable } from "@tanstack/react-table" +import { FileTextIcon, PlusIcon, XIcon } from "lucide-react" +import type { IxConfiguration, IxSegment, IxSite, IxSiteObservation } from "@mmapp/contracts/internet-exchange" +import { DataGridShell } from "@/components/data-grids/shared/data-grid-shell" +import { EmptyState } from "@/components/empty-state" +import { Badge } from "@/components/reui/badge" +import { dataGridFeatures, type DataGridFeatures } from "@/components/reui/data-grid" +import { Frame, FrameDescription, FrameHeader, FramePanel, FrameTitle } from "@/components/reui/frame" +import { Button } from "@/components/ui/button" +import { Field, FieldDescription, FieldLabel } from "@/components/ui/field" +import { Input } from "@/components/ui/input" +import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select" + +export type IxNode = { id: number; name: string; site: string; country: string; enabled: boolean } +type Route = IxSiteObservation["routes"][number] + +export const nodeLabel = (nodes: readonly IxNode[], id: number) => nodes.find(node => node.id === id)?.name || `Узел ${id}` +export const newSite = (): IxSite => ({ + serverId: 0, autonomousSystem: 64512, routerId: "", + interfaces: [], groups: [], exits: [], routes: [], neighbors: [], discardNetworks: [], +}) + +export function SegmentStatus({ segment }: { segment: IxSegment }) { + return segment.revision === segment.appliedRevision + ? Применена + : {segment.appliedRevision ? "Есть черновик" : "Черновик"} +} + +export function SegmentGrid({ rows, nodes, loading, open, empty }: { + rows: IxSegment[]; nodes: IxNode[]; loading: boolean; open: (segment: IxSegment) => void; empty: React.ReactNode +}) { + const columns = useMemo[]>(() => [ + { id: "name", header: "Сегмент", size: 210, cell: ({ row }) => ( + + ) }, + { id: "sites", header: "Площадки", size: 230, cell: ({ row }) => row.original.configuration.sites.map(site => nodeLabel(nodes, site.serverId)).join(", ") }, + { id: "neighbors", header: "BGP-соседи", size: 115, cell: ({ row }) => + {row.original.configuration.sites.reduce((total, site) => total + site.neighbors.length, 0)} }, + { id: "state", header: "Состояние", size: 140, cell: ({ row }) => }, + ], [nodes, open]) + const table = useTable({ features: dataGridFeatures, manualPagination: true, data: rows, columns, getRowId: row => row.id }) + return +} + +export function ConfigurationFields({ configuration, nodes, readOnly, change }: { + configuration: IxConfiguration; nodes: IxNode[]; readOnly: boolean; change: (value: IxConfiguration) => void +}) { + function updateSite(index: number, fields: Partial) { + change({ ...configuration, sites: configuration.sites.map((site, position) => position === index ? { ...site, ...fields } : site) }) + } + const canAddSite = configuration.sites.length < 2 && nodes.filter(node => node.enabled).length > configuration.sites.length + + return
+ + Сегмент + + + Имя сегмента + change({ ...configuration, name: event.target.value })} /> + {!readOnly && Латинские строчные буквы, цифры и дефисы.} + + + + {configuration.sites.map((site, index) => { + const fieldId = `ix-site-${index}` + const choices = nodes.filter(node => node.id === site.serverId || (node.enabled && !configuration.sites.some((other, i) => i !== index && other.serverId === node.id))) + return + +
+ Площадка {index + 1} + {site.serverId > 0 && {nodeLabel(nodes, site.serverId)}} +
+ {!readOnly && configuration.sites.length > 1 && } +
+ +
+ + Узел IX + + + + Локальный ASN + { if (/^\d*$/.test(event.target.value)) updateSite(index, { autonomousSystem: Number(event.target.value) }) }} /> + + + Router ID + updateSite(index, { routerId: event.target.value })} /> + +
+
+ {[ + ["Интерфейсы", site.interfaces.length], ["Группы шлюзов", site.groups.length], + ["Маршруты", site.routes.length], ["BGP-соседи", site.neighbors.length], + ].map(([label, count]) =>
+
{label}
+
{count}
+
)} +
+
+ + })} + {!readOnly && canAddSite && } +
+} + +const routeColumns: ColumnDef[] = [ + { id: "prefix", header: "Префикс", size: 160, cell: ({ row }) => {row.original.prefix} }, + { id: "gateway", header: "Шлюз", size: 140, cell: ({ row }) => row.original.gateway || "—" }, + { id: "immediate", header: "Фактический next hop", size: 200, cell: ({ row }) => row.original.immediateGateway ?? "—" }, + { id: "active", header: "Состояние", size: 112, cell: ({ row }) => row.original.active + ? Активен + : Неактивен }, +] + +export function RouteGrid({ observation, nodes }: { observation: IxSiteObservation; nodes: IxNode[] }) { + const table = useTable({ features: dataGridFeatures, manualPagination: true, data: observation.routes, columns: routeColumns }) + return + +
+ {nodeLabel(nodes, observation.serverId)} + {new Date(observation.observedAt).toLocaleString("ru-RU")} +
+ {observation.available ? + BGP {observation.neighbors.filter(peer => peer.established).length} из {observation.neighbors.length} + : Состояние недоступно} +
+ {observation.available && +
+ } title="Маршруты не найдены" className="py-8" />} /> +
+
} + +} diff --git a/app/(main)/ix/page.tsx b/app/(main)/ix/page.tsx index 33052039..c68d6573 100644 --- a/app/(main)/ix/page.tsx +++ b/app/(main)/ix/page.tsx @@ -1,250 +1,351 @@ "use client" -import { useEffect, useMemo, useState } from "react" +import { useEffect, useRef, useState } from "react" import Link from "next/link" -import { NetworkIcon, PlusIcon, RefreshCwIcon } from "lucide-react" -import { type ColumnDef, useTable } from "@tanstack/react-table" -import { ixSegmentConfigurationSchema, type IxChange, type IxRouterObject, type IxSegment, type IxSiteObservation } from "@mmapp/contracts/internet-exchange" +import { ArrowLeftIcon, CircleAlertIcon, NetworkIcon, PlusIcon, RefreshCwIcon } from "lucide-react" +import { ixSegmentConfigurationSchema, type IxChange, type IxConfiguration, type IxRouterObject, type IxSegment, type IxSiteObservation } from "@mmapp/contracts/internet-exchange" +import { Alert, AlertDescription, AlertTitle } from "@/components/reui/alert" import { Badge } from "@/components/reui/badge" -import { dataGridFeatures, type DataGridFeatures } from "@/components/reui/data-grid" -import { DataGridShell } from "@/components/data-grids/shared/data-grid-shell" +import { Frame, FrameDescription, FrameHeader, FramePanel, FrameTitle } from "@/components/reui/frame" import { EmptyState } from "@/components/empty-state" import { PageHeader } from "@/components/page-header" -import { Button, buttonVariants } from "@/components/ui/button" +import { Button } from "@/components/ui/button" +import { Field, FieldLabel } from "@/components/ui/field" import { Input } from "@/components/ui/input" -import { Label } from "@/components/ui/label" +import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select" +import { Skeleton } from "@/components/ui/skeleton" +import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs" import { Textarea } from "@/components/ui/textarea" import { can, ensureAuthConfig } from "@/lib/auth" import { useDataSource } from "@/lib/data-source" import { requestJson } from "@/shared/api/http-client" import { mcpApi } from "@/shared/api/mcp" +import { ConfigurationFields, newSite, RouteGrid, SegmentGrid, SegmentStatus, type IxNode } from "./ix-view" -type Node = { id: number; name: string; site: string; country: string; enabled: boolean } type Connection = { id: string; name: string } type Plan = { planId: string; state: string } +type Tab = "configuration" | "routes" | "changes" +const title = "Точки обмена трафиком" const describe = (error: unknown) => error instanceof Error ? error.message : "Не удалось выполнить операцию IX" const json = (value: unknown) => JSON.stringify(value, null, 2) const post = (value: unknown) => ({ method: "POST", body: JSON.stringify(value) }) -function SegmentGrid({ rows, open }: { rows: IxSegment[]; open: (segment: IxSegment) => void }) { - const columns: ColumnDef[] = [ - { id: "name", header: "Сегмент", cell: ({ row }) => }, - { id: "sites", header: "Площадки", cell: ({ row }) => row.original.configuration.sites.length }, - { id: "neighbors", header: "BGP-соседи", cell: ({ row }) => row.original.configuration.sites.reduce((total, site) => total + site.neighbors.length, 0) }, - { id: "state", header: "Состояние конфигурации", cell: ({ row }) => row.original.revision === row.original.appliedRevision - ? Применена - : Черновик }, - ] - const table = useTable({ features: dataGridFeatures, manualPagination: true, data: rows, columns, getRowId: row => row.id }) - return +const planStates: Record = { + draft: "Черновик плана", "awaiting-approval": "Ждёт подтверждения", approved: "Подтверждён", + pending: "В очереди", running: "Выполняется", completed: "Завершён", applied: "Применён", + rejected: "Отклонён", expired: "Истёк", failed: "Ошибка", partial: "Выполнен частично", unknown: "Нужна сверка", } export default function IxPage() { const { backendUrl, mode, prefsHydrated } = useDataSource() const [segments, setSegments] = useState([]) - const [nodes, setNodes] = useState([]) + const [nodes, setNodes] = useState([]) const [connections, setConnections] = useState([]) const [connectionId, setConnectionId] = useState("") + const [connectionError, setConnectionError] = useState("") const [selected, setSelected] = useState(null) - const [editing, setEditing] = useState(false) - const [body, setBody] = useState("") + const [draft, setDraft] = useState(null) + const [advanced, setAdvanced] = useState(null) const [filter, setFilter] = useState("") - const [nodeId, setNodeId] = useState("") - const [name, setName] = useState("") - const [asn, setAsn] = useState("64512") - const [routerId, setRouterId] = useState("") - const [observations, setObservations] = useState([]) + const [observations, setObservations] = useState(null) const [preview, setPreview] = useState(null) const [linux, setLinux] = useState("") const [plan, setPlan] = useState(null) - const [tab, setTab] = useState<"configuration" | "routes" | "changes">("configuration") + const [tab, setTab] = useState("configuration") + const [loading, setLoading] = useState(true) const [busy, setBusy] = useState(false) const [error, setError] = useState("") + const [notice, setNotice] = useState("") const [write, setWrite] = useState(false) const [approve, setApprove] = useState(false) + const heading = useRef(null) + const focusAfterNavigation = useRef(false) + const inDetail = draft !== null async function load(signal?: AbortSignal) { - const options = { signal } + if (signal?.aborted) return + setWrite(can("mm:network:write")) + setApprove(can("mm:mcp:approve")) const [segmentsResult, nodesResult] = await Promise.all([ - requestJson<{ items: IxSegment[] }>(backendUrl, "/api/ix/segments?limit=100", options), - requestJson<{ items: Node[] }>(backendUrl, "/api/ix/nodes", options), + requestJson<{ items: IxSegment[] }>(backendUrl, "/api/ix/segments?limit=100", { signal }), + requestJson<{ items: IxNode[] }>(backendUrl, "/api/ix/nodes", { signal }), ]) + if (signal?.aborted) return setSegments(segmentsResult.items) setNodes(nodesResult.items) - if (can("mm:mcp:read")) { - const { connections } = await mcpApi(backendUrl).connections(signal) - setConnections(connections.filter(connection => connection.policy.status === "active" && - connection.policy.scope.operationIds.includes("network.ix.configure")).map(connection => ({ id: connection.id, name: connection.name }))) + + setConnectionError("") + if (!can("mm:mcp:read")) { + setConnections([]) + setConnectionId("") + return + } + try { + const result = await mcpApi(backendUrl).connections(signal) + if (signal?.aborted) return + const available = result.connections.filter(connection => connection.policy.status === "active" && + connection.policy.scope.operationIds.includes("network.ix.configure")) + setConnections(available.map(connection => ({ id: connection.id, name: connection.name }))) + setConnectionId(current => available.some(connection => connection.id === current) ? current : available.length === 1 ? available[0].id : "") + } catch (error) { + if (signal?.aborted) return + setConnections([]) + setConnectionId("") + setConnectionError(describe(error)) } } useEffect(() => { if (!prefsHydrated || mode !== "live") return const controller = new AbortController() - void ensureAuthConfig().then(async () => { + void ensureAuthConfig().then(() => { if (controller.signal.aborted) return - setWrite(can("mm:network:write")) - setApprove(can("mm:mcp:approve")) - await load(controller.signal) - }).catch(error => { if (!controller.signal.aborted) setError(describe(error)) }) + setLoading(true) + setError("") + return load(controller.signal) + }) + .catch(error => { if (!controller.signal.aborted) setError(describe(error)) }) + .finally(() => { if (!controller.signal.aborted) setLoading(false) }) return () => controller.abort() - // Load only when the project source changes. + // Reload when the project data source changes. // eslint-disable-next-line react-hooks/exhaustive-deps }, [backendUrl, mode, prefsHydrated]) - const rows = useMemo(() => segments.filter(segment => segment.configuration.name.includes(filter.toLowerCase().trim())), [filter, segments]) - function open(segment: IxSegment | null) { - setSelected(segment) - setBody(segment ? json(segment.configuration) : "") - setPreview(null) + useEffect(() => { + if (focusAfterNavigation.current) { + focusAfterNavigation.current = false + heading.current?.focus() + } + }, [inDetail]) + + const rows = segments.filter(segment => segment.configuration.name.includes(filter.trim().toLowerCase())) + const enabledNodes = nodes.filter(node => node.enabled) + const live = prefsHydrated && mode === "live" + const canCreate = live && write && !loading && enabledNodes.length > 0 + + function invalidateReview() { setPlan(null) - setObservations([]) + setPreview(null) + setNotice("") + } + + function open(segment: IxSegment | null) { + focusAfterNavigation.current = !inDetail + setSelected(segment) + setDraft(segment?.configuration ?? { name: "", sites: [{ ...newSite(), serverId: enabledNodes.length === 1 ? enabledNodes[0].id : 0 }] }) + setAdvanced(null) + setObservations(null) setLinux("") setTab("configuration") setError("") - setEditing(true) + invalidateReview() } + + function close() { + focusAfterNavigation.current = true + setDraft(null) + setError("") + setNotice("") + } + function change(): IxChange { - const configuration = ixSegmentConfigurationSchema.parse(JSON.parse(body)) + const configuration = ixSegmentConfigurationSchema.parse(advanced === null ? draft : JSON.parse(advanced)) return { ...(selected ? { id: selected.id } : {}), revision: selected?.revision ?? 0, configuration } } + async function perform(work: () => Promise) { setBusy(true) setError("") + setNotice("") try { await work() } catch (error) { setError(describe(error)) } finally { setBusy(false) } } + async function save() { const { segment } = await requestJson<{ segment: IxSegment }>(backendUrl, "/api/ix/segments", post(change())) open(segment) - await load() - } - async function observe() { - if (!selected) return - const { sites } = await requestJson<{ sites: IxSiteObservation[] }>(backendUrl, `/api/ix/segments/${selected.id}/status`) - setObservations(sites) - setTab("routes") + setSegments(current => current.some(item => item.id === segment.id) + ? current.map(item => item.id === segment.id ? segment : item) + : [segment, ...current]) + setNotice("Черновик сохранён") } + async function observe() { + if (!selected?.appliedRevision) return + const { sites } = await requestJson<{ sites: IxSiteObservation[] }>(backendUrl, `/api/ix/segments/${selected.id}/status`) + setObservations(sites) + } + + function showTab(next: Tab) { + if (next === tab || busy) return + setError("") + setTab(next) + if (next === "routes" && observations === null && selected?.appliedRevision) void perform(observe) + } + + const listEmpty = error ? "Не удалось загрузить список" : + filter.trim() ? "Сегменты не найдены" : !live ? "Подключите backend" : "Нет сегментов IX" + const listDescription = error ? "Повторите загрузку списка." : filter.trim() ? "Попробуйте другое имя сегмента." : + !live ? "Откройте раздел в режиме «Живые»." : enabledNodes.length ? undefined : "Сначала добавьте сервер типа IX Node." + const linuxBindings = selected?.appliedRevision ? selected.configuration.sites.flatMap(site => + site.interfaces.filter(binding => binding.provisionWireguard?.hubEndpoint).map(binding => ({ site, binding }))) : [] + return <> - -
-
-
-

Точки обмена трафиком

-

IX-сегменты, маршруты и BGP-политики в отдельных VRF.

-
-
- - {write && } -
-
- {error &&

{error}

} -
- {[{ name: "Узлы IX", count: nodes.length }, { name: "Сегменты", count: segments.length }, { name: "Применённые ревизии", count: segments.filter(segment => segment.appliedRevision === segment.revision).length }].map(item => -
-
{item.name}
-
{item.count}
-
- )} -
-
- setFilter(event.target.value)} /> - {rows.length ? : - } title={filter ? "Сегменты не найдены" : "Нет IX-сегментов"} - description={mode !== "live" ? "Сегменты доступны при подключении к серверу." : "Добавьте сервер типа IX Node, чтобы создать сегмент."} />} -
- {editing &&
-
-

{selected?.configuration.name ?? "Новый сегмент"}

- -
-
- - - -
- {tab === "configuration" && <> - {!body &&
-
setName(event.target.value)} />
-
-
setAsn(event.target.value)} />
-
setRouterId(event.target.value)} />
- - Открыть каталог серверов -
} - {body &&
- -