feat(traffic, users): enhance interface and peer management features
Docker images / prepare-release (push) Successful in 7s
Docker images / backend-image (push) Successful in 1m37s
Docker images / frontend-image (push) Successful in 2m44s
Docker images / notify-webhook (push) Skipped
Docker images / updater-image (push) Successful in 40s
Docker images / publish-release (push) Successful in 10s

Added support for managing peer information in interface bindings, including new fields for peerPublicKey and peerName in the BoundIfaceTraffic interface. Updated the database schema to include these fields in user_interface_bindings and traffic_samples tables. Enhanced the UI components to display peer details alongside interface names, improving user experience and clarity in the traffic management system. Updated relevant functions and services to handle peer-specific logic, ensuring robust integration across the application.
This commit is contained in:
Denozordec committed 2026-09-06 20:45:37 +07:00
1 parent fc161506e7
commit 5884bd8873
19 files changed
+749 -134

No files matched your search

+69 -9
View File
@@ -16,6 +16,38 @@ interface RosIfaceTraffic {
"tx-bits-per-second"?: string
}
interface RosWgPeerTraffic {
interface?: string
name?: string
comment?: string
"public-key"?: string
rx?: string
tx?: string
disabled?: string
}
function waveKey(interfaceName: string, peerPublicKey = ""): string {
return `${interfaceName}\0${peerPublicKey}`
}
function sampleRate(
prevWave: Map<string, { rxBytes: number; txBytes: number; sampledAt: string }>,
key: string,
rxBytes: number,
txBytes: number,
nowMs: number,
): { rxBps: number; txBps: number } {
const prev = prevWave.get(key)
const prevMs = prev ? Date.parse(prev.sampledAt) : NaN
const rxBps = prev && Number.isFinite(prevMs)
? (rateBpsFromDelta(prev.rxBytes, rxBytes, prevMs, nowMs) ?? 0)
: 0
const txBps = prev && Number.isFinite(prevMs)
? (rateBpsFromDelta(prev.txBytes, txBytes, prevMs, nowMs) ?? 0)
: 0
return { rxBps, txBps }
}
export interface TrafficCollectorState {
running: boolean
lastRunAt: string | null
@@ -63,6 +95,7 @@ function readPreviousWave(serverId: number): Map<string, { rxBytes: number; txBy
const rows = db
.select({
interfaceName: trafficSamples.interfaceName,
peerPublicKey: trafficSamples.peerPublicKey,
rxBytes: trafficSamples.rxBytes,
txBytes: trafficSamples.txBytes,
sampledAt: trafficSamples.sampledAt,
@@ -73,7 +106,7 @@ function readPreviousWave(serverId: number): Map<string, { rxBytes: number; txBy
eq(trafficSamples.sampledAt, last.sampledAt),
))
.all()
return new Map(rows.map((r) => [r.interfaceName, r]))
return new Map(rows.map((r) => [`${r.interfaceName}\0${r.peerPublicKey ?? ""}`, r]))
}
export async function collectTrafficOnce(): Promise<TrafficRunSnapshot> {
@@ -116,14 +149,7 @@ export async function collectTrafficOnce(): Promise<TrafficRunSnapshot> {
const txBytes = toNum(i["tx-byte"])
const running = (i.running ?? "false") === "true"
const disabled = (i.disabled ?? "false") === "true"
const prev = prevWave.get(interfaceName)
const prevMs = prev ? Date.parse(prev.sampledAt) : NaN
const rxBps = prev && Number.isFinite(prevMs)
? (rateBpsFromDelta(prev.rxBytes, rxBytes, prevMs, nowMs) ?? 0)
: 0
const txBps = prev && Number.isFinite(prevMs)
? (rateBpsFromDelta(prev.txBytes, txBytes, prevMs, nowMs) ?? 0)
: 0
const { rxBps, txBps } = sampleRate(prevWave, waveKey(interfaceName), rxBytes, txBytes, nowMs)
if (shouldIncludeIface(interfaceName, running, disabled)) {
sumRxMbps += bpsToMbps(rxBps)
sumTxMbps += bpsToMbps(txBps)
@@ -131,6 +157,7 @@ export async function collectTrafficOnce(): Promise<TrafficRunSnapshot> {
return {
serverId: srv.id,
interfaceName,
peerPublicKey: "",
sampledAt: now,
rxBytes,
txBytes,
@@ -140,6 +167,39 @@ export async function collectTrafficOnce(): Promise<TrafficRunSnapshot> {
disabled,
}
})
try {
const peers = await client.get<RosWgPeerTraffic[]>("/interface/wireguard/peers")
for (const p of peers) {
const interfaceName = (p.interface ?? "").trim()
const peerPublicKey = (p["public-key"] ?? "").trim()
if (!interfaceName || !peerPublicKey) continue
const rxBytes = toNum(p.rx)
const txBytes = toNum(p.tx)
const disabled = (p.disabled ?? "false") === "true" || p.disabled === "yes"
const running = !disabled
const { rxBps, txBps } = sampleRate(
prevWave,
waveKey(interfaceName, peerPublicKey),
rxBytes,
txBytes,
nowMs,
)
rows.push({
serverId: srv.id,
interfaceName,
peerPublicKey,
sampledAt: now,
rxBytes,
txBytes,
rxBps,
txBps,
running,
disabled,
})
}
} catch {
/* WG peers optional — iface samples already recorded */
}
if (rows.length > 0) {
db.insert(trafficSamples).values(rows).run()
}
+25
View File
@@ -97,4 +97,29 @@ const listed = buildTrafficFromSamples([...samples, ...wgSamples], start, end, [
assert.equal(userAgg.rxNow, listed.rxNow, "сумма привязанных ifaces = фильтр по списку имён")
assert.ok(userAgg.rxNow > built.rxNow, "агрегация пользователя больше одного iface")
const peerA: TrafficSampleLike[] = [
{ interfaceName: "wg-server", peerPublicKey: "peer-a", sampledAt: t0, rxBytes: 1_000_000, txBytes: 100_000, rxBps: 0, txBps: 0, running: true, disabled: false },
{ interfaceName: "wg-server", peerPublicKey: "peer-a", sampledAt: t1, rxBytes: 1_000_000 + 3_750_000, txBytes: 100_000 + 375_000, rxBps: 0, txBps: 0, running: true, disabled: false },
]
const peerB: TrafficSampleLike[] = [
{ interfaceName: "wg-server", peerPublicKey: "peer-b", sampledAt: t0, rxBytes: 500_000, txBytes: 50_000, rxBps: 0, txBps: 0, running: true, disabled: false },
{ interfaceName: "wg-server", peerPublicKey: "peer-b", sampledAt: t1, rxBytes: 500_000 + 1_875_000, txBytes: 50_000 + 187_500, rxBps: 0, txBps: 0, running: true, disabled: false },
]
const ifaceWg: TrafficSampleLike[] = [
{ interfaceName: "wg-server", sampledAt: t0, rxBytes: 10_000_000, txBytes: 2_000_000, rxBps: 0, txBps: 0, running: true, disabled: false },
{ interfaceName: "wg-server", sampledAt: t1, rxBytes: 10_000_000 + 7_500_000, txBytes: 2_000_000 + 750_000, rxBps: 0, txBps: 0, running: true, disabled: false },
]
const mixed = [...peerA, ...peerB, ...ifaceWg]
const rateA = buildTrafficFromSamples(mixed, start, end, "wg-server", "peer-a")
const rateB = buildTrafficFromSamples(mixed, start, end, "wg-server", "peer-b")
const rateIface = buildTrafficFromSamples(mixed, start, end, "wg-server")
assert.ok(rateA.rxNow > 0 && rateB.rxNow > 0, "скорость по каждому пиру")
assert.notEqual(rateA.rxNow, rateB.rxNow, "два пира одного iface — разный rate")
assert.ok(rateIface.rxNow > rateA.rxNow, "iface-level не суммирует пиров")
assert.equal(
buildTrafficFromSamples(mixed, start, end).rxNow,
rateIface.rxNow,
"режим сервера игнорирует семплы пиров",
)
console.log("traffic-rate tests ok")
+19 -4
View File
@@ -4,6 +4,7 @@ export const SERIES_POINTS = 60
export interface TrafficSampleLike {
interfaceName: string
peerPublicKey?: string
sampledAt: string
rxBytes: number
txBytes: number
@@ -94,11 +95,16 @@ function parseIsoMs(iso: string): number {
return Number.isFinite(t) ? t : 0
}
export function sampleSeriesKey(interfaceName: string, peerPublicKey = ""): string {
return `${interfaceName}\0${peerPublicKey}`
}
export function buildTrafficFromSamples(
rows: TrafficSampleLike[],
rangeStartMs: number,
rangeEndMs: number,
onlyInterface?: string | readonly string[],
peerPublicKey?: string,
): BuiltTrafficSeries {
const empty: BuiltTrafficSeries = {
rxNow: 0,
@@ -113,11 +119,12 @@ export function buildTrafficFromSamples(
}
if (rows.length === 0) return empty
const byIface = new Map<string, TrafficSampleLike[]>()
const bySeries = new Map<string, TrafficSampleLike[]>()
for (const r of rows) {
const arr = byIface.get(r.interfaceName) ?? []
const peer = r.peerPublicKey ?? ""
const arr = bySeries.get(sampleSeriesKey(r.interfaceName, peer)) ?? []
arr.push(r)
byIface.set(r.interfaceName, arr)
bySeries.set(sampleSeriesKey(r.interfaceName, peer), arr)
}
const allowList = Array.isArray(onlyInterface)
@@ -132,12 +139,20 @@ export function buildTrafficFromSamples(
let txBytesDelta = 0
let sessions = 0
for (const [name, arr] of byIface) {
for (const [key, arr] of bySeries) {
const sep = key.indexOf("\0")
const name = sep >= 0 ? key.slice(0, sep) : key
const peer = sep >= 0 ? key.slice(sep + 1) : ""
if (allowList) {
if (!allowList.includes(name)) continue
} else if (isLoopbackName(name)) {
continue
}
if (peerPublicKey === undefined) {
if (peer !== "") continue
} else if (peer !== peerPublicKey) {
continue
}
const sorted = [...arr].sort((a, b) => a.sampledAt.localeCompare(b.sampledAt))
const last = sorted[sorted.length - 1]
+11 -19
View File
@@ -17,6 +17,8 @@ export interface BoundIfaceTrafficDto {
userName: string
interfaceName: string
interfaceType: string
peerPublicKey: string
peerName: string
comment: string
serverId: string
serverName: string
@@ -77,22 +79,6 @@ export function buildUserTrafficList(rangeStartMs: number, rangeEndMs: number):
return users.map((user) => {
const parts: BuiltTrafficSeries[] = []
const interfaces: BoundIfaceTrafficDto[] = []
const byServer = new Map<number, string[]>()
for (const b of user.bindings) {
const arr = byServer.get(b.serverId) ?? []
arr.push(b.interfaceName)
byServer.set(b.serverId, arr)
}
for (const [serverId, names] of byServer) {
let rows = sampleCache.get(serverId)
if (!rows) {
rows = readServerSamplesInRange(serverId, sinceIso)
sampleCache.set(serverId, rows)
}
const built = buildTrafficFromSamples(rows, rangeStartMs, rangeEndMs, names)
parts.push(built)
}
for (const b of user.bindings) {
let rows = sampleCache.get(b.serverId)
@@ -100,19 +86,25 @@ export function buildUserTrafficList(rangeStartMs: number, rangeEndMs: number):
rows = readServerSamplesInRange(b.serverId, sinceIso)
sampleCache.set(b.serverId, rows)
}
const built = buildTrafficFromSamples(rows, rangeStartMs, rangeEndMs, b.interfaceName)
const last = [...rows.filter((r) => r.interfaceName === b.interfaceName)]
const peerKey = b.peerPublicKey ?? ""
const built = buildTrafficFromSamples(rows, rangeStartMs, rangeEndMs, b.interfaceName, peerKey)
parts.push(built)
const last = [...rows.filter((r) =>
r.interfaceName === b.interfaceName && (r.peerPublicKey ?? "") === peerKey,
)]
.sort((a, c) => a.sampledAt.localeCompare(c.sampledAt))
.at(-1)
const running = Boolean(last?.running) && !last?.disabled
interfaces.push({
id: `${b.userId}:${b.serverId}:${b.interfaceName}`,
id: `${b.userId}:${b.serverId}:${b.interfaceName}:${peerKey || "_iface"}`,
bindingId: b.id,
userId: user.id,
userLogin: user.login,
userName: user.name,
interfaceName: b.interfaceName,
interfaceType: b.interfaceType,
peerPublicKey: peerKey,
peerName: b.peerName ?? "",
comment: b.comment,
serverId: String(b.serverId),
serverName: b.serverName,
+47
View File
@@ -211,4 +211,51 @@ export function getEnabledServerById(serverId: string | number): ServerRow | nul
return db.select().from(servers).where(eq(servers.id, id)).limit(1).all()[0] ?? null
}
export type CatalogWgPeer = {
interfaceName: string
publicKey: string
name: string
comment: string
allowedIps: string[]
latestHandshake?: string
disabled: boolean
}
const WG_CATALOG_TIMEOUT_MS = 5_000
export async function listWireGuardPeersForCatalog(serverId: number): Promise<{
peers: CatalogWgPeer[]
error?: string
}> {
const row = getEnabledServerById(serverId)
if (!row) return { peers: [], error: "Сервер не найден" }
try {
const client = MikrotikClient.fromServer(row)
const peersRaw = await Promise.race([
client.get<RosWireGuardPeer[]>("/interface/wireguard/peers"),
new Promise<never>((_, reject) => {
setTimeout(() => reject(new Error("Таймаут RouterOS")), WG_CATALOG_TIMEOUT_MS)
}),
])
const peers: CatalogWgPeer[] = peersRaw.flatMap((p, idx) => {
const mapped = mapPeer(p, idx)
const interfaceName = (p.interface ?? "").trim()
const publicKey = mapped.publicKey.trim()
if (!interfaceName || !publicKey) return []
return [{
interfaceName,
publicKey,
name: mapped.name ?? "",
comment: mapped.comment ?? "",
allowedIps: mapped.allowedIps,
latestHandshake: mapped.latestHandshake,
disabled: mapped.disabled === true,
}]
})
return { peers }
} catch (e) {
return { peers: [], error: e instanceof Error ? e.message : String(e) }
}
}
export { type RosWireGuard, type RosWireGuardPeer }