Compare commits

..
2 Commits
Author SHA1 Message Date
Denozordec ee6fd675ac fix(routing): устранить конфликты чтения фильтров и маршрутов
Docker images / prepare-release (push) Successful in 10s
Docker images / backend-test (push) Successful in 10m25s
Docker images / frontend-image (push) Successful in 3m18s
Docker images / updater-image (push) Successful in 41s
Docker images / netflow-agent-image (push) Successful in 32s
Docker images / backend-image (push) Successful in 2m48s
Docker images / publish-release (push) Successful in 10s
Docker images / notify-webhook (push) Successful in 1s
2026-11-24 12:46:31 +07:00
Denozordec 5a46594ec9 fix(ix): объединить туннели по клиентам и показать счётчики трафика
Docker images / prepare-release (push) Successful in 11s
Docker images / backend-test (push) Successful in 10m24s
Docker images / backend-image (push) Successful in 2m0s
Docker images / frontend-image (push) Successful in 2m15s
Docker images / updater-image (push) Successful in 39s
Docker images / netflow-agent-image (push) Successful in 32s
Docker images / notify-webhook (push) Successful in 2s
Docker images / publish-release (push) Successful in 10s
2026-11-24 10:48:21 +07:00
26 changed files with 468 additions and 117 deletions

No files matched your search

