Files
nmon/web/e2e/mock/api.ts
Vibe Coder 26fdcdc124
Some checks failed
ci / lint (push) Successful in 1m25s
ci / openapi (push) Successful in 29s
ci / postgres (push) Successful in 3m32s
ci / test (push) Failing after 17m53s
Match LibreNMS port graphs: totals, max, aggregate 95th, compare, utilisation
Operators coming from LibreNMS expect the same figures under a port
graph. Add them:

- Totals: bytes transferred in and out over the selected range
  (GraphResponse.totals), integrated from the average rate across the
  stitched raw and hourly tiers without double counting; partial
  coverage is flagged.
- Summaries read Now / Avg / Max / 95th / Total per direction, plus an
  aggregate (in+out) 95th (p95.aggregate_bps, hot store only).
- Utilisation as a percentage of port speed, and a "% of speed" axis.
- "Compare previous period" overlay on the graph view and expanded row.
- Errors and discards graphs (GET /api/v1/graph/counters), hot-store
  range only since they have no rollups. Packet and broadcast/multicast
  graphs stay disabled: those counters are not polled (DEVIATIONS 56).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017TuKgyKve2XLFtrrXWMi2w
2026-10-25 21:02:32 +00:00

361 lines
17 KiB
TypeScript

// Mock nmon API for Playwright: serves the contract shapes from e2e/fixtures and
// synthesises graphs deterministically from traffic.ts. Nothing here is a hand-written
// API type: every shape is checked against the generated schema.
import { readFileSync, readdirSync } from 'node:fs'
import path from 'node:path'
import type { Page } from '@playwright/test'
import type { components } from '../../src/api/schema.d.ts'
import { AlertDownStore } from './alertDown.ts'
import { AlertStore } from './alerts.ts'
import { GroupStore } from './groups.ts'
import { MgmtStore } from './mgmt.ts'
import { PollToolsMock } from './pollTools.ts'
import { M6Store, type M6Options } from './m6.ts'
import { SetupMock, type SetupMode } from './setup.ts'
import { OpsStore } from './ops.ts'
import { PolicyStore } from './policies.ts'
import { route as profileRoute, withProfileInfo } from './profiles.ts'
import { bgpRoute } from './bgp.ts'
import { buildCounterGraph } from './counters.ts'
import { L2Mock } from './l2.ts'
import { extraSlug, extraViews, metricsRoute } from './metrics.ts'
import { NOW, profileFor, rateAt, rnd, type Profile } from './traffic.ts'
type S = components['schemas']
const fx = path.join(import.meta.dirname, '..', 'fixtures')
const readJson = (f: string): unknown => JSON.parse(readFileSync(path.join(fx, f), 'utf8'))
const devices = readJson('devices.json') as S['DeviceSummary'][]
const views = new Map<string, S['DeviceView']>(
readdirSync(path.join(fx, 'devices'))
.filter((f) => f.endsWith('.json'))
.map((f) => readJson(path.join('devices', f)) as S['DeviceView'])
.map((d) => [d.slug, d]),
)
for (const extra of extraViews(structuredClone(views.get(slugOfNameEarly('yyz1-acc01')) as S['DeviceView']))) views.set(extra.slug, extra)
for (const dev of views.values()) withProfileInfo(dev)
function slugOfNameEarly(name: string): string {
const d = devices.find((x) => x.name === name)
if (!d) throw new Error(`fixture device ${name} not found`)
return d.slug
}
/** Operator-owned port descriptions (device/ifname), so the Description column and its search have data. */
const DESCRIPTIONS: Record<string, string> = {
'yyz1-core1/xe-0/0/1': 'Uplink to yul1-core1, circuit YYZ-YUL-0042',
'yyz1-acc01/Gi1/0/2': 'Lakeshore Clinic, circuit LKSH-4412, patch panel B7',
'yyz1-acc01/Gi1/0/3': 'Contoso transit, circuit CTSO-0098',
}
for (const dev of views.values()) {
for (const iface of dev.interfaces) iface.description = DESCRIPTIONS[`${dev.name}/${iface.ifname}`] ?? ''
}
const health = readJson('poller-health.json') as S['PollerHealth']
const facets = readJson('facets.json') as S['DeviceFacets']
const meta = readJson('meta.json') as S['Meta']
interface IfaceRef {
iface: S['InterfaceView']
dev: S['DeviceView']
profile: Profile
}
const byId = new Map<string, IfaceRef>()
for (const dev of views.values()) {
for (const iface of dev.interfaces) {
const speed = iface.ifhighspeed * 1e6
byId.set(iface.id, { iface, dev, profile: profileFor(iface.id, speed, iface.oper_status === 1 && iface.admin_status === 1 && dev.reachability !== 'down') })
}
}
/** Slug of a fixture device by its name (slugs are name + 4 base32 chars). */
export function slugOfName(name: string): string {
const d = devices.find((x) => x.name === name)
if (!d) throw new Error(`fixture device ${name} not found`)
return d.slug
}
export const allInterfaces = () => [...byId.values()]
const HOT_SECONDS = 31 * 86400
const LONG_COVERAGE = 120 * 86400
const isoZ = (t: number) => new Date(t * 1000).toISOString().replace('.000Z', 'Z')
type Pt = [number, number | null]
function p95(v: (number | null)[]): number | null {
const a = v.filter((x): x is number => x != null).sort((x, y) => x - y)
return a.length ? (a[Math.max(0, Math.ceil(0.95 * a.length) - 1)] as number) : null
}
/** 95th percentile of in+out over the samples where both directions have a value. */
function aggregateP95(inS: Pt[], outS: Pt[]): number | null {
return p95(
inS.map((p, i) => {
const o = outS[i]?.[1]
return p[1] == null || o == null ? null : p[1] + o
}),
)
}
function p95Of(inS: Pt[], outS: Pt[], coverage: number, month: string | undefined): S['GraphP95'] {
const materialised = !!month && month < isoZ(NOW).slice(0, 7)
return {
in_bps: p95(inS.map((p) => p[1])),
out_bps: p95(outS.map((p) => p[1])),
source: materialised ? 'materialised' : 'live',
coverage: Math.min(1, coverage),
partial: coverage < 0.9,
aggregate_bps: aggregateP95(inS, outS) ?? undefined,
...(month && { month }),
}
}
const partialSpans = (stitched: boolean, from: number) => (stitched && from < NOW - LONG_COVERAGE ? [{ from: isoZ(from), to: isoZ(NOW - LONG_COVERAGE) }] : [])
function unreliableGraph(head: Pick<S['GraphResponse'], 'iface'>, ref: IfaceRef, step: number): S['GraphResponse'] {
const mb = ref.iface.ifhighspeed
return {
...head,
step_seconds: step,
tier: 'raw',
partial: [],
unreliable: true,
unreliable_reason: `32-bit counters: not trustworthy at ${mb >= 1000 ? `${mb / 1000} Gb/s` : `${mb} Mb/s`}. They wrap too fast to compute a reliable rate; enable 64-bit (ifHC*) counters on the device.`,
series: { in: [], out: [] },
}
}
interface SeriesPlan {
dataFrom: number
end: number
stepS: number
rawStep: number
stitched: boolean
stitchedAt: number
}
function synthSeries(id: string, profile: Profile, plan: SeriesPlan) {
const { dataFrom, end, stepS, rawStep, stitched, stitchedAt } = plan
const inS: Pt[] = []
const outS: Pt[] = []
const inMax: Pt[] = []
const outMax: Pt[] = []
const first = Math.ceil(dataFrom / stepS) * stepS
for (let t = first; t <= end; t += stitched && t >= stitchedAt ? rawStep : stepS) {
const [i, o] = rateAt(id, profile, t + stepS / 2 > NOW ? t : t + stepS / 2)
const k = 1.12 + rnd(id, Math.floor(t / stepS) + 500) * 0.35
inS.push([t, i])
outS.push([t, o])
inMax.push([t, i == null ? null : i * k])
outMax.push([t, o == null ? null : o * k])
}
return { inS, outS, inMax, outMax }
}
/** Bytes over the series: each point stands for the step it sits on (the mock's tiers are 3600 s, then 300 s). */
function totalsOf(inS: Pt[], outS: Pt[], from: number, to: number, stepAt: (t: number) => number): S['GraphTotals'] {
const sum = (a: Pt[]) => a.reduce((acc, [t, v]) => (v == null ? acc : acc + (v * stepAt(t)) / 8), 0)
const covered = inS.reduce((acc, [t, v]) => (v == null ? acc : acc + stepAt(t)), 0)
return { in_bytes: sum(inS), out_bytes: sum(outS), covered_seconds: Math.min(covered, to - from), range_seconds: to - from }
}
export function buildGraph(id: string, from: number, to: number, step: number, opts: { p95?: boolean; month?: string } = {}): S['GraphResponse'] | null {
const ref = byId.get(id)
if (!ref) return null
const head = {
iface: { id, ifname: ref.iface.ifname, ifalias: ref.iface.ifalias, speed_bps: ref.iface.ifhighspeed * 1e6, device: { slug: ref.dev.slug, name: ref.dev.name } },
}
if (ref.iface.unreliable) return unreliableGraph(head, ref, step)
const end = Math.min(to, NOW)
const range = to - from
const stitched = range > HOT_SECONDS
const stepS = stitched ? 3600 : step
const rawStep = 300
const stitchedAt = Math.floor((NOW - HOT_SECONDS) / 3600) * 3600
const dataFrom = stitched ? Math.max(from, NOW - LONG_COVERAGE) : from
const { inS, outS, inMax, outMax } = synthSeries(id, ref.profile, { dataFrom, end, stepS, rawStep, stitched, stitchedAt })
const g: S['GraphResponse'] = {
...head,
step_seconds: stitched ? rawStep : stepS,
tier: stitched ? '1h' : 'raw',
tiers: stitched
? [
{ from: isoZ(dataFrom), to: isoZ(stitchedAt), tier: '1h', step_seconds: 3600 },
{ from: isoZ(stitchedAt), to: isoZ(end), tier: 'raw', step_seconds: rawStep },
]
: [{ from: isoZ(dataFrom), to: isoZ(end), tier: 'raw', step_seconds: stepS }],
partial: partialSpans(stitched, from),
unreliable: false,
series: { in: inS, out: outS, in_max: inMax, out_max: outMax },
...(opts.p95 && { p95: p95Of(inS, outS, (end - dataFrom) / Math.max(1, to - from), opts.month) }),
}
if (stitched) g.stitched_at = isoZ(stitchedAt)
g.totals = totalsOf(inS, outS, from, to, (t) => (stitched && t < stitchedAt ? 3600 : stitched ? rawStep : stepS))
return g
}
const problem = (status: number, title: string, detail: string) => ({ type: 'about:blank', title, status, detail })
export interface MockOptions extends M6Options {
/** The first-install wizard: 'install' puts the server in install mode (default: set up long ago). */
setup?: SetupMode
latencyMs?: number
/** Overrides a fixture device's reachability by name (used by the M4 alert scenarios). */
reach?: Record<string, S['DeviceSummary']['reachability']>
}
const ifaceIdOf = (device: string, ifname: string): string => {
const r = allInterfaces().find((x) => x.dev.name === device && x.iface.ifname === ifname)
if (!r) throw new Error(`fixture interface ${device}/${ifname} not found`)
return r.iface.id
}
function filterDevices(devs: S['DeviceSummary'][], q: URLSearchParams): S['DeviceSummary'][] {
const term = (q.get('q') ?? '').toLowerCase()
return devs
.filter((d) => !q.get('site') || d.site === q.get('site'))
.filter((d) => !q.get('role') || d.role === q.get('role'))
.filter((d) => !q.get('kind') || d.kind === q.get('kind'))
.filter((d) => !q.get('state') || d.reachability === q.get('state'))
.filter((d) => !term || d.name.toLowerCase().includes(term) || d.mgmt_ip.includes(term) || d.profile.includes(term))
.sort((a, b) => a.name.localeCompare(b.name))
}
function setup(opts: MockOptions) {
const reach = opts.reach ?? {}
const withReach = <T extends { name: string; reachability: S['DeviceSummary']['reachability'] }>(v: T): T => ({ ...v, reachability: reach[v.name] ?? v.reachability })
const name = (s: string) => devices.find((d) => d.slug === s)?.name
const store = new AlertStore({ slug: slugOfName, name, iface: ifaceIdOf })
const groups = new GroupStore({
slug: slugOfName,
iface: ifaceIdOf,
info: (id) => {
const r = byId.get(id)
return r && { id, ifname: r.iface.ifname, ifalias: r.iface.ifalias, device: { slug: r.dev.slug, name: r.dev.name } }
},
series: (id, from, to, step) => buildGraph(id, from, to, step)?.series ?? null,
})
const ops = new OpsStore({ slug: slugOfName, name }, opts.apiTokens)
const m6 = new M6Store(opts, name)
const mgmt = new MgmtStore({
base: (slug) => views.get(slug),
template: () => structuredClone(views.get(slugOfName('yyz1-acc01')) as S['DeviceView']),
retiredCandidate: () => ({ slug: slugOfName('ott1-ups1'), name: 'ott1-ups1' }),
})
const policies = new PolicyStore()
const poll = new PollToolsMock()
const l2 = new L2Mock({
slug: slugOfName,
name,
iface: ifaceIdOf,
ifaceInfo: (id) => {
const r = byId.get(id)
return r && { device: r.dev.name, ifname: r.iface.ifname }
},
})
const alertDown = new AlertDownStore(
(id) => groups.alertDownVia(id),
(slug) => views.get(slug)?.interfaces.filter((i) => !i.retired_at).map((i) => i.id),
(id) => byId.has(id),
)
const wizard = new SetupMock(opts.setup, () => structuredClone(views.get(slugOfName('yyz1-acc01')) as S['DeviceView']))
return { wizard, latency: opts.latencyMs ?? 8, devs: devices.map((d) => withReach(d)), withReach, store, groups, ops, m6, mgmt, alertDown, policies, l2, poll }
}
type Ctx = ReturnType<typeof setup>
type Reply = { status: number; body: unknown }
const ok = (body: unknown): Reply => ({ status: 200, body })
const notFound = (detail: string): Reply => ({ status: 404, body: problem(404, 'Not Found', detail) })
function interfaceHits(q: URLSearchParams): S['InterfaceHit'][] {
const term = (q.get('q') ?? '').toLowerCase()
return allInterfaces()
.filter(({ iface }) => !iface.retired_at)
.filter(({ iface }) => term && [iface.ifname, iface.ifalias, iface.description].some((f) => f.toLowerCase().includes(term)))
.sort((a, b) => a.dev.name.localeCompare(b.dev.name) || a.iface.ifindex - b.iface.ifindex)
.map(({ iface, dev }) => ({
id: iface.id,
device: { slug: dev.slug, name: dev.name },
ifname: iface.ifname,
ifalias: iface.ifalias,
description: iface.description,
ifdescr: iface.ifdescr,
oper_status: iface.oper_status,
admin_status: iface.admin_status,
speed_bps: iface.ifhighspeed * 1e6,
in_bps: iface.in_bps,
out_bps: iface.out_bps,
alert_down: false,
alert_down_effective: false,
alert_down_via: '',
}))
}
function graphReply(q: URLSearchParams): Reply {
const id = q.get('iface') ?? ''
const to = q.get('to') ? Date.parse(q.get('to') as string) / 1000 : NOW
const from = q.get('from') ? Date.parse(q.get('from') as string) / 1000 : to - 86400
const step = Number(q.get('step')) > 0 ? Number(q.get('step')) : 60
const g = buildGraph(id, from, to, step, { p95: q.get('p95') === 'true', month: q.get('month') ?? undefined })
return g ? ok(g) : notFound(`interface "${id}" does not exist`)
}
function counterReply(q: URLSearchParams): Reply {
const id = q.get('iface') ?? ''
const ref = byId.get(id)
const kind = q.get('kind') === 'discards' ? 'discards' : 'errors'
const to = q.get('to') ? Date.parse(q.get('to') as string) / 1000 : NOW
const from = q.get('from') ? Date.parse(q.get('from') as string) / 1000 : to - 3600
const step = Number(q.get('step')) > 0 ? Number(q.get('step')) : 60
if (!ref) return notFound(`interface "${id}" does not exist`)
const iface = { id, ifname: ref.iface.ifname, ifalias: ref.iface.ifalias, speed_bps: ref.iface.ifhighspeed * 1e6, device: { slug: ref.dev.slug, name: ref.dev.name } }
return ok(buildCounterGraph(iface, kind, from, to, step))
}
function deviceReply(c: Ctx, slug: string): Reply {
const v = views.get(slug)
if (!v || c.m6.isPurged(slug)) return notFound(`device "${slug}" does not exist`)
const days = c.m6.retiredDays(v.name)
const retired = days === undefined ? {} : { retired_at: isoZ(NOW - days * 86400) }
return ok(c.alertDown.overlayDevice({ ...c.withReach(v), ...retired, checks: c.ops.checksFor(v.slug) }))
}
/** The read-only fixture endpoints; undefined when `p` is not one of them. */
function readReply(c: Ctx, p: string, q: URLSearchParams, paged: (items: unknown[]) => unknown): Reply | undefined {
if (p === '/meta') return ok(meta)
if (p === '/devices/facets') return ok(facets)
if (p === '/devices') return ok(paged(filterDevices(c.devs, q)))
const dm = /^\/devices\/([^/]+)$/.exec(p)
if (dm) return deviceReply(c, decodeURIComponent(dm[1] as string))
if (p === '/interfaces') return ok(paged(c.alertDown.overlayHits(interfaceHits(q))))
if (p === '/graph') return graphReply(q)
if (p === '/graph/counters') return counterReply(q)
if (p === '/poller/health') return ok(health)
return undefined
}
function reply(c: Ctx, method: string, p: string, q: URLSearchParams, body: () => unknown): Reply {
const num = (k: string, d: number) => {
const n = Number(q.get(k))
return Number.isFinite(n) && n > 0 ? n : d
}
const paged = (items: unknown[]) => {
const per = Math.min(1000, num('per_page', 100))
const page = num('page', 1)
return { items: items.slice((page - 1) * per, page * per), page, per_page: per, total: items.length }
}
return metricsRoute(method, p, q) ?? c.l2.route(method, p, q) ?? bgpRoute(method, p, q, extraSlug) ?? profileRoute(method, p) ?? c.alertDown.route(method, p, body) ?? c.policies.route(method, p, body) ?? c.mgmt.route(method, p, body) ?? c.poll.route(method, p, q, body) ?? readReply(c, p, q, paged) ?? c.store.route(method, p, q, paged, body) ?? c.groups.route(method, p, q, body) ?? c.ops.route(method, p, body) ?? notFound(`no mock for ${p}`)
}
/** Routes every /api/v1 call of `page` to the fixtures. */
export async function installMockApi(page: Page, opts: MockOptions = {}) {
const c = setup(opts)
await c.m6.install(page)
await page.route('**/api/v1/**', async (route) => {
const req = route.request()
const url = new URL(req.url())
const p = url.pathname.replace(/^\/api\/v1/, '')
const header = (n: string) => req.headers()[n]
const body = { json: () => req.postDataJSON() as unknown, raw: () => req.postData() ?? '' }
// In install mode nobody is signed in: the wizard's routes run without the session guard (no CSRF, no role).
const r = c.wizard.route(req.method(), p, body.json) ?? (c.wizard.open ? undefined : c.m6.guard(req.method(), p, header)) ?? c.m6.route(req.method(), p, body) ?? reply(c, req.method(), p, url.searchParams, body.json)
if (c.latency) await new Promise((res) => setTimeout(res, c.latency))
await route.fulfill({ status: r.status, contentType: r.status >= 400 ? 'application/problem+json' : 'application/json', body: JSON.stringify(r.body) })
})
}