199 lines
13 KiB
TypeScript
199 lines
13 KiB
TypeScript
"use client"
|
|
|
|
import { useEffect, useMemo, useState } from "react"
|
|
import { type ColumnDef, useTable } from "@tanstack/react-table"
|
|
import { FileTextIcon, PlusIcon, XIcon } from "lucide-react"
|
|
import type { IxConfiguration, IxNodeInventory, 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"
|
|
import { requestJson } from "@/shared/api/http-client"
|
|
import { IxSiteEditor } from "./ix-site-editor"
|
|
|
|
export type IxNode = { id: number; name: string; site: string; country: string; enabled: boolean; type?: string }
|
|
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: "", autoRouterId: true,
|
|
interfaces: [], groups: [], exits: [], routes: [], neighbors: [], discardNetworks: [],
|
|
})
|
|
|
|
export function SegmentStatus({ segment }: { segment: IxSegment }) {
|
|
return segment.revision === segment.appliedRevision
|
|
? <Badge variant="success-light">Применена</Badge>
|
|
: <Badge variant="warning-light">{segment.appliedRevision ? "Есть черновик" : "Черновик"}</Badge>
|
|
}
|
|
|
|
export function SegmentGrid({ rows, nodes, loading, open, empty }: {
|
|
rows: IxSegment[]; nodes: IxNode[]; loading: boolean; open: (segment: IxSegment) => void; empty: React.ReactNode
|
|
}) {
|
|
const columns = useMemo<ColumnDef<DataGridFeatures, IxSegment>[]>(() => [
|
|
{ id: "name", header: "Сегмент", size: 210, cell: ({ row }) => (
|
|
<Button type="button" variant="link" size="sm" className="max-w-full justify-start" onClick={() => open(row.original)}>
|
|
<span className="truncate">{row.original.configuration.name}</span>
|
|
</Button>
|
|
) },
|
|
{ id: "sites", header: "Площадки", size: 230, cell: ({ row }) => row.original.configuration.sites.map(site => nodeLabel(nodes, site.serverId)).join(", ") },
|
|
{ id: "clients", header: "Linux-клиенты", size: 125, cell: ({ row }) =>
|
|
<span className="tabular-nums">{row.original.configuration.sites.reduce((total, site) => total + site.interfaces.filter(item => item.linux).length, 0)}</span> },
|
|
{ id: "state", header: "Состояние", size: 140, cell: ({ row }) => <SegmentStatus segment={row.original} /> },
|
|
], [nodes, open])
|
|
const table = useTable({ features: dataGridFeatures, manualPagination: true, data: rows, columns, getRowId: row => row.id })
|
|
return <DataGridShell table={table} recordCount={rows.length} isLoading={loading} loadingMode="skeleton" emptyMessage={empty} />
|
|
}
|
|
|
|
export function useIxNodeInventory(backendUrl: string, serverId: number, segmentId?: string) {
|
|
const path = serverId > 0 ? `/api/ix/nodes/${serverId}/inventory${segmentId ? "?segmentId=" + segmentId : ""}` : null
|
|
const [result, setResult] = useState<{ path: string; inventory?: IxNodeInventory; error?: string }>()
|
|
const [refresh, setRefresh] = useState(0)
|
|
useEffect(() => {
|
|
if (!path) return
|
|
const controller = new AbortController()
|
|
void requestJson<IxNodeInventory>(backendUrl, path, { signal: controller.signal }).then(inventory => {
|
|
if (!Array.isArray(inventory?.interfaces) || !Array.isArray(inventory.defaultRoutes)) throw new Error("Неполный каталог интерфейсов")
|
|
if (!controller.signal.aborted) setResult({ path, inventory })
|
|
}).catch(() => {
|
|
if (!controller.signal.aborted) setResult({ path, error: "Не удалось прочитать интерфейсы CHR" })
|
|
})
|
|
return () => controller.abort()
|
|
}, [backendUrl, path, refresh])
|
|
return { ...(result?.path === path ? result : undefined), loading: path !== null && result?.path !== path,
|
|
reload: () => { setResult(undefined); setRefresh(value => value + 1) } }
|
|
}
|
|
|
|
function IxInventoryFields({ site, segmentId, backendUrl, fieldId, peers, readOnly, segmentName, edit }: {
|
|
site: IxSite; segmentId?: string; backendUrl: string; fieldId: string; peers: { value: string; label: string }[]
|
|
readOnly: boolean; segmentName: string; edit: (fields: Partial<IxSite>) => void
|
|
}) {
|
|
const { inventory, error, loading, reload } = useIxNodeInventory(backendUrl, site.serverId, segmentId)
|
|
const suggested = site.routerId || (site.autoRouterId ? inventory?.routerId ?? "" : "")
|
|
return <>
|
|
<Field className="min-w-0">
|
|
<FieldLabel htmlFor={fieldId + "-router"}>Router ID</FieldLabel>
|
|
<Input id={fieldId + "-router"} value={suggested} placeholder="Подбирается автоматически" readOnly={readOnly}
|
|
onChange={event => edit({ routerId: event.target.value, autoRouterId: !event.target.value })} />
|
|
<FieldDescription>{suggested ? site.autoRouterId ? "Назначен автоматически" : "Задан вручную" :
|
|
loading ? "Проверяем занятые идентификаторы…" : "Свободный ID будет выбран при сохранении."}</FieldDescription>
|
|
</Field>
|
|
<div className="grid min-w-0 gap-3 sm:col-span-2 lg:col-span-3">
|
|
{site.serverId > 0 && <div className="flex flex-wrap items-center justify-between gap-2">
|
|
<span className="text-sm text-muted-foreground" role="status">
|
|
{loading ? "Читаем интерфейсы CHR…" : error ?? `Интерфейсы CHR · ${inventory?.interfaces?.length ?? 0}`}
|
|
</span>
|
|
<Button type="button" size="sm" variant="outline" disabled={loading} onClick={reload}>Обновить интерфейсы</Button>
|
|
</div>}
|
|
<IxSiteEditor site={site} segmentName={segmentName} readOnly={readOnly} edit={edit} peers={peers}
|
|
inventory={inventory?.interfaces ?? []} />
|
|
</div>
|
|
</>
|
|
}
|
|
|
|
export function ConfigurationFields({ configuration, nodes, peers, readOnly, change, backendUrl, segmentId, section }: {
|
|
section: "configuration" | "routes"
|
|
configuration: IxConfiguration; nodes: IxNode[]; peers: IxNode[]; readOnly: boolean; change: (value: IxConfiguration) => void
|
|
backendUrl: string; segmentId?: string
|
|
}) {
|
|
function updateSite(index: number, fields: Partial<IxSite>) {
|
|
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 <div className="grid min-w-0 gap-3">
|
|
{section === "configuration" && <Frame spacing="sm">
|
|
<FrameHeader><FrameTitle>Сегмент</FrameTitle></FrameHeader>
|
|
<FramePanel>
|
|
<Field className="max-w-md">
|
|
<FieldLabel htmlFor="ix-name">Имя сегмента</FieldLabel>
|
|
<Input id="ix-name" placeholder="ix-central" value={configuration.name} readOnly={readOnly}
|
|
onChange={event => change({ ...configuration, name: event.target.value })} />
|
|
{!readOnly && <FieldDescription>Латинские строчные буквы, цифры и дефисы.</FieldDescription>}
|
|
</Field>
|
|
</FramePanel>
|
|
</Frame>}
|
|
{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 <Frame key={fieldId} spacing="sm">
|
|
<FrameHeader className="flex-row items-center justify-between gap-2">
|
|
<div className="min-w-0">
|
|
<FrameTitle>{section === "configuration" ? "Площадка " + (index + 1) : nodeLabel(nodes, site.serverId)}</FrameTitle>
|
|
</div>
|
|
{section === "configuration" && !readOnly && configuration.sites.length > 1 && <Button type="button" size="icon-sm" variant="ghost"
|
|
aria-label={`Убрать площадку ${index + 1}`}
|
|
onClick={() => change({ ...configuration, sites: configuration.sites.filter((_, position) => position !== index) })}>
|
|
<XIcon aria-hidden />
|
|
</Button>}
|
|
</FrameHeader>
|
|
<FramePanel className="grid gap-4">
|
|
<div className="grid min-w-0 gap-3 sm:grid-cols-2 lg:grid-cols-3">
|
|
{section === "configuration" && <Field className="min-w-0">
|
|
<FieldLabel htmlFor={fieldId}>Узел IX</FieldLabel>
|
|
<Select
|
|
value={site.serverId ? String(site.serverId) : null}
|
|
items={choices.map(node => ({ value: String(node.id), label: node.name }))}
|
|
disabled={readOnly}
|
|
onValueChange={value => { if (value && Number(value) !== site.serverId) updateSite(index, { ...newSite(), serverId: Number(value) }) }}
|
|
>
|
|
<SelectTrigger id={fieldId} className="w-full"><SelectValue placeholder="Выберите узел" /></SelectTrigger>
|
|
<SelectContent>
|
|
{choices.map(node => <SelectItem key={node.id} value={String(node.id)} disabled={!node.enabled}>{node.name}</SelectItem>)}
|
|
</SelectContent>
|
|
</Select>
|
|
</Field>}
|
|
{section === "routes" && <Field className="min-w-0">
|
|
<FieldLabel htmlFor={fieldId + "-asn"}>Локальный ASN</FieldLabel>
|
|
<Input id={fieldId + "-asn"} inputMode="numeric" value={site.autonomousSystem || ""} readOnly={readOnly}
|
|
onChange={event => { if (/^\d*$/.test(event.target.value)) updateSite(index, { autonomousSystem: Number(event.target.value) }) }} />
|
|
</Field>}
|
|
{section !== "configuration" && <IxInventoryFields site={site} segmentId={segmentId} backendUrl={backendUrl} fieldId={fieldId}
|
|
readOnly={readOnly} segmentName={configuration.name} edit={fields => updateSite(index, fields)}
|
|
peers={peers.filter(node => node.id !== site.serverId && (node.enabled || site.interfaces.some(binding => binding.peerServerId === node.id)))
|
|
.map(node => ({ value: String(node.id), label: node.name }))} />}
|
|
</div>
|
|
</FramePanel>
|
|
</Frame>
|
|
})}
|
|
{section === "configuration" && !readOnly && canAddSite && <Button type="button" variant="outline" size="sm" className="w-fit"
|
|
onClick={() => change({ ...configuration, sites: [...configuration.sites, newSite()] })}>
|
|
<PlusIcon aria-hidden />Добавить площадку
|
|
</Button>}
|
|
</div>
|
|
}
|
|
|
|
const routeColumns: ColumnDef<DataGridFeatures, Route>[] = [
|
|
{ id: "prefix", header: "Префикс", size: 160, cell: ({ row }) => <span className="font-mono">{row.original.prefix}</span> },
|
|
{ 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
|
|
? <Badge variant="success-light">Активен</Badge>
|
|
: <Badge variant="secondary">Неактивен</Badge> },
|
|
]
|
|
|
|
export function RouteGrid({ observation, nodes }: { observation: IxSiteObservation; nodes: IxNode[] }) {
|
|
const table = useTable({ features: dataGridFeatures, manualPagination: true, data: observation.routes, columns: routeColumns })
|
|
return <Frame spacing="sm" className="min-w-0">
|
|
<FrameHeader className="flex-row flex-wrap items-center justify-between gap-2">
|
|
<div className="min-w-0">
|
|
<FrameTitle className="wrap-anywhere">{nodeLabel(nodes, observation.serverId)}</FrameTitle>
|
|
<FrameDescription>{new Date(observation.observedAt).toLocaleString("ru-RU")}</FrameDescription>
|
|
</div>
|
|
{observation.available ? <Badge variant="info-light">
|
|
BGP {observation.neighbors.filter(peer => peer.established).length} из {observation.neighbors.length}
|
|
</Badge> : <Badge variant="warning-light">Состояние недоступно</Badge>}
|
|
</FrameHeader>
|
|
{observation.available && <FramePanel className="min-w-0 p-0">
|
|
<div className="overflow-x-auto">
|
|
<DataGridShell table={table} recordCount={observation.routes.length}
|
|
emptyMessage={<EmptyState icon={<FileTextIcon />} title="Маршруты не найдены" className="py-8" />} />
|
|
</div>
|
|
</FramePanel>}
|
|
</Frame>
|
|
}
|