+20 -29
View File
@@ -2,7 +2,6 @@
import { useEffect, useState, type ReactNode } from "react"
import type { IxBondBundle, IxBondCandidate, IxBondCatalog, IxBondEdit, IxBondMode, IxSavedBond, IxSegment } from "@mmapp/contracts/internet-exchange"
import { Frame, FrameHeader, FramePanel, FrameTitle } from "@/components/reui/frame"
import { Button } from "@/components/ui/button"
import { Checkbox } from "@/components/ui/checkbox"
import { Input } from "@/components/ui/input"
@@ -29,7 +28,7 @@ const modeLabel = (mode: IxBondMode) => modes.find(item => item.value === mode)?
export function IxClientBonds({ segmentId, segments, backendUrl, nodes, readOnly, download, live, children }: {
segmentId: string; segments: IxSegment[]; backendUrl: string; nodes: IxNode[]; readOnly: boolean; live: boolean
download: (filename: string, text: string) => void
children: (action: IxRowBondAction, catalog: IxBondCatalog) => ReactNode
children: (action: IxRowBondAction, catalog: IxBondCatalog, groups: (clientId: string) => ReactNode, unassigned: ReactNode) => ReactNode
}) {
const [catalog, setCatalog] = useState<IxBondCatalog>({ groups: [], candidates: [] })
const [reload, setReload] = useState(0)
@@ -93,29 +92,7 @@ export function IxClientBonds({ segmentId, segments, backendUrl, nodes, readOnly
const needsConfirmation = selected.length > 1 && selected.some(c => !c.clientId && !previous?.members.some(m => memberKey(m) === memberKey(c)))
const selectionKey = selected.map(memberKey).sort().join(",")
const issue = error && <p role="alert" className="text-sm text-destructive">{error}</p>
const rows = children(binding => {
const k = memberKey({ ...binding, segmentId })
const current = ownedGroups.find(g => g.members.some(m => memberKey(m) === k))
const candidate = available.get(k)
if (current) return { label: "Открыть группу «" + current.name + "»", open: () => open(current) }
if (candidate?.destinations.length) return { label: "Создать группу с этим туннелем", open: () => open(undefined, candidate) }
const site = segments.find(s => s.id === segmentId)?.configuration.sites.find(s => s.serverId === binding.serverId)
const saved = site?.interfaces.find(b => b.name === binding.interfaceName)
if (saved && saved.kind !== "uplink" && !saved.peerServerId && !saved.linux && !saved.provisionWireguard && !saved.provisionGre &&
!saved.provisionTransit && !site?.neighbors.some(p => p.binding === saved.name)) {
return { label: "Создать группу с этим туннелем", open: () => { open(); setInitialInterface(binding); setImporting(true) } }
}
}, catalog)
if (!live) return <>{rows}</>
return <>{rows}<Frame spacing="sm">
<FrameHeader className="flex-row flex-wrap items-center justify-between gap-2">
<FrameTitle>Группы туннелей VPS</FrameTitle>
{!readOnly && <Button size="sm" variant="outline" onClick={() => open()}>Создать группу</Button>}
</FrameHeader>
<FramePanel className="grid gap-3">
{!draft && issue}
{!ownedGroups.length && <p className="text-sm text-muted-foreground">Туннели этого сегмента используются отдельно.</p>}
{ownedGroups.map(g => <div key={g.id} className="grid gap-1.5">
const renderGroups = (clientId: string) => ownedGroups.filter(g => g.clientId === clientId).map(g => <div key={g.id} className="grid gap-1.5">
<span className="font-medium">{g.name} · {modeLabel(g.mode)}</span>
<ol className="grid gap-1 text-sm">{g.members.map((m, i) => {
const c = available.get(memberKey(m))
@@ -131,9 +108,23 @@ export function IxClientBonds({ segmentId, segments, backendUrl, nodes, readOnly
download("ix-bond-" + g.id + ".json", JSON.stringify(bundle, null, 2))
})}>Скачать для ix-client</Button>
</div>}
</div>)}
{!!ownedGroups.length && <p className="text-sm text-muted-foreground">Импортируйте JSON в ix-client на VPS и сверьте выбранные локальные интерфейсы. Активный путь показывает TUI клиента.</p>}
</FramePanel>
</div>)
const rows = children(binding => {
const k = memberKey({ ...binding, segmentId })
const current = ownedGroups.find(g => g.members.some(m => memberKey(m) === k))
const candidate = available.get(k)
if (current) return { label: "Открыть группу «" + current.name + "»", open: () => open(current) }
if (candidate?.destinations.length) return { label: "Создать группу с этим туннелем", open: () => open(undefined, candidate) }
const site = segments.find(s => s.id === segmentId)?.configuration.sites.find(s => s.serverId === binding.serverId)
const saved = site?.interfaces.find(b => b.name === binding.interfaceName)
if (saved && saved.kind !== "uplink" && !saved.peerServerId && !saved.linux && !saved.provisionWireguard && !saved.provisionGre &&
!saved.provisionTransit && !site?.neighbors.some(p => p.binding === saved.name)) {
return { label: "Создать группу с этим туннелем", open: () => { open(); setInitialInterface(binding); setImporting(true) } }
}
}, catalog, renderGroups, live && !readOnly &&
<Button size="sm" variant="outline" onClick={() => open()}>Создать группу вручную</Button>)
if (!live) return <>{rows}</>
return <>{rows}{!draft && issue}
<Sheet open={!!draft} onOpenChange={value => !value && !busy && setDraft(null)}>
<SheetContent className="data-[side=right]:w-full data-[side=right]:sm:max-w-xl">
<SheetHeader><SheetTitle>Группа туннелей VPS</SheetTitle>
@@ -204,5 +195,5 @@ export function IxClientBonds({ segmentId, segments, backendUrl, nodes, readOnly
</form>}
</SheetContent>
</Sheet>
</Frame></>
</>
}
+53 -15
View File
@@ -1,6 +1,6 @@
"use client"
import { useMemo, useState } from "react"
import { useMemo, useState, type ReactNode } from "react"
import { type ColumnDef, useTable } from "@tanstack/react-table"
import { EllipsisIcon, PencilIcon, PlusIcon, RefreshCwIcon } from "lucide-react"
import type { IxBondCatalog, IxLinuxBinding, IxLinuxClientRequest, IxSegment, IxSite } from "@mmapp/contracts/internet-exchange"
@@ -17,6 +17,7 @@ import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@
import { Sheet, SheetContent, SheetDescription, SheetFooter, SheetHeader, SheetTitle } from "@/components/ui/sheet"
import { Textarea } from "@/components/ui/textarea"
import { isIpv4String } from "@/lib/gre-endpoint-resolve"
import { formatBytes } from "@/lib/fmt-rate"
import { publicEndpoint, transitName } from "./ix-exits"
import { nodeLabel, useIxNodeInventory, type IxNode } from "./ix-view"
import type { IxRowBondAction } from "./ix-client-bonds"
@@ -230,12 +231,21 @@ function ClientForm({ segment, edit, setAddProtocol, nodes, backendUrl, catalog,
</form>
}
export function IxLinuxClients({ segment, nodes, backendUrl, applied, readOnly, busy, error, save, refresh, revoke, view, inspect, bondAction, catalog }: {
function TunnelTable({ data, columns, busy }: {
data: IxLinuxBinding[]; columns: ColumnDef<DataGridFeatures, IxLinuxBinding>[]; busy: boolean
}) {
const table = useTable({ features: dataGridFeatures, manualPagination: true, data, columns,
getRowId: row => row.serverId + ":" + row.interfaceName })
return <DataGridShell table={table} recordCount={data.length} isLoading={busy && !data.length} loadingMode="skeleton" emptyMessage="В сегменте пока нет Linux-клиентов" />
}
export function IxLinuxClients({ segment, nodes, backendUrl, applied, readOnly, busy, error, save, refresh, revoke, view, 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
bondAction: IxRowBondAction; catalog: IxBondCatalog
renderGroups: (clientId: string) => ReactNode; manualGroup: ReactNode
}) {
const [open, setOpen] = useState(false)
const [edit, setEdit] = useState<ClientSelection | null>(null)
@@ -247,10 +257,27 @@ export function IxLinuxClients({ segment, nodes, backendUrl, applied, readOnly,
}] : []))
return [...saved, ...applied.filter(binding => !saved.some(item => item.serverId === binding.serverId && item.interfaceName === binding.interfaceName))]
}, [segment, applied])
const clients = new Map<string, { name: string; tunnels: IxLinuxBinding[]; hasGroups: boolean }>()
const relevantGroups = catalog.groups.filter(group => group.members.some(member => member.segmentId === segment.id))
const tunnelKey = (binding: Pick<IxLinuxBinding, "serverId" | "interfaceName">) => binding.serverId + ":" + binding.interfaceName
const affiliations = new Map(relevantGroups.flatMap(group => group.members.filter(member => member.segmentId === segment.id)
.map(member => [tunnelKey(member), group.clientId] as const)))
for (const row of rows) {
const key = affiliations.get(tunnelKey(row)) ?? row.policy?.clientId ?? tunnelKey(row)
const client = clients.get(key) ?? { name: row.name ?? row.interfaceName, tunnels: [], hasGroups: false }
if (row.name && !client.tunnels.some(tunnel => tunnel.name)) client.name = row.name
client.tunnels.push(row)
clients.set(key, client)
}
for (const group of relevantGroups) {
const client = clients.get(group.clientId) ?? { name: group.name, tunnels: [], hasGroups: false }
client.hasGroups = true
clients.set(group.clientId, client)
}
const columns = useMemo<ColumnDef<DataGridFeatures, IxLinuxBinding>[]>(() => [
{ id: "name", header: "Клиент", size: 170, cell: ({ row }) => <div className="grid gap-0.5">
<span className="font-medium">{row.original.name ?? row.original.interfaceName}</span>
<span className="text-xs text-muted-foreground">{nodeLabel(nodes, row.original.serverId)} · {row.original.interfaceName}</span>
{ id: "name", header: "Интерфейс", size: 195, cell: ({ row }) => <div className="grid gap-0.5">
<span className="break-all font-medium">{row.original.interfaceName}</span>
<span className="text-xs text-muted-foreground">{nodeLabel(nodes, row.original.serverId)}</span>
</div> },
{ id: "transport", header: "Туннель", size: 105, cell: ({ row }) => row.original.kind === "wireguard" ? "WireGuard" : "GRE/IPsec" },
{ id: "egress", header: "Выход трафика", size: 205, cell: ({ row }) => {
@@ -274,11 +301,15 @@ export function IxLinuxClients({ segment, nodes, backendUrl, applied, readOnly,
if (!site?.interfaces.some(item => item.name === binding.interfaceName)) return <Badge variant="warning-light">Ожидает отзыва</Badge>
if (!live || JSON.stringify(binding.policy) !== JSON.stringify(live.policy)) return <Badge variant="warning-light">Ожидает сохранения</Badge>
if (!binding.enabled) return <Badge variant="secondary">Приостановлен</Badge>
return binding.connection?.state === "connected" ? <div className="grid gap-1">
<Badge variant="success-light" className="w-fit">Подключён</Badge>
{binding.connection.rx !== undefined && <span className="text-xs text-muted-foreground">RX {binding.connection.rx} · TX {binding.connection.tx}</span>}
const { state, rx, tx } = binding.connection ?? {}
return <div className="grid gap-1">
<Badge className="w-fit" variant={state === "connected" ? "success-light" : "secondary"}>
{state === "connected" ? "Подключён" : state === "waiting" ? "Ожидает туннель" : "Нет данных"}
</Badge>
{(rx !== undefined || tx !== undefined) && <span className="text-xs text-muted-foreground" title="Счётчики на узле IX">
RX {rx !== undefined ? formatBytes(Number(rx)) : "—"} · TX {tx !== undefined ? formatBytes(Number(tx)) : "—"}
</span>}
</div>
: <Badge variant="secondary">{binding.connection?.state === "waiting" ? "Ожидает туннель" : "Нет данных"}</Badge>
} },
{ id: "actions", header: "Действия", size: 140, cell: ({ row }) => {
const binding = row.original
@@ -292,7 +323,8 @@ export function IxLinuxClients({ segment, nodes, backendUrl, applied, readOnly,
(paired ? binding.kind === "wireguard" ? " · WireGuard" : " · GRE/IPsec" : "")}
onClick={() => view(live)}>Конфиг Linux</Button>}
{(bond || binding.policy && (live || !readOnly && saved?.linux)) && <DropdownMenu>
<DropdownMenuTrigger render={<Button type="button" size="icon-sm" variant="ghost" disabled={busy} aria-label={"Действия клиента " + (binding.name ?? binding.interfaceName)} />}>
<DropdownMenuTrigger render={<Button type="button" size="icon-sm" variant="ghost" disabled={busy} aria-label={"Действия клиента " +
(binding.name ?? binding.interfaceName) + (paired ? " · " + binding.interfaceName : "")} />}>
<EllipsisIcon aria-hidden />
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
@@ -308,19 +340,25 @@ export function IxLinuxClients({ segment, nodes, backendUrl, applied, readOnly,
</div>
} },
], [nodes, applied, segment, readOnly, busy, view, revoke, inspect, bondAction, catalog.candidates])
const table = useTable({ features: dataGridFeatures, manualPagination: true, data: rows, columns,
getRowId: row => row.serverId + ":" + row.interfaceName })
return <Frame spacing="sm" className="min-w-0">
<FrameHeader className="flex-row flex-wrap items-center justify-between gap-2">
<FrameTitle>Linux-клиенты</FrameTitle>
<div className="flex flex-wrap items-center gap-2">
<Button type="button" size="icon-sm" variant="outline" aria-label="Обновить клиентов" disabled={busy || !segment.appliedRevision} onClick={refresh}><RefreshCwIcon /></Button>
{!readOnly && <Button type="button" size="sm" disabled={busy} onClick={() => { setEdit(null); setOpen(true) }}><PlusIcon />Подключить Linux</Button>}
{manualGroup}
</div>
</FrameHeader>
<FramePanel className="min-w-0 p-0">
<DataGridShell table={table} recordCount={rows.length} isLoading={busy && !rows.length} loadingMode="skeleton" emptyMessage="В сегменте пока нет Linux-клиентов" />
</FramePanel>
{clients.size ? [...clients].map(([key, client]) => <FramePanel key={key} className="grid min-w-0 gap-3 p-0">
<section aria-label={"Клиент " + client.name} className="grid min-w-0 gap-3">
<h3 className="px-4 pt-3 text-sm font-semibold">{client.name}</h3>
{!!client.tunnels.length && <TunnelTable data={client.tunnels} columns={columns} busy={busy} />}
{client.hasGroups && <div className="grid gap-3 px-4 pb-4">
<h4 className="text-sm font-medium">Группы туннелей</h4>
{renderGroups(key)}
</div>}
</section>
</FramePanel>) : <FramePanel className="min-w-0 p-0"><TunnelTable data={rows} columns={columns} busy={busy} /></FramePanel>}
<Sheet open={open} onOpenChange={value => !busy && setOpen(value)}>
<SheetContent className="data-[side=right]:w-full data-[side=right]:sm:max-w-lg" showCloseButton={!busy}>
<SheetHeader><SheetTitle>{edit?.chooseTransport ? "Добавить туннель" : edit?.addProtocol ? "Добавить другой протокол" : edit ? "Доступ и выход клиента" : "Подключить Linux"}</SheetTitle>
+2 -1
View File
@@ -469,7 +469,8 @@ export default function IxPage() {
<TabsContent value="linux" className="grid min-w-0 gap-3">
{selected ? <IxClientBonds key={selected.id + ":" + selected.appliedRevision} segmentId={selected.id} segments={segments}
backendUrl={backendUrl} nodes={peers} readOnly={!write || busy || dirty} live={live} download={download}>
{(bondAction, catalog) => <IxLinuxClients segment={selected} nodes={peers} backendUrl={backendUrl} bondAction={bondAction} catalog={catalog}
{(bondAction, catalog, renderGroups, manualGroup) => <IxLinuxClients segment={selected} nodes={peers} backendUrl={backendUrl}
bondAction={bondAction} catalog={catalog} renderGroups={renderGroups} manualGroup={manualGroup}
applied={linuxBindings} busy={busy} error={error} readOnly={!live || !write || dirty}
save={input => perform(() => stageClient(input))} revoke={binding => void perform(() => stageClient(binding))}
refresh={() => void perform(loadLinuxBindings)} view={(binding, transportOnly) => void perform(() => exportLinux(binding, transportOnly))}
@@ -41,6 +41,16 @@ const serveRouter = (rows: RouterRows): RequestListener => async (request, respo
const path = new URL(request.url!, "http://127.0.0.1").pathname.replace(/^\/rest/, "")
let result: unknown
if (request.method === "GET") result = rows[path] ?? []
else if (request.method === "POST" && path === "/interface/print") {
let raw = ""
for await (const chunk of request) raw += chunk
const body = JSON.parse(raw)
assert.equal(body.stats, "")
result = (rows["/interface"] ?? []).map(row => {
const gre = rows["/interface/gre"]?.some(item => item.name === row.name)
return { name: row.name, "rx-byte": gre ? "1536" : "9000", "tx-byte": gre ? "2048" : "8000" }
})
}
else if (request.method === "PUT") {
if (writes === failPutAt) throw Error("Synthetic RouterOS apply failure")
let raw = ""
@@ -312,6 +322,8 @@ try {
const clientInput = { serverId: Number(server.id), name: "linux-auto", kind: "wireguard", hubEndpoint: "192.0.2.20",
peerEndpoint: "192.0.2.40", exit: "local-wan", prefixes: [], destinations: ["203.0.113.0/24"], enabled: true }
const staged = await post(managedPath + "/linux", { ...clientInput, revision: managed.revision }, 200)
assert.match(staged.interfaceName, /^il-wg-[a-z0-9-]+-[0-9a-f]{12}$/)
assert.ok(staged.segment.configuration.sites[0].interfaces[0].linux.clientId)
const clientKey = { serverId: clientInput.serverId, interfaceName: staged.interfaceName }
await post(managedPath + "/linux/credential", clientKey, 409)
await post(managedPath + "/linux/credential", clientKey, 403, reader)
@@ -379,6 +391,7 @@ try {
const paired = await post(managedPath + "/linux", { ...companionInput, revision: resumed.segment.revision }, 200)
const bindings = paired.segment.configuration.sites[0].interfaces
const [wireguard, greBinding] = bindings
assert.match(greBinding.name, /^il-gre-[a-z0-9-]+-[0-9a-f]{12}$/)
assert.ok(wireguard.linux.clientId)
const original = resumed.segment.configuration.sites[0].interfaces[0]
assert.deepEqual(wireguard, { ...original, linux: { ...original.linux, clientId: wireguard.linux.clientId } })
@@ -393,6 +406,11 @@ try {
const pairPlan = await post(managedPath + "/plan", { revision: paired.segment.revision }, 200)
assert(!pairPlan.changes.some(change => change.path.startsWith("/interface/wireguard")))
const pairedApplied = await post(managedPath + "/apply", { revision: paired.segment.revision, digest: pairPlan.digest }, 200)
const countersResponse = await fetch(origin + "/api/ix/segments" + managedPath + "/linux", { headers: { authorization: "Bearer " + reader } })
assert.equal(countersResponse.status, 200)
const observedGre = (await countersResponse.json()).items.find(item => item.interfaceName === greBinding.name)
assert.equal(observedGre.connection.rx, "1536")
assert.equal(observedGre.connection.tx, "2048")
const pairVrf = rows["/ip/vrf"].find(row => row.interfaces?.includes(wireguard.name))!
assert(pairVrf.interfaces.split(",").includes(greBinding.name))
const greCredential = await post(managedPath + "/linux/credential",
+2
View File
@@ -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 })
})
@@ -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)))
}
@@ -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"]){
+1 -1
View File
@@ -23,7 +23,7 @@ export function installDatabaseRequestGate(app: FastifyInstance, admit = withDat
const run = async () => withConfigurationActor(request.authUser?.id ?? "system", async () => await original.call(this, request, reply))
// 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 {
+22 -12
View File
@@ -1,3 +1,4 @@
import { coalesceCatalogReads, observationIsCurrent, readCatalogWithObservedCache, withCatalogWriteLock } from "../services/routing-catalog-observation.js"
import { and, asc, eq, inArray } from "drizzle-orm"
import { 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) })
}
+1 -1
View File
@@ -53,7 +53,7 @@ const ixRoutes: FastifyPluginAsync = async app => {
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 не подтверждено. Обновите данные и проверьте план."
+41 -25
View File
@@ -1,9 +1,10 @@
import { coalesceCatalogReads, observationIsCurrent, readCatalogWithObservedCache, withCatalogWriteLock } from "../services/routing-catalog-observation.js"
import { recursiveApplyBodySchema, recursiveTargetSchema, recursiveInputRowsSchema } from '../services/recursive-route-validation.js'
import { 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 })
}
})
+11
View File
@@ -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() }
})
+4 -4
View File
@@ -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 })
}
})
+5 -5
View File
@@ -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> {
@@ -90,7 +90,7 @@ export async function withApplicationCollectorLock<T>(work: () => Promise<T>): P
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 +159,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()
}
@@ -167,6 +167,10 @@ function verifyEgressMembers(device: NativeDevice, id: string, objects: IxRouter
async function readRows(client: IpCore, path: string, props: readonly string[]) {
const raw = await client.get<unknown>(path + "?" + new URLSearchParams({ ".proplist": [...new Set(props)].join(",") }))
return nativeRows(raw, props)
}
function nativeRows(raw: unknown, props: readonly string[]) {
if (!Array.isArray(raw) || raw.length > 10000 || raw.some(value => !value || typeof value !== "object" || Array.isArray(value))) {
throw new IxConflict("Не удалось прочитать полный каталог RouterOS")
}
@@ -280,8 +284,8 @@ export async function configureIxLinuxClient(segment: IxSegment, input: IxLinuxC
}) : undefined
const result = second ?? first
const currentId = site?.interfaces.find(binding => binding.name === input.interfaceName)?.linux?.clientId
const clientId = existingId ?? input.vpsClientId ?? currentId ?? (companion || second ? randomUUID() : undefined)
if (!clientId) return result
const clientId = existingId ?? input.vpsClientId ?? currentId ??
(input.interfaceName ? await ixBondClientId(segment.id, input.serverId, input.interfaceName) : undefined) ?? randomUUID()
const siblings = new Set([first.interfaceName, second?.interfaceName, companion ? companion.name : undefined])
return { interfaceName: first.interfaceName, configuration: {
...result.configuration,
@@ -332,7 +336,9 @@ async function configureIxLinuxTunnel(segment: IxSegment, input: IxLinuxClientRe
}
let listenPort = 51820
while (ports.has(listenPort) && listenPort <= 65535) listenPort++
const name = previous?.name ?? "il-" + randomUUID().replace(/-/g, "").slice(0, 12)
const slug = input.name.normalize("NFKD").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "").slice(0, 24).replace(/-$/, "")
const transport = input.kind === "wireguard" ? "wg" : "gre"
const name = previous?.name ?? ["il", transport, slug || "vps", randomUUID().replace(/-/g, "").slice(0, 12)].join("-")
const family = isIP(peerAddress)
const localExit = "ix-wan" + family
const groups = [...site.groups]
@@ -808,23 +814,30 @@ export async function listIxLinuxClients(segment: IxSegment) {
const observedAt = new Date().toISOString()
try {
const client = await requiredIxNode(site.serverId)
const [peers, ipsec] = await Promise.all([
const hasGre = bindings.some(binding => binding.linux?.enabled && binding.provisionGre)
const counterFields = ["name", "rx-byte", "tx-byte"]
const [peers, ipsec, stats] = await Promise.all([
bindings.some(binding => binding.linux && binding.provisionWireguard) ? readRows(client, "/interface/wireguard/peers",
["interface", "public-key", "last-handshake", "rx", "tx"]) : [],
bindings.some(binding => binding.linux && binding.provisionGre) ? readRows(client, "/ip/ipsec/active-peers", ["remote-address", "state"]) : [],
["interface", "public-key", "last-handshake", "rx", "tx"]).catch(() => null) : [],
hasGre ? readRows(client, "/ip/ipsec/active-peers", ["remote-address", "state"]).catch(() => null) : [],
hasGre ? client.post<unknown>("/interface/print", { stats: "", ".proplist": counterFields })
.then(raw => nativeRows(raw, counterFields)).catch(() => []) : [],
])
for (const [index, binding] of bindings.entries()) {
if (!binding.linux?.enabled) continue
const peer = peers.find(row => row.interface === binding.name && row["public-key"] === binding.provisionWireguard?.peerPublicKey)
const peer = peers?.find(row => row.interface === binding.name && row["public-key"] === binding.provisionWireguard?.peerPublicKey)
const handshake = peer?.["last-handshake"]?.trim()
const age = handshake && /^\d+:\d{2}:\d{2}$/.test(handshake)
? handshake.split(":").reduce((total, part) => total * 60 + Number(part), 0)
: handshake && /^(?:(\d+)m)?(?:(\d+)s)?$/.exec(handshake)
const fresh = typeof age === "number" ? age < 180 :
Array.isArray(age) && Number(age[1] ?? 0) * 60 + Number(age[2] ?? 0) < 180
const established = binding.provisionGre && ipsec.some(row => row.state === "established" &&
const established = binding.provisionGre && ipsec?.some(row => row.state === "established" &&
(row["remote-address"] === binding.endpoint || row["remote-address"]?.startsWith(binding.endpoint + ":")))
items[index].connection = { observedAt, state: fresh || established ? "connected" : "waiting", ...(peer && { rx: peer.rx, tx: peer.tx }) }
const iface = binding.provisionGre && stats.find(row => row.name === binding.name)
const state = fresh || established ? "connected" : (binding.provisionGre ? ipsec : peers) === null ? "unknown" : "waiting"
items[index].connection = { observedAt, state,
rx: peer?.rx ?? (iface ? iface["rx-byte"] : undefined), tx: peer?.tx ?? (iface ? iface["tx-byte"] : undefined) }
}
} catch {
for (const item of items) if (item.enabled) item.connection = { observedAt, state: "unknown" }
@@ -47,7 +47,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]
}
@@ -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,146 @@
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 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)), async () => {
await assertCatalogSource(server)
const latest = await read(true)
return latest.current ? latest : save(latest)
})
} finally { catalogRefreshes.delete(serverId); done() }
}
+1 -1
View File
@@ -216,7 +216,7 @@ export async function runSchedulerJobNow(jobKey: string): Promise<SchedulerRunRe
throw new Error(`Unknown job key: ${jobKey}`)
}
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 -1
View File
@@ -80,7 +80,7 @@ async function getSettingsRow() {
...trafficSettingsDefaults,
createdAt: now,
updatedAt: now,
})
}).onConflictDoNothing({ target: trafficSettings.id })
return readSettingsRow()
}
+1 -1
View File
@@ -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]
}
+2
View File
@@ -66,6 +66,8 @@
### Несколько туннелей на одном VPS
Карточка Linux-клиента объединяет его туннели и группы резервирования. Для нового интерфейса RouterOS имя включает протокол, имя клиента и уникальный суффикс, например `il-gre-tg-a1b2c3d4e5f6`. Существующие подключения сохраняют свои имена. RX и TX в строке GRE/IPsec показывают накопленные байты интерфейса на CHR.
1. В **Linux-клиенты** откройте меню действующего подключения и выберите **Создать группу с этим туннелем**. Интерфейс уже будет первым в списке. Для участника существующей группы это же меню открывает её редактор. Ключи VPS и CHR при создании группы сохраняются. Для нового транспорта откройте меню клиента и скачайте **Конфиг для группы ix-client**.
2. Добавьте второе подключение одного VPS. Старые управляемые подключения без идентификатора VPS можно выбрать вместе, подтвердив их принадлежность одному серверу. Для исправления прежней привязки свободного подключения откройте **Доступ и выход → Привязка к VPS**, выберите VPS и сохраните ревизию. У всех участников должны различаться внутренние IP-адреса VPS и IX и совпадать семейство адресов и сети назначения. В режиме резервирования первым поставьте основной, затем резервы в порядке предпочтения. В параллельном режиме задайте равное распределение или веса. В прямые исключения внесите сети, к которым VPS должен обращаться через WAN.
3. Нажмите **Скачать для ix-client** и импортируйте JSON группы через **B → I**. Если имя интерфейса на VPS отличается от имени в JSON, ix-client сопоставит существующий транспорт по адресам и параметрам пира. Проверьте найденное локальное имя и соответствие туннеля в предварительном просмотре **F2**. Нажмите **Enter** для применения и **Y** для подтверждения. Без подтверждения через 60 секунд восстановится предыдущая конфигурация. Одиночные интерфейсы можно продолжать использовать отдельно.
+3 -1
View File
@@ -71,7 +71,9 @@ test("Filters: чтение под общей блокировкой повто
await page.route("**/health", route => route.fulfill({ json: { ok: true } }))
await page.route("**/api/**", async route => {
const { pathname, searchParams } = new URL(route.request().url())
const conflict = () => route.fulfill({ status: 409, json: { error: "Глобальная конфигурация изменяется другой операцией" } })
const conflict = () => route.fulfill({ status: 409, json: lock === "held"
? { code: "CONFIGURATION_BUSY", error: "Конфигурация временно занята другой операцией" }
: { error: "Глобальная конфигурация изменяется другой операцией" } })
if (pathname === "/api/filters/rules" && searchParams.has("serverId")) {
if (lock === "held" || lock === "brief") {
conflicts++
+7 -2
View File
@@ -65,8 +65,9 @@ test("IX: сборка группы VPS из двух площадок с вес
await expect(editor.getByRole("button", { name: "Сохранить" })).toBeDisabled()
await editor.getByRole("checkbox", { name: "Подтверждаю, что выбранные интерфейсы настроены на одном VPS" }).check()
await editor.getByRole("button", { name: "Сохранить" }).click()
await expect(page.getByText("vps-01 · Параллельно, по весам")).toBeVisible()
await expect(page.getByRole("button", { name: "Скачать для ix-client" })).toBeVisible()
const clientCard = page.getByRole("region", { name: "Клиент wg-vps", exact: true })
await expect(clientCard.getByText("vps-01 · Параллельно, по весам")).toBeVisible()
await expect(clientCard.getByRole("button", { name: "Скачать для ix-client" })).toBeVisible()
await page.getByRole("button", { name: "Действия клиента wg-vps" }).click()
await page.getByRole("menuitem", { name: "Открыть группу «vps-01»" }).click()
await expect(editor.getByLabel("Имя группы")).toHaveValue("vps-01")
@@ -372,6 +373,7 @@ for (const mode of ["WAN IX", "два протокола", "новый ExitNode"
if (path === `/api/ix/segments/${id}/linux`) {
return json({ revision: segment.appliedRevision, items: segment.appliedRevision >= 3 && client ? [
client, ...(both || segment.appliedRevision === 5 ? [{ name: "vps-01", kind: "gre-ipsec", serverId: 1, interfaceName: "il-gre",
connection: { observedAt, state: "connected", rx: "1536", tx: "2048" },
policy: segment.configuration.sites[0].interfaces[1].linux }] : []),
] : [] })
}
@@ -418,6 +420,9 @@ for (const mode of ["WAN IX", "два протокола", "новый ExitNode"
expect(await readFile((await file.path())!, "utf8")).toBe(configFile)
await expect(page.getByText("TEST_PRIVATE_KEY")).toHaveCount(0)
if (both) {
const card = page.getByRole("region", { name: "Клиент vps-01", exact: true })
await expect(card.getByRole("row").filter({ hasText: "il-vps" })).toHaveCount(1)
await expect(card.getByRole("row").filter({ hasText: "il-gre" })).toContainText("RX 1.5 КБ · TX 2.0 КБ")
await page.getByRole("button", { name: "Получить конфиг vps-01 · GRE/IPsec", exact: true }).click()
await expect(page.getByText(/sudo sh .\/vps-gre-setup\.sh/)).toBeVisible()
await expect(page.getByText("TEST_PSK")).toHaveCount(0)