222 lines
9.5 KiB
TypeScript
222 lines
9.5 KiB
TypeScript
import { env } from "../config.js"
|
|
import { mcpDatabaseRequestSignal, withDatabaseApiRequest } from "../modules/mcp/database-request-lease.js"
|
|
import { McpError } from "../modules/mcp/security.js"
|
|
import { registerDatabaseStreamAbort } from "../plugins/database-request-gate.js"
|
|
import { eq } from "drizzle-orm"
|
|
import type { FastifyPluginAsyncZod } from "@fastify/type-provider-zod"
|
|
import { db } from "../db/index.js"
|
|
import { servers } from "../db/schema.js"
|
|
import {
|
|
readPublicTrafficSettings,
|
|
toTrafficSettingsDto,
|
|
updateTrafficSettings,
|
|
} from "../services/traffic-collector.js"
|
|
import { refreshScheduler } from "../services/scheduler.js"
|
|
import { collectTrafficManually } from "../services/manual-traffic-collection.js"
|
|
import { readTrafficLiveSample, TrafficLiveSourceChanged } from "../services/traffic-live.js"
|
|
import { MikrotikClient, MikrotikError } from "../services/mikrotik.js"
|
|
import { getEnabledServerById } from "../services/wireguard-live.js"
|
|
import { readTrafficCollectionContext } from "../services/traffic-collection-state.js"
|
|
import { readServerTrafficHistory, readServerTrafficInterfaces } from "../services/traffic-history-read.js"
|
|
import {
|
|
buildBoundInterfaceTraffic,
|
|
buildUserTrafficList,
|
|
} from "../services/traffic-users.js"
|
|
|
|
const LIVE_TICK_MS = 1500
|
|
|
|
function rangeToMinutes(range: string | undefined): number {
|
|
switch ((range ?? "1h").toLowerCase()) {
|
|
case "5m": return 5
|
|
case "15m": return 15
|
|
case "1h": return 60
|
|
case "4h": return 240
|
|
case "24h": return 1440
|
|
default: return 60
|
|
}
|
|
}
|
|
|
|
function writeSse(raw: NodeJS.WritableStream, event: string, data: unknown) {
|
|
raw.write(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`)
|
|
}
|
|
|
|
function sleep(ms: number, signal: AbortSignal): Promise<void> {
|
|
return new Promise((resolve, reject) => {
|
|
if (signal.aborted) {
|
|
reject(new Error("aborted"))
|
|
return
|
|
}
|
|
const timer = setTimeout(() => {
|
|
signal.removeEventListener("abort", onAbort)
|
|
resolve()
|
|
}, ms)
|
|
const onAbort = () => {
|
|
clearTimeout(timer)
|
|
reject(new Error("aborted"))
|
|
}
|
|
signal.addEventListener("abort", onAbort, { once: true })
|
|
})
|
|
}
|
|
|
|
const trafficRoutes: FastifyPluginAsyncZod = async (app) => {
|
|
app.get("/traffic/settings", async (_req, reply) => {
|
|
return reply.send(await readPublicTrafficSettings())
|
|
})
|
|
|
|
app.put("/traffic/settings", async (req, reply) => {
|
|
const body = req.body as {
|
|
enabled?: boolean
|
|
intervalSec?: number | string
|
|
retentionDays?: number | string
|
|
}
|
|
const intervalSec = body.intervalSec == null ? undefined : Math.max(5, Number.parseInt(String(body.intervalSec), 10) || 30)
|
|
const retentionDays = body.retentionDays == null ? undefined : Math.max(1, Number.parseInt(String(body.retentionDays), 10) || 14)
|
|
const updated = await updateTrafficSettings({
|
|
enabled: body.enabled,
|
|
intervalSec,
|
|
retentionDays,
|
|
})
|
|
await refreshScheduler()
|
|
return reply.send({
|
|
ok: true,
|
|
settings: toTrafficSettingsDto(updated),
|
|
})
|
|
})
|
|
|
|
app.post("/traffic/collect-now", async (_req, reply) => {
|
|
const result = await collectTrafficManually()
|
|
return reply.status(result.statusCode).send(result.body)
|
|
})
|
|
|
|
app.get("/traffic/servers", async (req, reply) => {
|
|
const q = req.query as { range?: string }
|
|
const rangeEndMs = Date.now(), rangeStartMs = rangeEndMs - rangeToMinutes(q.range) * 60000
|
|
const allServers = await db.select().from(servers).where(eq(servers.enabled, true))
|
|
const context = await readTrafficCollectionContext(allServers.map(server => server.id))
|
|
const data = await Promise.all(allServers.map(server => readServerTrafficHistory(server, rangeStartMs, rangeEndMs, undefined, {}, context)))
|
|
return reply.send({ servers: data })
|
|
})
|
|
app.get("/traffic/servers/:id/live", async (req, reply) => {
|
|
const p = req.params as { id?: string | number }
|
|
const q = req.query as { iface?: string }
|
|
const readServer = (id: string | number, signal?: AbortSignal) => withDatabaseApiRequest(async () => {
|
|
signal?.throwIfAborted()
|
|
const row = await getEnabledServerById(id)
|
|
mcpDatabaseRequestSignal()?.throwIfAborted()
|
|
return row
|
|
})
|
|
const server = await readServer(p.id ?? "")
|
|
if (!server || !server.enabled) return reply.status(404).send({ error: "Server not found" })
|
|
|
|
const onlyInterface = q.iface && q.iface !== "__all__" ? q.iface : undefined
|
|
const abort = new AbortController()
|
|
const onClose = () => abort.abort()
|
|
registerDatabaseStreamAbort(req, onClose)
|
|
if (abort.signal.aborted) return reply.code(503).send({ error: "Выполняется операция с базой приложения" })
|
|
if (reply.raw.destroyed) return
|
|
reply.raw.on("close", onClose)
|
|
|
|
reply.hijack()
|
|
req.raw.setTimeout(0)
|
|
reply.raw.setTimeout(0)
|
|
const origin = typeof req.headers.origin === "string" ? req.headers.origin : ""
|
|
const allowed = env.CORS_ORIGIN
|
|
const sseHeaders: Record<string, string> = {
|
|
"Content-Type": "text/event-stream; charset=utf-8",
|
|
"Cache-Control": "no-cache, no-transform",
|
|
Connection: "keep-alive",
|
|
"X-Accel-Buffering": "no",
|
|
}
|
|
if (origin && (allowed === "*" || allowed === origin)) {
|
|
sseHeaders["Access-Control-Allow-Origin"] = origin
|
|
sseHeaders["Access-Control-Allow-Credentials"] = "true"
|
|
sseHeaders["Access-Control-Allow-Headers"] = "Authorization, Accept"
|
|
sseHeaders.Vary = "Origin"
|
|
}
|
|
reply.raw.writeHead(200, sseHeaders)
|
|
reply.raw.write(":\n\n")
|
|
|
|
const client = MikrotikClient.fromServer(server)
|
|
const cache = { names: onlyInterface ? [onlyInterface] : [] as string[], joinedFailed: false }
|
|
|
|
try {
|
|
while (!abort.signal.aborted) {
|
|
try {
|
|
const sample = await readTrafficLiveSample(client, onlyInterface, cache, abort.signal, async () => {
|
|
const current = await readServer(server.id, abort.signal)
|
|
if (!current) throw new TrafficLiveSourceChanged("Устройство выключено или удалено. Live-поток остановлен")
|
|
if (Date.parse(current.updatedAt) !== Date.parse(server.updatedAt)) throw new TrafficLiveSourceChanged("Конфигурация устройства изменилась. Переподключите live-поток")
|
|
})
|
|
if (abort.signal.aborted) break
|
|
writeSse(reply.raw, "sample", sample)
|
|
} catch (error) {
|
|
if (abort.signal.aborted) break
|
|
const msg = error instanceof Error ? error.message : String(error)
|
|
writeSse(reply.raw, "error", { error: msg.slice(0,1024) })
|
|
if (error instanceof TrafficLiveSourceChanged || error instanceof McpError || error instanceof MikrotikError && [401,403].includes(error.statusCode)) break
|
|
}
|
|
await sleep(LIVE_TICK_MS, abort.signal)
|
|
}
|
|
} catch {
|
|
/* abort / disconnect */
|
|
} finally {
|
|
reply.raw.off("close", onClose)
|
|
try {
|
|
reply.raw.end()
|
|
} catch {
|
|
/* already closed */
|
|
}
|
|
}
|
|
})
|
|
|
|
app.get("/traffic/servers/:id/interfaces", async (req, reply) => {
|
|
const p = req.params as { id?: string | number }
|
|
const serverId = Number.parseInt(String(p.id ?? ""), 10)
|
|
if (!Number.isFinite(serverId)) return reply.status(400).send({ error: "id is required" })
|
|
const server = (await db.select().from(servers).where(eq(servers.id, serverId)).limit(1))[0]
|
|
if (!server) return reply.status(404).send({ error: "Server not found" })
|
|
return reply.send({ interfaces: (await readServerTrafficInterfaces(server)).interfaces })
|
|
})
|
|
app.get("/traffic/servers/:id", async (req, reply) => {
|
|
const p = req.params as { id?: string | number }
|
|
const q = req.query as { range?: string; iface?: string }
|
|
const serverId = Number.parseInt(String(p.id ?? ""), 10)
|
|
if (!Number.isFinite(serverId)) return reply.status(400).send({ error: "id is required" })
|
|
const server = (await db.select().from(servers).where(eq(servers.id, serverId)).limit(1))[0]
|
|
if (!server) return reply.status(404).send({ error: "Server not found" })
|
|
const end = Date.now()
|
|
return reply.send({ server: await readServerTrafficHistory(server, end - rangeToMinutes(q.range) * 60000, end, q.iface && q.iface !== "__all__" ? q.iface : undefined) })
|
|
})
|
|
app.get("/traffic/users", async (req, reply) => {
|
|
const q = req.query as { range?: string }
|
|
const minutes = rangeToMinutes(q.range)
|
|
const rangeEndMs = Date.now()
|
|
const rangeStartMs = rangeEndMs - minutes * 60_000
|
|
return reply.send({ users: await buildUserTrafficList(rangeStartMs, rangeEndMs) })
|
|
})
|
|
|
|
app.get("/traffic/users/:id", async (req, reply) => {
|
|
const p = req.params as { id?: string }
|
|
const q = req.query as { range?: string }
|
|
const id = String(p.id ?? "")
|
|
if (!id) return reply.status(400).send({ error: "id is required" })
|
|
const minutes = rangeToMinutes(q.range)
|
|
const rangeEndMs = Date.now()
|
|
const rangeStartMs = rangeEndMs - minutes * 60_000
|
|
const users = await buildUserTrafficList(rangeStartMs, rangeEndMs)
|
|
const user = users.find((u) => u.id === id)
|
|
if (!user) return reply.status(404).send({ error: "Пользователь не найден" })
|
|
return reply.send({ user })
|
|
})
|
|
|
|
app.get("/traffic/bound-interfaces", async (req, reply) => {
|
|
const q = req.query as { range?: string }
|
|
const minutes = rangeToMinutes(q.range)
|
|
const rangeEndMs = Date.now()
|
|
const rangeStartMs = rangeEndMs - minutes * 60_000
|
|
return reply.send({ interfaces: await buildBoundInterfaceTraffic(rangeStartMs, rangeEndMs) })
|
|
})
|
|
}
|
|
|
|
export default trafficRoutes
|