97 lines
3.4 KiB
TypeScript
97 lines
3.4 KiB
TypeScript
import { eq, sql } from "drizzle-orm"
|
|
import type { FastifyPluginAsyncZod } from "@fastify/type-provider-zod"
|
|
import { createEvoBgpCatalogRoutes } from "./evobgp-catalog.js"
|
|
import { createEvoBgpSettingsRoutes } from "./evobgp-settings.js"
|
|
import { db } from "../db/index.js"
|
|
import { evobgpSettings, filterRules } from "../db/schema.js"
|
|
|
|
async function ensureEvobgpRow() {
|
|
let row = (await db.select().from(evobgpSettings).where(eq(evobgpSettings.id, 1)).limit(1))[0]
|
|
if (!row) {
|
|
await db.insert(evobgpSettings).values({ id: 1 }).onConflictDoNothing()
|
|
row = (await db.select().from(evobgpSettings).where(eq(evobgpSettings.id, 1)).limit(1))[0]
|
|
}
|
|
return row!
|
|
}
|
|
|
|
/**
|
|
* Уникальные серверы из локальной БД, у которых в BGP-фильтре указан community (строка AS:NNN).
|
|
* Ключ — значение `filter_rules.community` после trim (как в EvoBGP `community`).
|
|
*/
|
|
async function distinctServersByFilterCommunityValue(): Promise<Map<string, number>> {
|
|
const rows = await db
|
|
.select({ serverId: filterRules.serverId, community: filterRules.community })
|
|
.from(filterRules)
|
|
const byVal = new Map<string, Set<number>>()
|
|
for (const r of rows) {
|
|
const v = (r.community ?? "").trim()
|
|
if (!v) continue
|
|
let set = byVal.get(v)
|
|
if (!set) {
|
|
set = new Set()
|
|
byVal.set(v, set)
|
|
}
|
|
set.add(r.serverId)
|
|
}
|
|
const out = new Map<string, number>()
|
|
for (const [v, set] of byVal) out.set(v, set.size)
|
|
return out
|
|
}
|
|
|
|
function problemMessage(text: string, status: number): string {
|
|
try {
|
|
const j = JSON.parse(text) as { detail?: string; title?: string }
|
|
return j.detail ?? j.title ?? `HTTP ${status}`
|
|
} catch {
|
|
return text || `HTTP ${status}`
|
|
}
|
|
}
|
|
|
|
async function fetchEvoJson<T>(root: string, path: string, token: string): Promise<T> {
|
|
const url = `${root}${path.startsWith("/") ? "" : "/"}${path}`
|
|
const ac = new AbortController()
|
|
const t = setTimeout(() => ac.abort(), 90_000)
|
|
try {
|
|
const res = await fetch(url, {
|
|
method: "GET",
|
|
headers: {
|
|
Authorization: `Bearer ${token}`,
|
|
Accept: "application/json",
|
|
},
|
|
signal: ac.signal,
|
|
})
|
|
const text = await res.text()
|
|
if (!res.ok) {
|
|
throw new Error(problemMessage(text, res.status))
|
|
}
|
|
return JSON.parse(text) as T
|
|
} finally {
|
|
clearTimeout(t)
|
|
}
|
|
}
|
|
|
|
const evobgpRoutes: FastifyPluginAsyncZod = async (app) => {
|
|
await app.register(createEvoBgpSettingsRoutes({
|
|
read: ensureEvobgpRow,
|
|
probe: (root,key) => fetchEvoJson<unknown>(root,"/v1/modules?limit=1",key),
|
|
write: async patch => {
|
|
await ensureEvobgpRow()
|
|
const values: {baseUrl?:string;enabled?:boolean;apiKey?:string} = {}
|
|
if(patch.baseUrl!==undefined) values.baseUrl=patch.baseUrl
|
|
if(patch.enabled!==undefined) values.enabled=patch.enabled
|
|
if(patch.apiKey!==undefined) values.apiKey=patch.apiKey??""
|
|
const [row] = await db.update(evobgpSettings).set({...values,updatedAt:sql`now()`}).where(eq(evobgpSettings.id,1)).returning()
|
|
if(!row) throw new Error("Сохранение EvoBGP не подтверждено сервером")
|
|
return row
|
|
},
|
|
}))
|
|
|
|
await app.register(createEvoBgpCatalogRoutes({
|
|
read: ensureEvobgpRow,
|
|
fetchCatalog: (root,key) => fetchEvoJson<unknown>(root,"/v1/router-lists/catalog",key),
|
|
serversByCommunity: distinctServersByFilterCommunityValue,
|
|
}))
|
|
}
|
|
|
|
export default evobgpRoutes
|