diff --git a/app/(main)/filters/page.tsx b/app/(main)/filters/page.tsx index fc4229db..8020f4bc 100644 --- a/app/(main)/filters/page.tsx +++ b/app/(main)/filters/page.tsx @@ -252,7 +252,7 @@ function generateCombinedRouterOSConfig( // ── shared components ────────────────────────────────────────────────────────── -function TypeChip({ type }: { type: "jump-host" | "exit-node" | "home-router" }) { +function TypeChip({ type }: { type: import("@mmapp/contracts/servers").ServerType }) { return ( - {type === "jump-host" ? "JH" : type === "home-router" ? "HR" : "EN"} + {type === "jump-host" ? "JH" : type === "home-router" ? "HR" : type === "ix-node" ? "IX" : "EN"} ) } diff --git a/app/(main)/ipsec/page.tsx b/app/(main)/ipsec/page.tsx index a13dd808..280fe9cb 100644 --- a/app/(main)/ipsec/page.tsx +++ b/app/(main)/ipsec/page.tsx @@ -1,5 +1,6 @@ "use client" +import { serverTypeSchema } from "@mmapp/contracts/servers" import { can } from "@/lib/auth" import { z } from "zod" @@ -174,7 +175,7 @@ function mapBackendServer(s: BackendServer): InventoryServer { const ipsecInventorySchema = z.array(z.object({ id: z.number().int().positive(), name: z.string(), host: z.string(), enabled: z.boolean(), country: z.string().optional().default("UN"), - type: z.enum(["jump-host", "exit-node", "home-router"]).optional(), + type: serverTypeSchema.optional(), status: z.enum(["online", "offline", "degraded"]).nullable().optional(), latency: z.number().nullable().optional(), asn: z.string().optional(), })).refine(rows => new Set(rows.map(row => row.id)).size === rows.length) diff --git a/app/(main)/ix/page.tsx b/app/(main)/ix/page.tsx new file mode 100644 index 00000000..33052039 --- /dev/null +++ b/app/(main)/ix/page.tsx @@ -0,0 +1,250 @@ +"use client" + +import { useEffect, useMemo, 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 { 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 { EmptyState } from "@/components/empty-state" +import { PageHeader } from "@/components/page-header" +import { Button, buttonVariants } from "@/components/ui/button" +import { Input } from "@/components/ui/input" +import { Label } from "@/components/ui/label" +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" + +type Node = { id: number; name: string; site: string; country: string; enabled: boolean } +type Connection = { id: string; name: string } +type Plan = { planId: string; state: string } + +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 +} + +export default function IxPage() { + const { backendUrl, mode, prefsHydrated } = useDataSource() + const [segments, setSegments] = useState([]) + const [nodes, setNodes] = useState([]) + const [connections, setConnections] = useState([]) + const [connectionId, setConnectionId] = useState("") + const [selected, setSelected] = useState(null) + const [editing, setEditing] = useState(false) + const [body, setBody] = useState("") + 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 [preview, setPreview] = useState(null) + const [linux, setLinux] = useState("") + const [plan, setPlan] = useState(null) + const [tab, setTab] = useState<"configuration" | "routes" | "changes">("configuration") + const [busy, setBusy] = useState(false) + const [error, setError] = useState("") + const [write, setWrite] = useState(false) + const [approve, setApprove] = useState(false) + + async function load(signal?: AbortSignal) { + const options = { signal } + const [segmentsResult, nodesResult] = await Promise.all([ + requestJson<{ items: IxSegment[] }>(backendUrl, "/api/ix/segments?limit=100", options), + requestJson<{ items: Node[] }>(backendUrl, "/api/ix/nodes", options), + ]) + 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 }))) + } + } + + useEffect(() => { + if (!prefsHydrated || mode !== "live") return + const controller = new AbortController() + void ensureAuthConfig().then(async () => { + 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)) }) + return () => controller.abort() + // Load only when the project 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) + setPlan(null) + setObservations([]) + setLinux("") + setTab("configuration") + setError("") + setEditing(true) + } + function change(): IxChange { + const configuration = ixSegmentConfigurationSchema.parse(JSON.parse(body)) + return { ...(selected ? { id: selected.id } : {}), revision: selected?.revision ?? 0, configuration } + } + async function perform(work: () => Promise) { + setBusy(true) + setError("") + 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") + } + + 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 &&
+ +