36 lines
2.1 KiB
TypeScript
36 lines
2.1 KiB
TypeScript
import { rateBpsFromDelta } from "./traffic-rate.js"
|
|
export function nativeTrafficCounterIdentity(updatedAt: string | Date, nativeId: unknown): string | null {
|
|
const at = updatedAt instanceof Date ? updatedAt.getTime() : Date.parse(updatedAt)
|
|
if (!Number.isFinite(at) || typeof nativeId !== "string" || !/^\*[0-9a-f]+$/i.test(nativeId)) return null
|
|
return JSON.stringify([new Date(at).toISOString(), nativeId.toUpperCase()])
|
|
}
|
|
export function parseTrafficFlag(raw: unknown): boolean {
|
|
if (raw === true || raw === "true" || raw === "yes") return true
|
|
if (raw === false || raw === "false" || raw === "no") return false
|
|
throw new Error("RouterOS вернул неизвестное состояние интерфейса")
|
|
}
|
|
|
|
/** RouterOS byte counters must be exact nonnegative integers, never fallback zero. */
|
|
export function parseTrafficCounter(raw: unknown): number {
|
|
if (typeof raw !== "number" && (typeof raw !== "string" || !/^\d+$/.test(raw))) {
|
|
throw new Error("RouterOS вернул некорректный счётчик трафика")
|
|
}
|
|
const n = Number(raw)
|
|
if (!Number.isSafeInteger(n) || n < 0) throw new Error("RouterOS вернул некорректный счётчик трафика")
|
|
return n
|
|
}
|
|
|
|
export function observedTrafficRate(
|
|
previous: { rxBytes: number; txBytes: number; sampledAt: string } | undefined,
|
|
rxBytes: number, txBytes: number, nowMs: number, maxIntervalMs = Infinity,
|
|
): { rxBps: number; txBps: number; measured: boolean } {
|
|
const prevMs = previous ? Date.parse(previous.sampledAt) : NaN
|
|
if (!previous || nowMs - prevMs > maxIntervalMs || ![previous.rxBytes, previous.txBytes, rxBytes, txBytes].every(v => Number.isSafeInteger(v) && v >= 0)) {
|
|
return { rxBps: 0, txBps: 0, measured: false }
|
|
}
|
|
const rx = previous ? rateBpsFromDelta(previous.rxBytes, rxBytes, prevMs, nowMs) : null
|
|
const tx = previous ? rateBpsFromDelta(previous.txBytes, txBytes, prevMs, nowMs) : null
|
|
// Stored rates retain the legacy numeric shape; observed totals require both deltas.
|
|
return { rxBps: rx ?? 0, txBps: tx ?? 0, measured: rx !== null && tx !== null }
|
|
}
|