diff --git a/webui/mock/match.ts b/webui/mock/match.ts new file mode 100644 index 0000000..7ff7f70 --- /dev/null +++ b/webui/mock/match.ts @@ -0,0 +1,169 @@ +import { WINDOW_HOURS, type MockWindow } from './time-shift.ts' + +export interface Fixture { + file: string + path: string + query: Record + status: number +} + +/** Query params that decide which fixture answers; anything else (limit, cache busters) never affects matching. */ +const SIGNIFICANT: Record = { + '/admin/api/usage/series': ['scope', 'metric', 'window', 'span', 'offset'], + '/admin/api/usage/totals': ['kind', 'window', 'span', 'offset', 'metrics', 'group', 'user', 'model', 'target'], + '/admin/api/usage/models': ['metric', 'window', 'span', 'detail'], + '/admin/api/performance': ['kind', 'window', 'span', 'offset', 'series', 'id'], +} + +/** Params naming an entity; a fixture for another entity of the same class stands in when the exact one is missing. */ +const ID_PARAMS: Record = { + '/admin/api/usage/series': ['scope'], + '/admin/api/usage/totals': ['group', 'user', 'model', 'target'], + '/admin/api/performance': ['id'], +} + +/** Metric ratios relative to requests, used only when a series fixture exists for another metric. */ +export const METRIC_PER_REQ: Record = { + req: 1, + tokin: 45_000, + tokout: 600, + cost: 150, + attempt: 1.25, + fail: 0.15, + fover: 0.05, + timeout: 0.03, + r402: 0.002, + rej: 0.004, +} + +export const TOTALS_METRICS = ['req', 'tokin', 'tokout', 'cost'] + +export type NormQuery = Record + +export function normaliseQuery(path: string, query: URLSearchParams | Record): NormQuery { + const keys = SIGNIFICANT[path] ?? [] + const entries: [string, string][] = + query instanceof URLSearchParams + ? [...query.entries()] + : Object.entries(query).flatMap(([k, v]) => (Array.isArray(v) ? v.map((x): [string, string] => [k, x]) : [[k, v]])) + const out: NormQuery = {} + for (const [k, v] of entries) { + if (!keys.includes(k)) continue + const parts = k === 'metrics' ? v.split(',').filter(Boolean) : [v] + out[k] = [...(out[k] ?? []), ...parts] + } + for (const k of Object.keys(out)) { + out[k] = [...new Set(out[k])].sort() + if (k === 'offset' && out[k].every((x) => Number(x) === 0)) delete out[k] + } + return out +} + +const keyOf = (q: NormQuery) => + Object.keys(q) + .sort() + .map((k) => `${k}=${q[k]!.join(',')}`) + .join('&') + +const scopeClass = (s: string) => (s.includes(':') ? s.slice(0, s.indexOf(':')) : s) + +function classOf(path: string, param: string, values: string[]): string { + if (path === '/admin/api/usage/series' && param === 'scope') return [...new Set(values.map(scopeClass))].sort().join('|') + return '*' +} + +function overlap(a: string[], b: string[]): number { + const set = new Set(b) + return a.filter((x) => set.has(x)).length +} + +/** Exact match on normalised query (key order, repeated-key order and non-significant params ignored), else the fixture for a same-class id. */ +export function matchFixture(manifest: Fixture[], path: string, query: URLSearchParams): Fixture | null { + const cands = manifest.filter((f) => f.path === path) + if (cands.length === 0) return null + const want = normaliseQuery(path, query) + const wantKey = keyOf(want) + const exact = cands.find((f) => keyOf(normaliseQuery(path, f.query)) === wantKey) + if (exact) return exact + const ids = ID_PARAMS[path] ?? [] + let best: Fixture | null = null + let bestScore = -Infinity + for (const f of cands) { + const have = normaliseQuery(path, f.query) + const others = Object.keys({ ...want, ...have }).filter((k) => !ids.includes(k)) + if (others.some((k) => (want[k] ?? []).join(',') !== (have[k] ?? []).join(','))) continue + let score = 0 + let ok = true + for (const k of ids) { + const w = want[k] + const h = have[k] + if (!w !== !h) ok = false + else if (w && h) { + if (classOf(path, k, w) !== classOf(path, k, h)) ok = false + score += overlap(w, h) * 10 - Math.abs(w.length - h.length) + } + } + if (ok && score > bestScore) { + best = f + bestScore = score + } + } + return best +} + +export const hoursOf = (q: NormQuery): number => { + const w = (q.window?.[0] ?? 'day') as MockWindow + return Number(q.span?.[0] ?? 14) * (WINDOW_HOURS[w] ?? 24) +} + +/** Closeness of a fixture's range to the requested one: same window and similar total span score highest. */ +function rangeScore(want: NormQuery, have: NormQuery): number { + const sameWindow = (want.window?.[0] ?? 'day') === (have.window?.[0] ?? 'day') ? 20 : 0 + return sameWindow - Math.abs(Math.log(hoursOf(have) / hoursOf(want))) * 5 +} + +const fixtureMetrics = (q: NormQuery, kind: string | undefined): string[] => + q.metrics ?? (kind === 'targetcaller' ? ['req'] : TOTALS_METRICS) + +/** Closest fixture of any other range, to be rescaled by the caller. Null when nothing is usable. */ +export function nearestFixture(manifest: Fixture[], path: string, query: URLSearchParams): Fixture | null { + const want = normaliseQuery(path, query) + let best: Fixture | null = null + let bestScore = -Infinity + for (const f of manifest) { + if (f.path !== path || f.status !== 200) continue + const have = normaliseQuery(path, f.query) + let score = rangeScore(want, have) + if (path === '/admin/api/usage/series') { + const metric = want.metric?.[0] ?? '' + const same = have.metric?.[0] === metric + if (!same && !(have.metric?.[0] && have.metric[0] in METRIC_PER_REQ && metric in METRIC_PER_REQ)) continue + score += same ? 100 : 0 + const w = want.scope ?? [] + const h = have.scope ?? [] + score += (overlap(w, h) / Math.max(w.length, 1)) * 60 + score += classOf(path, 'scope', w) === classOf(path, 'scope', h) ? 20 : 0 + score -= Math.abs(w.length - h.length) * 0.1 + score += (want.offset?.[0] ?? '0') === (have.offset?.[0] ?? '0') ? 5 : 0 + } else if (path === '/admin/api/usage/totals') { + if (want.kind?.[0] !== have.kind?.[0]) continue + for (const k of ID_PARAMS[path]!) if (!want[k] !== !have[k]) score = -Infinity + if (score === -Infinity) continue + const need = want.metrics ?? fixtureMetrics(want, want.kind?.[0]) + const got = fixtureMetrics(have, have.kind?.[0]) + if (need.some((m) => !got.includes(m))) continue + for (const k of ID_PARAMS[path]!) if (want[k]?.join() === have[k]?.join()) score += 30 + score += need.length === got.length ? 10 : 0 + } else if (path === '/admin/api/usage/models') { + if (!want.detail !== !have.detail) continue + } else if (path === '/admin/api/performance') { + if (want.kind?.[0] !== have.kind?.[0] || !want.series !== !have.series) continue + if (!want.id !== !have.id) continue + } + if (score > bestScore) { + best = f + bestScore = score + } + } + return best +} diff --git a/webui/mock/respond.ts b/webui/mock/respond.ts new file mode 100644 index 0000000..30b659b --- /dev/null +++ b/webui/mock/respond.ts @@ -0,0 +1,113 @@ +import { matchFixture, nearestFixture, normaliseQuery, type Fixture } from './match.ts' +import { applyScenarios, errorEnvelope, scenarioDelayMs } from './scenarios.ts' +import { fitSeriesScopes, synthesise } from './synth.ts' +import { CAPTURE_AT, shiftTimestamps } from './time-shift.ts' + +type Obj = Record // eslint-disable-line @typescript-eslint/no-explicit-any + +export interface RespondInput { + manifest: Fixture[] + readFixture: (file: string) => unknown + path: string + query: URLSearchParams + scenarios: string[] + now: number + rng: () => number +} + +export interface MockResponse { + status: number + body: unknown + delayMs: number +} + +const SERIES = '/admin/api/usage/series' +const MODELS = '/admin/api/usage/models' +const SERIES_SCOPE = /^(model|provider|group|user):.+$|^total$/ +const WINDOWS = ['hour', 'day', 'month'] +const JITTER = 0.15 +const RANGE_TOO_LARGE = 'range too large; narrow span or filter' +/** Spans at which the live API rejects usage/models?detail=1. */ +const DETAIL_MAX_SPAN: Record = { hour: 48, day: 30 } + +const notFound = (message: string) => ({ status: 404, body: errorEnvelope(404, 'invalid_request_error', message) }) + +function validQuery(path: string, query: URLSearchParams): string | null { + const window = query.get('window') + if (window !== null && !WINDOWS.includes(window)) return 'invalid window' + const span = query.get('span') + if (span !== null && !(Number(span) >= 1)) return 'invalid span' + if (path === SERIES) { + const scopes = query.getAll('scope') + if (scopes.length === 0 || scopes.some((s) => !SERIES_SCOPE.test(s))) return 'unknown scope' + } + return null +} + +function limitRows(path: string, query: URLSearchParams, body: Obj): Obj { + const limit = Number(query.get('limit') ?? 0) + if (!(limit > 0)) return body + if (path === '/admin/api/events') return { ...body, events: body.events.slice(0, limit) } + if (path === '/admin/api/usage/totals') return { ...body, rows: body.rows.slice(0, limit) } + if (path === MODELS) return { ...body, models: body.models.slice(0, limit) } + return body +} + +function resolveBase(i: RespondInput): { status: number; body: unknown } { + const { manifest, path, query, now } = i + if (!manifest.some((f) => f.path === path)) return notFound(`unknown admin route ${path}`) + const bad = validQuery(path, query) + if (bad) return notFound(bad) + + const exact = matchFixture(manifest, path, query) + if (exact && exact.status !== 200) return { status: exact.status, body: i.readFixture(exact.file) } + const detail = query.get('detail') + const window = query.get('window') ?? '' + if (path === MODELS && detail && Number(query.get('span')) >= (DETAIL_MAX_SPAN[window] ?? Infinity)) { + return { status: 400, body: errorEnvelope(400, 'invalid_request_error', RANGE_TOO_LARGE) } + } + + const want = normaliseQuery(path, query) + if (exact) { + const have = normaliseQuery(path, exact.query) + const sameRange = ['window', 'span', 'offset', 'metric', 'metrics'].every((k) => (want[k] ?? []).join() === (have[k] ?? []).join()) + if (sameRange) { + let body = shiftTimestamps(i.readFixture(exact.file), CAPTURE_AT, now) as Obj + if (path === SERIES) body = fitSeriesScopes(body, query) + return { status: 200, body: limitRows(path, query, body) } + } + } + const near = exact ?? nearestFixture(manifest, path, query) + if (!near) return notFound('no data for this query') + return { status: 200, body: limitRows(path, query, synthesise(near, i.readFixture(near.file) as Obj, query, now)) } +} + +const wobble = (v: number, rng: () => number, cap?: number) => { + const next = Math.round(v * (1 - JITTER + rng() * 2 * JITTER)) + return cap !== undefined ? Math.min(next, cap) : next +} + +/** Live minute meters move on every call; counters that are zero stay zero. */ +export function jitterMeters(path: string, body: unknown, rng: () => number): unknown { + if (path !== '/admin/api/overview' && path !== '/admin/api/usage') return body + const b = structuredClone(body) as Obj + if (path === '/admin/api/overview') { + for (const p of b.providers ?? []) { + p.attemptsMinute = wobble(p.attemptsMinute, rng) + p.failuresMinute = Math.min(wobble(p.failuresMinute, rng), p.attemptsMinute) + } + } else { + for (const u of b.users ?? []) u.requestsPerMinute = wobble(u.requestsPerMinute, rng, u.limits?.requestsPerMinute || undefined) + for (const g of b.groups ?? []) g.requestsPerMinute = wobble(g.requestsPerMinute, rng) + if (b.total) b.total.requestsPerMinute = wobble(b.total.requestsPerMinute, rng) + } + return b +} + +/** One mock admin API response: fixture or synthesis, then scenarios, then meter jitter. */ +export function respond(i: RespondInput): MockResponse { + const base = resolveBase(i) + const out = applyScenarios(i.scenarios, i.path, base.body, base.status, { now: i.now, rng: i.rng }) + const body = out.status === 200 ? jitterMeters(i.path, out.body, i.rng) : out.body + return { status: out.status, body, delayMs: scenarioDelayMs(i.scenarios) } +} diff --git a/webui/mock/scenarios.ts b/webui/mock/scenarios.ts new file mode 100644 index 0000000..882dde4 --- /dev/null +++ b/webui/mock/scenarios.ts @@ -0,0 +1,297 @@ +type Obj = Record // eslint-disable-line @typescript-eslint/no-explicit-any + +export const SCENARIOS = [ + 'live', + 'breaker-open', + 'redis-down', + 'config-warnings', + 'router-escalations', + 'targets-healthy', + 'stats-disabled', + 'auth-401', + 'auth-403', + 'empty', + 'limits-hot', + 'slow', + 'huge', +] as const + +export type ScenarioName = (typeof SCENARIOS)[number] + +export const SLOW_DELAY_MS = 1500 + +const API = '/admin/api/' +const HISTORY_PATHS = ['/admin/api/usage/series', '/admin/api/usage/totals', '/admin/api/usage/models'] +const LATENCY_KEYS = ['p50Ms', 'p95Ms', 'p99Ms', 'ttfbP50Ms', 'ttfbP95Ms'] +const HOT_USER_IDS = ['user-01', 'user-02', 'user-03'] +const HOT_GROUP = 'friends' +const HOT_MINUTE_FRACTION = 0.93 +const HOT_DAY_FRACTION = 0.9 +const BREAKER_OPEN_MS = 90_000 +const HUGE_FACTOR = 3 + +export interface ScenarioContext { + now: number + rng: () => number +} + +export interface ScenarioResult { + status: number + body: unknown +} + +const ZERO_TIME = '0001-01-01T00:00:00Z' +const BREAKER_PROVIDER = 'alibaba' +const WARNINGS = [ + 'provider "alibaba": baseUrl has no scheme; assuming https', + 'modelAliases: "deepseek" targets a model no provider lists', + 'groups.friends.memberLimits.tokensPerMinute is below requestsPerMinute*1000; pacing may never start', + 'users file lists "user-13" twice; the last entry wins', + 'cache.ttl 5m0s is shorter than the router session ttl; session affinity can miss', +] +const WARNINGS_DROPPED = 3 + +/** Scenario names from `?mock=a,b` in a page URL (Referer) or the x-mock-scenario header; unknown names drop out. */ +export function parseScenarios(referer: string | undefined, header: string | undefined): string[] { + let raw = header ?? '' + if (!raw && referer) { + try { + raw = new URL(referer).searchParams.get('mock') ?? '' + } catch { + raw = '' + } + } + return raw + .split(',') + .map((s) => s.trim()) + .filter((s): s is ScenarioName => (SCENARIOS as readonly string[]).includes(s)) +} + +export function scenarioDelayMs(names: string[]): number { + return names.includes('slow') ? SLOW_DELAY_MS : 0 +} + +export const errorEnvelope = (status: number, type: string, message: string) => ({ + error: { message, type, code: String(status) }, +}) + +const fail = (status: number, type: string, message: string): ScenarioResult => ({ status, body: errorEnvelope(status, type, message) }) + +const iso = (ms: number) => new Date(ms).toISOString() + +function eachRouter(body: Obj, fn: (r: Obj) => void) { + if (Array.isArray(body.routers)) body.routers.forEach(fn) +} + +function pickBreakerProvider(providers: Obj[]): Obj | undefined { + return providers.find((p) => p.name === BREAKER_PROVIDER) ?? providers[0] +} + +function breakerOpen(path: string, body: Obj, ctx: ScenarioContext) { + if (path !== '/admin/api/overview' && path !== '/admin/api/catalog') return + const p = pickBreakerProvider(body.providers ?? []) + if (!p) return + for (const other of body.providers) { + other.healthState = 'closed' + other.openUntil = ZERO_TIME + } + p.healthState = 'open' + p.openUntil = iso(ctx.now + BREAKER_OPEN_MS) + p.lastErr = 'model discovery failed: Get "/v1/models": context deadline exceeded' + if (path === '/admin/api/overview') { + p.attemptsMinute = Math.max(p.attemptsMinute ?? 0, 12) + p.failuresMinute = p.attemptsMinute + } +} + +function redisDown(path: string, body: Obj, ctx: ScenarioContext): ScenarioResult | void { + if (HISTORY_PATHS.includes(path)) return fail(503, 'server_error', 'usage history store unavailable') + if (path === '/admin/api/overview') { + body.redis = { configured: true, lastErrAt: iso(ctx.now - 4000), lastErr: 'dial tcp: connect: connection refused' } + } else if (path === '/admin/api/events') { + body.source = 'replica' + body.degraded = true + } +} + +function configWarnings(path: string, body: Obj) { + if (path === '/admin/api/overview') { + body.warnings = [...WARNINGS] + body.warningsDropped = WARNINGS_DROPPED + } else if (path === '/admin/api/config') { + body.warnings = [...WARNINGS] + } +} + +function routerEscalations(path: string, body: Obj) { + if (path !== '/admin/api/overview' && path !== '/admin/api/catalog') return + eachRouter(body, (r) => { + const tiers: string[] = (r.tiers ?? []).map((t: Obj) => t.name) + if (tiers.length < 2) return + const stats = (r.stats ??= { scope: 'shared', tiers: [], reasons: [], outcomes: [], requests: 0 }) + stats.escalations = tiers.slice(0, -1).map((from, i) => ({ from, to: tiers[i + 1], count: 14 - i * 5 })) + if (tiers.length > 2) stats.escalations.push({ from: tiers[0], to: tiers[tiers.length - 1], count: 3 }) + stats.shadow = tiers.flatMap((live, i) => tiers.map((shadow, j) => ({ live, shadow, count: i === j ? 40 - i * 9 : 4 + ((i + j) % 3) * 3 }))) + stats.requests = Math.max(stats.requests ?? 0, 120) + r.shadowEnabled = true + r.shadowClassifier ??= 'v2' + r.fellBack = 7 + }) +} + +function targetsHealthy(path: string, body: Obj, ctx: ScenarioContext) { + if (path !== '/admin/api/targets') return + for (const t of [...(body.mcpServers ?? []), ...(body.agents ?? [])]) { + t.health = { state: 'healthy', consecutiveFailures: 0, lastCheck: iso(ctx.now - 3000), latencyMs: 18 + (t.name.length % 40), source: 'traffic' } + } +} + +function statsDisabled(path: string, body: Obj, status: number): ScenarioResult | void { + if (path === '/admin/api/usage/totals' && body.kind === 'usermodel') { + return fail(404, 'invalid_request_error', 'user/model stats are not enabled') + } + if (status !== 200) return + if (path === '/admin/api/overview') { + Object.assign((body.features ??= {}), { userModelStats: false, latencyStats: false, cacheStats: false }) + } else if (path === '/admin/api/config') { + const stats = (((body.config ??= {}).admin ??= {}).stats ??= {}) + stats.latency = false + stats.userModel = false + if (body.features) Object.assign(body.features, { userModelStats: false, latencyStats: false, cacheStats: false }) + } else if (path === '/admin/api/performance') { + body.latencyEnabled = false + for (const r of [...(body.rows ?? []), ...(body.points ?? [])]) for (const k of LATENCY_KEYS) delete r[k] + } +} + +const zeroCounters = (o: Obj) => { + for (const k of Object.keys(o)) { + if (/(PerMinute|PerDay|PerMonth|MicroUsd)$/.test(k) && typeof o[k] === 'number') o[k] = 0 + } +} + +function empty(path: string, body: Obj) { + switch (path) { + case '/admin/api/usage/series': + for (const s of body.series ?? []) s.points = s.points.map(() => 0) + break + case '/admin/api/usage/totals': + body.rows = [] + break + case '/admin/api/usage/models': + body.models = [] + break + case '/admin/api/events': + body.events = [] + break + case '/admin/api/performance': + body.rows = [] + for (const p of body.points ?? []) for (const k of ['count', 'attempts', 'failures', ...LATENCY_KEYS]) if (k in p) p[k] = 0 + break + case '/admin/api/usage': + for (const o of [...(body.users ?? []), ...(body.groups ?? []), body.total ?? {}]) zeroCounters(o) + break + case '/admin/api/overview': + for (const p of body.providers ?? []) zeroCounters(p) + for (const p of body.providers ?? []) for (const k of ['attemptsDay', 'failuresDay', 'attemptsMinute', 'failuresMinute']) p[k] = 0 + break + case '/admin/api/targets': + for (const t of [...(body.mcpServers ?? []), ...(body.agents ?? [])]) zeroCounters(t.counters ?? {}) + break + } +} + +function limitsHot(path: string, body: Obj, ctx: ScenarioContext) { + if (path === '/admin/api/usage') { + const hot = (body.users as Obj[]).filter((u) => HOT_USER_IDS.includes(u.id) && (u.limits?.requestsPerMinute ?? 0) > 0) + for (const u of hot) { + u.requestsPerMinute = Math.floor(u.limits.requestsPerMinute * HOT_MINUTE_FRACTION) + if (u.limits.requestsPerDay > 0) u.requestsPerDay = Math.floor(u.limits.requestsPerDay * HOT_DAY_FRACTION) + u.rejectionsPerDay = Math.max(u.rejectionsPerDay ?? 0, 9) + } + const added = hot.reduce((s: number, u: Obj) => s + u.requestsPerMinute, 0) + for (const g of body.groups ?? []) if (g.id === HOT_GROUP) g.requestsPerMinute += added + if (body.total) body.total.requestsPerMinute += added + } else if (path === '/admin/api/events') { + const fresh = HOT_USER_IDS.flatMap((user, i) => [ + limitEvent(user, 'rate_limit', ctx.now - (i * 2 + 1) * 4000, 'requests per minute limit reached; request rejected', 429), + limitEvent(user, 'paced', ctx.now - (i * 2 + 2) * 4000, `request delayed ${(1.5 + i * 0.7).toFixed(1)}s by pacing`), + ]) + body.events = [...fresh, ...(body.events ?? [])] + } +} + +function limitEvent(user: string, kind: string, at: number, message: string, status?: number): Obj { + return { time: iso(at), replica: 'mock-replica-1', instance: 'mock', user, group: HOT_GROUP, route: 'chat/completions', kind, message, ...(status ? { status } : {}) } +} + +const copies = (factor: number, make: (n: number) => T): T[] => Array.from({ length: factor }, (_, n) => make(n)) +const suffix = (id: string, n: number) => (n === 0 ? id : `${id}-v${n + 1}`) + +function huge(path: string, body: Obj) { + if (path === '/admin/api/overview') { + body.providers = (body.providers as Obj[]).flatMap((p) => + copies(HUGE_FACTOR, (n) => { + const models = (p.models as string[]).flatMap((m) => copies(HUGE_FACTOR, (r) => suffix(m, r))) + const grow = (src: Obj) => Object.fromEntries(Object.entries(src ?? {}).flatMap(([m, v]) => copies(HUGE_FACTOR, (r) => [suffix(m, r), v]))) + return { ...p, name: n === 0 ? p.name : `${p.name}-${n + 1}`, models, modelCount: models.length, modelMeta: grow(p.modelMeta), modelRates: grow(p.modelRates) } + }), + ) + } else if (path === '/admin/api/catalog') { + body.providers = (body.providers as Obj[]).flatMap((p) => + copies(HUGE_FACTOR, (n) => { + const name = n === 0 ? p.name : `${p.name}-${n + 1}` + const models = (p.models as Obj[]).flatMap((m) => copies(HUGE_FACTOR, (r) => ({ ...m, model: suffix(m.model, r), id: `${name}/${suffix(m.model, r)}` }))) + return { ...p, name, models } + }), + ) + } else if (path === '/admin/api/usage/models' && Array.isArray(body.models)) { + body.models = tripleRows(body.models) + } else if (path === '/admin/api/performance' && Array.isArray(body.rows) && body.kind === 'model') { + body.rows = tripleRows(body.rows) + } +} + +function tripleRows(rows: Obj[]): Obj[] { + return rows.flatMap((r) => copies(HUGE_FACTOR, (n) => ({ ...r, id: suffix(r.id, n) }))) +} + +function live(path: string, body: Obj, ctx: ScenarioContext) { + if (path === '/admin/api/events') { + const kinds = ['upstream', 'capacity', 'unpriced'] + const kind = kinds[Math.floor(ctx.rng() * kinds.length)]! + body.events = [{ time: iso(ctx.now), replica: body.replica ?? 'mock-replica-1', instance: 'mock', model: 'gx10/Qwen3.8-27B', route: 'chat/completions', kind, message: `live ${kind} event at ${iso(ctx.now)}` }, ...(body.events ?? [])] + } else if (path === '/admin/api/usage') { + for (const u of body.users ?? []) if (u.requestsPerDay > 0) u.requestsPerMinute = Math.max(u.requestsPerMinute, 3) + body.total.requestsPerMinute = Math.max(body.total.requestsPerMinute, 24) + } else if (path === '/admin/api/overview') { + for (const p of body.providers ?? []) if (p.attemptsDay > 0) p.attemptsMinute = Math.max(p.attemptsMinute, 4) + } +} + +/** Applies the selected scenarios to one response. The input body is never mutated. */ +export function applyScenarios(names: string[], path: string, body: unknown, status: number, ctx: ScenarioContext = { now: Date.now(), rng: Math.random }): ScenarioResult { + if (!path.startsWith(API)) return { status, body } + if (names.includes('auth-401')) return fail(401, 'authentication_error', 'invalid or missing API key') + if (names.includes('auth-403')) return fail(403, 'invalid_request_error', 'admin access required') + if (names.length === 0 || status !== 200) return { status, body } + + const b = structuredClone(body) as Obj + const steps: ((p: string, b: Obj) => ScenarioResult | void)[] = [] + const on = (name: ScenarioName, step: (p: string, b: Obj) => ScenarioResult | void) => names.includes(name) && steps.push(step) + on('stats-disabled', (p, x) => statsDisabled(p, x, status)) + on('redis-down', (p, x) => redisDown(p, x, ctx)) + on('empty', empty) + on('huge', huge) + on('breaker-open', (p, x) => breakerOpen(p, x, ctx)) + on('config-warnings', configWarnings) + on('router-escalations', routerEscalations) + on('targets-healthy', (p, x) => targetsHealthy(p, x, ctx)) + on('live', (p, x) => live(p, x, ctx)) + on('limits-hot', (p, x) => limitsHot(p, x, ctx)) + for (const step of steps) { + const out = step(path, b) + if (out) return out + } + return { status, body: b } +} diff --git a/webui/mock/server.ts b/webui/mock/server.ts new file mode 100644 index 0000000..ac8bf1c --- /dev/null +++ b/webui/mock/server.ts @@ -0,0 +1,56 @@ +import { readFileSync } from 'node:fs' +import type { IncomingMessage, ServerResponse } from 'node:http' +import { dirname, join } from 'node:path' +import { fileURLToPath } from 'node:url' + +import type { Plugin } from 'vite' + +import type { Fixture } from './match.ts' +import { respond } from './respond.ts' +import { errorEnvelope, parseScenarios, scenarioDelayMs } from './scenarios.ts' + +const HERE = dirname(fileURLToPath(import.meta.url)) +const API_PREFIX = '/admin/api' + +function send(res: ServerResponse, status: number, body: unknown) { + res.statusCode = status + res.setHeader('content-type', 'application/json') + res.setHeader('cache-control', 'no-store') + res.end(JSON.stringify(body)) +} + +const header = (req: IncomingMessage, name: string) => { + const v = req.headers[name] + return Array.isArray(v) ? v[0] : v +} + +/** Vite plugin serving /admin/api/* from the captured fixtures; dev server only, enabled by MOCK=1 in vite.config.ts. */ +export function mockAdminApi(): Plugin { + const manifest = JSON.parse(readFileSync(join(HERE, 'manifest.json'), 'utf8')) as Fixture[] + const readFixture = (file: string) => JSON.parse(readFileSync(join(HERE, 'fixtures', file), 'utf8')) as unknown + return { + name: 'mock-admin-api', + apply: 'serve', + configureServer(server) { + server.middlewares.use(API_PREFIX, async (req, res) => { + const url = new URL(req.originalUrl ?? req.url ?? '/', 'http://mock.local') + const scenarios = parseScenarios(header(req, 'referer'), header(req, 'x-mock-scenario')) + if (req.method !== 'GET') return send(res, 405, errorEnvelope(405, 'invalid_request_error', 'method not allowed')) + const hasKey = (header(req, 'x-api-key') ?? '').trim() !== '' + const out = respond({ + manifest, + readFixture, + path: url.pathname, + query: url.searchParams, + scenarios: hasKey ? scenarios : [...scenarios, 'auth-401'], + now: Date.now(), + rng: Math.random, + }) + const delay = scenarioDelayMs(scenarios) + if (delay > 0) await new Promise((r) => setTimeout(r, delay)) + send(res, out.status, out.body) + }) + server.config.logger.info(` mock admin API active (scenarios via ?mock=a,b)`) + }, + } +} diff --git a/webui/mock/synth.ts b/webui/mock/synth.ts new file mode 100644 index 0000000..f5f349d --- /dev/null +++ b/webui/mock/synth.ts @@ -0,0 +1,161 @@ +import { METRIC_PER_REQ, TOTALS_METRICS, hoursOf, normaliseQuery, type Fixture, type NormQuery } from './match.ts' +import { bucketsFor, WINDOW_HOURS, type MockWindow } from './time-shift.ts' + +type Obj = Record // eslint-disable-line @typescript-eslint/no-explicit-any + +const COUNT_KEYS = ['count', 'attempts', 'failures', 'timeouts', 'failovers'] +const MODEL_FIELDS: Record = { req: 'requests', tokin: 'tokensIn', tokout: 'tokensOut', cost: 'costMicroUsd' } + +export function hash(s: string): number { + let h = 2166136261 + for (let i = 0; i < s.length; i++) h = Math.imul(h ^ s.charCodeAt(i), 16777619) + return h >>> 0 +} + +/** + * Rescales one captured series to another bucket size, count and offset. Buckets are read as a rate + * over a periodic extension of the capture, so a longer span repeats the captured shape and a coarser + * bucket sums it. Output is oldest first. + */ +export function resample(points: number[], srcHours: number, dstHours: number, count: number, offset: number): number[] { + const n = points.length + const out = new Array(count).fill(0) + if (n === 0) return out + const newestFirst = [...points].reverse() + const cum = [0] + for (const v of newestFirst) cum.push(cum[cum.length - 1]! + v) + const total = cum[n]! + const period = n * srcHours + const integral = (x: number): number => { + const whole = Math.floor(x / period) + const y = x - whole * period + const i = Math.min(Math.floor(y / srcHours), n - 1) + return whole * total + cum[i]! + (newestFirst[i]! * (y - i * srcHours)) / srcHours + } + for (let k = 0; k < count; k++) { + out[count - 1 - k] = Math.round(integral((k + offset + 1) * dstHours) - integral((k + offset) * dstHours)) + } + return out +} + +const windowHours = (w: unknown) => WINDOW_HOURS[w as MockWindow] ?? 24 +const num = (q: NormQuery, k: string, d: number) => (q[k]?.[0] !== undefined ? Number(q[k]![0]) : d) +const win = (q: NormQuery) => (q.window?.[0] ?? 'day') as MockWindow + +const scopePrefix = (s: string) => s.slice(0, s.includes(':') ? s.indexOf(':') : s.length) + +/** The captured series for a scope, or a same-prefix one chosen by hash and scaled so ids differ visibly. */ +function pickSeries(pool: Obj[], scope: string): { src: Obj; scale: number } { + const hit = pool.find((s) => s.scope === scope) + if (hit) return { src: hit, scale: 1 } + const same = pool.filter((s) => scopePrefix(s.scope) === scopePrefix(scope)) + const from = same.length ? same : pool + return { src: from[hash(scope) % from.length]!, scale: 0.4 + (hash(`${scope}#`) % 100) / 80 } +} + +function synthSeries(body: Obj, fx: Fixture, q: NormQuery, requested: URLSearchParams, now: number): Obj { + const have = normaliseQuery(fx.path, fx.query) + const srcHours = windowHours(body.window) + const dstHours = windowHours(win(q)) + const span = num(q, 'span', 14) + const offset = num(q, 'offset', 0) + const metric = q.metric?.[0] ?? 'req' + const ratio = have.metric?.[0] === metric ? 1 : (METRIC_PER_REQ[metric] ?? 1) / (METRIC_PER_REQ[have.metric?.[0] ?? 'req'] ?? 1) + const pool: Obj[] = body.series + const series = requested.getAll('scope').map((scope) => { + const { src, scale } = pickSeries(pool, scope) + const points = resample(src.points, srcHours, dstHours, span, offset).map((v) => Math.round(v * ratio * scale)) + return { scope, points } + }) + return { ...body, metric, window: win(q), span, offset, buckets: bucketsFor(win(q), span, offset, now), series, unknown: [] } +} + +function synthTotals(body: Obj, q: NormQuery, limit: number | null): Obj { + const ratio = hoursOf(q) / (windowHours(body.window) * Number(body.span)) + const kind = q.kind?.[0] + const metrics = q.metrics ?? (kind === 'targetcaller' ? ['req'] : TOTALS_METRICS) + const order = ['req', 'tokin', 'tokout', 'cost'].filter((m) => metrics.includes(m)) + const rows = (body.rows as Obj[]).map((r) => ({ + ...r, + values: Object.fromEntries(order.map((m) => [m, Math.round((r.values[m] ?? 0) * ratio)])), + })) + return { ...body, window: win(q), span: num(q, 'span', 14), offset: num(q, 'offset', 0), metrics: order, rows: limit ? rows.slice(0, limit) : rows } +} + +function synthModels(body: Obj, q: NormQuery, requested: URLSearchParams): Obj { + const ratio = hoursOf(q) / (windowHours(body.window) * Number(body.span)) + const metric = q.metric?.[0] ?? 'cost' + const field = MODEL_FIELDS[metric] ?? 'requests' + const scaled = (body.models as Obj[]).map((m) => { + const o: Obj = { ...m } + for (const k of Object.keys(m)) if (typeof m[k] === 'number') o[k] = Math.round(m[k] * ratio) + o.value = o[field] ?? o.value + return o + }) + scaled.sort((a, b) => b.value - a.value) + const limit = Number(requested.get('limit') ?? 0) + return { ...body, metric, window: win(q), span: num(q, 'span', 14), offset: num(q, 'offset', 0), models: limit > 0 ? scaled.slice(0, limit) : scaled } +} + +function synthPerformance(body: Obj, q: NormQuery, now: number): Obj { + const srcHours = windowHours(body.window) + const dstHours = windowHours(win(q)) + const span = num(q, 'span', 14) + const offset = num(q, 'offset', 0) + const ratio = hoursOf(q) / (srcHours * Number(body.span ?? span)) + const rows = (body.rows as Obj[]).map((r) => { + const o: Obj = { ...r } + for (const k of COUNT_KEYS) if (typeof r[k] === 'number') o[k] = Math.round(r[k] * ratio) + return o + }) + const out: Obj = { ...body, window: win(q), span, offset, rows } + if (Array.isArray(body.points)) { + const src: Obj[] = body.points + const buckets = bucketsFor(win(q), span, offset, now) + const series = Object.fromEntries(COUNT_KEYS.filter((k) => typeof src[0]?.[k] === 'number').map((k) => [k, resample(src.map((p) => p[k]), srcHours, dstHours, span, offset)])) + const live = src.map((p, i) => (p.count > 0 ? i : -1)).filter((i) => i >= 0) + out.buckets = buckets + out.points = buckets.map((id, i) => { + const k = span - 1 - i + const pos = Math.floor(((k + offset + 0.5) * dstHours) / srcHours) % src.length + const from = src.length - 1 - pos + const pick = live.length ? live.reduce((a, b) => (Math.abs(b - from) < Math.abs(a - from) ? b : a)) : -1 + const p: Obj = { id } + for (const key of COUNT_KEYS) if (series[key]) p[key] = series[key]![i] + if (pick >= 0 && p.count > 0) for (const [key, v] of Object.entries(src[pick]!)) if (!(key in p) && key !== 'id') p[key] = v + return p + }) + } + return out +} + +/** Builds a response for a query no fixture covers from the nearest fixture, rescaled to the requested range. */ +export function synthesise(fx: Fixture, body: Obj, query: URLSearchParams, now: number): Obj { + const q = normaliseQuery(fx.path, query) + switch (fx.path) { + case '/admin/api/usage/series': + return synthSeries(body, fx, q, query, now) + case '/admin/api/usage/totals': { + const limit = Number(query.get('limit') ?? 0) + return synthTotals(body, q, limit > 0 ? limit : null) + } + case '/admin/api/usage/models': + return synthModels(body, q, query) + case '/admin/api/performance': + return synthPerformance(body, q, now) + default: + return body + } +} + +/** Remaps series scopes onto the ones requested when a same-class fixture answered, so each requested id gets a series. */ +export function fitSeriesScopes(body: Obj, requested: URLSearchParams): Obj { + const want = requested.getAll('scope') + const pool: Obj[] = body.series + if (want.length === pool.length && want.every((s, i) => s === pool[i]!.scope)) return body + const series = want.map((scope) => { + const { src, scale } = pickSeries(pool, scope) + return scale === 1 && src.scope === scope ? src : { scope, points: (src.points as number[]).map((v) => Math.round(v * scale)) } + }) + return { ...body, series } +} diff --git a/webui/mock/time-shift.ts b/webui/mock/time-shift.ts new file mode 100644 index 0000000..92badef --- /dev/null +++ b/webui/mock/time-shift.ts @@ -0,0 +1,86 @@ +export type MockWindow = 'hour' | 'day' | 'month' + +export const CAPTURE_AT = Date.parse('2026-11-25T01:01:07Z') + +/** Hours per bucket; a month bucket is treated as 30 days when rescaling. */ +export const WINDOW_HOURS: Record = { hour: 1, day: 24, month: 720 } + +const HOUR_MS = 3_600_000 +const DAY_MS = 24 * HOUR_MS +const ISO_RE = /^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.\d+)?Z$/ +const BUCKET_LEN: Record = { 10: 'hour', 8: 'day', 6: 'month' } +const MIN_REAL_TIME = Date.parse('2000-01-01T00:00:00Z') + +const pad = (n: number, w: number) => String(n).padStart(w, '0') + +function unitIndex(window: MockWindow, ms: number): number { + if (window === 'hour') return Math.floor(ms / HOUR_MS) + if (window === 'day') return Math.floor(ms / DAY_MS) + const d = new Date(ms) + return d.getUTCFullYear() * 12 + d.getUTCMonth() +} + +function unitStart(window: MockWindow, index: number): number { + if (window === 'hour') return index * HOUR_MS + if (window === 'day') return index * DAY_MS + return Date.UTC(Math.floor(index / 12), index % 12, 1) +} + +export function formatBucket(window: MockWindow, ms: number): string { + const d = new Date(ms) + const date = `${pad(d.getUTCFullYear(), 4)}${pad(d.getUTCMonth() + 1, 2)}` + if (window === 'month') return date + const day = `${date}${pad(d.getUTCDate(), 2)}` + return window === 'day' ? day : `${day}${pad(d.getUTCHours(), 2)}` +} + +function parseBucket(s: string): { window: MockWindow; ms: number } | null { + const window = BUCKET_LEN[s.length] + if (!window || !/^\d+$/.test(s)) return null + const y = Number(s.slice(0, 4)) + const mo = Number(s.slice(4, 6)) - 1 + const d = window === 'month' ? 1 : Number(s.slice(6, 8)) + const h = window === 'hour' ? Number(s.slice(8, 10)) : 0 + return { window, ms: Date.UTC(y, mo, d, h) } +} + +/** Bucket labels oldest first; the newest is the bucket holding `now` moved back by `offset` buckets. */ +export function bucketsFor(window: MockWindow, span: number, offset: number, now: number): string[] { + const newest = unitIndex(window, now) - offset + const out: string[] = [] + for (let i = span - 1; i >= 0; i--) out.push(formatBucket(window, unitStart(window, newest - i))) + return out +} + +function shiftBucket(s: string, captureAt: number, now: number): string { + const b = parseBucket(s) + if (!b) return s + const diff = unitIndex(b.window, now) - unitIndex(b.window, captureAt) + return formatBucket(b.window, unitStart(b.window, unitIndex(b.window, b.ms) + diff)) +} + +/** Moves every time-bearing value in a captured body forward by `now - captureAt`; the newest bucket lands on now's bucket. */ +export function shiftTimestamps(body: unknown, captureAt: number, now: number): unknown { + const delta = now - captureAt + const walk = (v: unknown, key: string): unknown => { + if (typeof v === 'string') { + if (ISO_RE.test(v)) { + const t = Date.parse(v) + return t < MIN_REAL_TIME ? v : new Date(t + delta).toISOString() + } + if (key === '__bucket') return shiftBucket(v, captureAt, now) + return v + } + if (typeof v === 'number') return key === 'lastSeen' ? v + Math.round(delta / 1000) : v + if (Array.isArray(v)) return v.map((x) => walk(x, key === 'buckets' ? '__bucket' : key)) + if (v && typeof v === 'object') { + const out: Record = {} + for (const [k, x] of Object.entries(v)) { + out[k] = k === 'id' && key === 'points' && typeof x === 'string' ? shiftBucket(x, captureAt, now) : walk(x, k) + } + return out + } + return v + } + return walk(body, '') +} diff --git a/webui/package.json b/webui/package.json index a740f2a..ac535c7 100644 --- a/webui/package.json +++ b/webui/package.json @@ -5,6 +5,7 @@ "type": "module", "scripts": { "dev": "vite", + "dev:mock": "MOCK=1 vite", "build": "vue-tsc -b && vite build", "preview": "vite preview", "test": "vitest run" diff --git a/webui/src/lib/mock-server.spec.ts b/webui/src/lib/mock-server.spec.ts new file mode 100644 index 0000000..3dd064b --- /dev/null +++ b/webui/src/lib/mock-server.spec.ts @@ -0,0 +1,308 @@ +import { describe, expect, it } from 'vitest' + +import manifestJson from '../../mock/manifest.json' +import { matchFixture, type Fixture } from '../../mock/match' +import { respond } from '../../mock/respond' +import { applyScenarios, SCENARIOS, scenarioDelayMs, parseScenarios } from '../../mock/scenarios' +import { bucketsFor, CAPTURE_AT, shiftTimestamps } from '../../mock/time-shift' + +const manifest = manifestJson as Fixture[] + +const raw = import.meta.glob('../../mock/fixtures/*.json', { query: '?raw', import: 'default', eager: true }) as Record +const readFixture = (file: string): unknown => JSON.parse(raw[`../../mock/fixtures/${file}`] as string) + +const NOW = CAPTURE_AT + 3 * 86_400_000 + 5 * 3_600_000 +const q = (s: string) => new URLSearchParams(s) +const get = (path: string, query = '', scenarios: string[] = [], now = NOW) => + respond({ manifest, readFixture, path, query: q(query), scenarios, now, rng: () => 0.5 }) + +// biome-ignore lint/suspicious/noExplicitAny: fixtures are untyped JSON +type Any = any + +describe('matchFixture', () => { + it('ignores key order', () => { + const a = matchFixture(manifest, '/admin/api/usage/totals', q('kind=group&window=day&span=14&metrics=cost')) + const b = matchFixture(manifest, '/admin/api/usage/totals', q('metrics=cost&span=14&window=day&kind=group')) + expect(a).not.toBeNull() + expect(b?.file).toBe(a?.file) + }) + + it('ignores repeated-key order', () => { + const f = manifest.find((m) => m.path.endsWith('/series') && Array.isArray(m.query.scope) && m.query.scope.length === 2) as Fixture + const scopes = f.query.scope as string[] + const mk = (list: string[]) => { + const p = new URLSearchParams() + for (const s of list) p.append('scope', s) + for (const [k, v] of Object.entries(f.query)) if (k !== 'scope') p.set(k, v as string) + return p + } + expect(matchFixture(manifest, f.path, mk([...scopes].reverse()))?.file).toBe(f.file) + }) + + it('returns null for unknown path', () => { + expect(matchFixture(manifest, '/admin/api/nope', q(''))).toBeNull() + }) + + it('matches on value class for an id not in the fixtures', () => { + const hit = matchFixture(manifest, '/admin/api/usage/totals', q('kind=usermodel&window=day&span=14&user=user-99')) + expect(hit?.query.kind).toBe('usermodel') + }) + + it('every manifest entry resolves to a fixture with its own status', () => { + for (const f of manifest) { + const p = new URLSearchParams() + for (const [k, v] of Object.entries(f.query)) for (const x of Array.isArray(v) ? v : [v]) p.append(k, x) + const hit = matchFixture(manifest, f.path, p) + expect(hit, f.file).not.toBeNull() + expect(hit?.status, f.file).toBe(f.status) + } + }) +}) + +describe('shiftTimestamps', () => { + it('moves newest bucket to now', () => { + const entry = manifest.find((m) => m.path.endsWith('/series') && m.query.window === 'day' && m.query.span === '14' && !m.query.offset)! + const body = readFixture(entry.file) as Any + const shifted = shiftTimestamps(body, CAPTURE_AT, NOW) as Any + expect(shifted.buckets.at(-1)).toBe(bucketsFor('day', 1, 0, NOW)[0]) + expect(shifted.buckets).toHaveLength(body.buckets.length) + expect(shifted.series[0].points).toEqual(body.series[0].points) + }) + + it('shifts ISO timestamps by the delta and leaves the zero time alone', () => { + const out = shiftTimestamps({ time: '2026-11-25T00:47:17.590946814Z', openUntil: '0001-01-01T00:00:00Z' }, CAPTURE_AT, CAPTURE_AT + 60_000) as Any + expect(Date.parse(out.time)).toBe(Date.parse('2026-11-25T00:48:17.590Z')) + expect(out.openUntil).toBe('0001-01-01T00:00:00Z') + }) +}) + +describe('respond', () => { + it('serves an exact fixture with buckets ending now', () => { + const r = get('/admin/api/usage/series', 'scope=group:friends&metric=cost&window=day&span=14') + expect(r.status).toBe(200) + expect((r.body as Any).buckets.at(-1)).toBe(bucketsFor('day', 1, 0, NOW)[0]) + }) + + it('404s an unknown query with the real error envelope', () => { + const r = get('/admin/api/performance', 'kind=bogus&window=day&span=7') + expect(r.status).toBe(404) + expect(r.body).toEqual({ error: { message: expect.any(String), type: 'invalid_request_error', code: '404' } }) + }) + + it('404s an unknown path', () => { + expect(get('/admin/api/nope').status).toBe(404) + }) + + it('400s detail=1 at day/30 for any metric', () => { + const r = get('/admin/api/usage/models', 'metric=tokout&window=day&span=30&limit=100&detail=1') + expect(r.status).toBe(400) + expect((r.body as Any).error.message).toContain('range too large') + }) + + it('synthesises performance month from day data with aligned buckets', () => { + const r = get('/admin/api/performance', 'kind=provider&window=month&span=3&series=1&id=alibaba') + expect(r.status).toBe(200) + const b = r.body as Any + expect(b.window).toBe('month') + expect(b.span).toBe(3) + expect(b.buckets).toEqual(bucketsFor('month', 3, 0, NOW)) + expect(b.points).toHaveLength(3) + expect(b.points.map((p: Any) => p.id)).toEqual(b.buckets) + }) + + it('synthesises performance month rows scaled up from day rows', () => { + const day = (get('/admin/api/performance', 'kind=provider&window=day&span=14').body as Any).rows[0] + const month = (get('/admin/api/performance', 'kind=provider&window=month&span=3').body as Any).rows[0] + expect(month.count).toBeGreaterThan(day.count * 2) + expect(month.p50Ms).toBe(day.p50Ms) + }) + + it('synthesises hour-window usermodel totals from day data', () => { + const r = get('/admin/api/usage/totals', 'kind=usermodel&window=hour&span=24&user=admin') + expect(r.status).toBe(200) + const b = r.body as Any + expect(b.window).toBe('hour') + expect(b.span).toBe(24) + const dayReq = (get('/admin/api/usage/totals', 'kind=usermodel&window=day&span=14&user=admin').body as Any).rows.reduce((s: number, x: Any) => s + x.values.req, 0) + const hourReq = b.rows.reduce((s: number, x: Any) => s + x.values.req, 0) + expect(hourReq).toBeLessThan(dayReq) + }) + + it('synthesises a missing series combination to the requested span and bucket count', () => { + const r = get('/admin/api/usage/series', 'scope=group:friends&scope=group:home&metric=req&window=hour&span=36') + expect(r.status).toBe(200) + const b = r.body as Any + expect(b.buckets).toEqual(bucketsFor('hour', 36, 0, NOW)) + expect(b.series.map((s: Any) => s.scope).sort()).toEqual(['group:friends', 'group:home']) + for (const s of b.series) expect(s.points).toHaveLength(36) + }) + + it('never serves a different range verbatim', () => { + const a = (get('/admin/api/usage/series', 'scope=group:friends&metric=cost&window=day&span=14').body as Any).series[0].points + const b = (get('/admin/api/usage/series', 'scope=group:friends&metric=cost&window=day&span=20').body as Any).series[0].points + expect(b).toHaveLength(20) + expect(b.slice(-14)).toEqual(a) + }) + + it('applies offset to synthesised buckets', () => { + const b = get('/admin/api/usage/series', 'scope=group:friends&metric=cost&window=day&span=10&offset=10').body as Any + expect(b.buckets).toEqual(bucketsFor('day', 10, 10, NOW)) + expect(b.offset).toBe(10) + }) + + it('slices events to the requested limit', () => { + expect((get('/admin/api/events', 'limit=20').body as Any).events).toHaveLength(20) + }) + + it('jitters live minute meters between calls', () => { + let n = 0 + const rng = () => (n++ % 2 ? 0.9 : 0.1) + const call = () => respond({ manifest, readFixture, path: '/admin/api/usage', query: q(''), scenarios: ['live'], now: NOW, rng }).body as Any + expect(call().total.requestsPerMinute).not.toBe(call().total.requestsPerMinute) + }) + + it('adds 1500ms with slow and sets auth status through scenarios', () => { + expect(get('/admin/api/overview', '', ['slow']).delayMs).toBe(1500) + expect(get('/admin/api/overview', '', ['auth-401']).status).toBe(401) + }) +}) + +describe('scenarios', () => { + const overview = () => readFixture('overview.json') as Any + const NOWS = { now: NOW, rng: () => 0.5 } + const apply = (names: string[], path: string, body: unknown, status = 200) => applyScenarios(names, path, body, status, NOWS) + + it('lists every documented scenario', () => { + expect([...SCENARIOS]).toEqual([ + 'live', 'breaker-open', 'redis-down', 'config-warnings', 'router-escalations', 'targets-healthy', + 'stats-disabled', 'auth-401', 'auth-403', 'empty', 'limits-hot', 'slow', 'huge', + ]) + }) + + it('parses scenarios from referer and header', () => { + expect(parseScenarios('http://localhost:5173/admin/?mock=empty,slow', undefined)).toEqual(['empty', 'slow']) + expect(parseScenarios(undefined, 'huge, bogus')).toEqual(['huge']) + expect(parseScenarios(undefined, undefined)).toEqual([]) + }) + + it('breaker-open sets healthState open with future openUntil on one provider', () => { + const out = apply(['breaker-open'], '/admin/api/overview', overview()).body as Any + const open = out.providers.filter((p: Any) => p.healthState === 'open') + expect(open).toHaveLength(1) + expect(Date.parse(open[0].openUntil)).toBeGreaterThan(NOW) + expect(open[0].lastErr).toBeTruthy() + }) + + it('breaker-open also marks the catalog provider', () => { + const out = apply(['breaker-open'], '/admin/api/catalog', readFixture('catalog.json')).body as Any + expect(out.providers.filter((p: Any) => p.healthState === 'open')).toHaveLength(1) + }) + + it('redis-down returns 503 on usage/series', () => { + const out = apply(['redis-down'], '/admin/api/usage/series', { buckets: [] }) + expect(out.status).toBe(503) + expect((out.body as Any).error.message).toBe('usage history store unavailable') + }) + + it('redis-down surfaces the redis error in overview and degrades events', () => { + const o = apply(['redis-down'], '/admin/api/overview', overview()).body as Any + expect(o.redis.lastErr).toBeTruthy() + const e = apply(['redis-down'], '/admin/api/events', readFixture('events__limit-200.json')).body as Any + expect(e.source).toBe('replica') + expect(e.degraded).toBe(true) + }) + + it('config-warnings fills warnings on overview and config', () => { + const o = apply(['config-warnings'], '/admin/api/overview', overview()).body as Any + expect(o.warnings.length).toBeGreaterThan(2) + expect(o.warningsDropped).toBeGreaterThan(0) + expect((apply(['config-warnings'], '/admin/api/config', readFixture('config.json')).body as Any).warnings.length).toBeGreaterThan(2) + }) + + it('router-escalations fills stats.escalations, stats.shadow and fellBack', () => { + const o = apply(['router-escalations'], '/admin/api/catalog', readFixture('catalog.json')).body as Any + const r = o.routers[0] + expect(r.stats.escalations.length).toBeGreaterThan(0) + expect(r.stats.shadow.length).toBeGreaterThan(0) + expect(r.fellBack).toBeGreaterThan(0) + expect(r.shadowEnabled).toBe(true) + }) + + it('targets-healthy marks every target healthy', () => { + const t = apply(['targets-healthy'], '/admin/api/targets', readFixture('targets.json')).body as Any + for (const x of [...t.mcpServers, ...t.agents]) { + expect(x.health.state).toBe('healthy') + expect(x.health.consecutiveFailures).toBe(0) + } + }) + + it('stats-disabled turns the features off and 404s usermodel totals', () => { + const o = apply(['stats-disabled'], '/admin/api/overview', overview()).body as Any + expect(o.features).toMatchObject({ userModelStats: false, latencyStats: false, cacheStats: false }) + expect(apply(['stats-disabled'], '/admin/api/usage/totals', { kind: 'usermodel', rows: [] }, 200)).toMatchObject({ status: 404 }) + const p = apply(['stats-disabled'], '/admin/api/performance', readFixture('performance__kind-model_window-day_span-14.json')).body as Any + expect(p.latencyEnabled).toBe(false) + expect(p.rows[0].p50Ms).toBeUndefined() + }) + + it('auth-401 returns 401 for every api path', () => { + for (const p of new Set(manifest.map((m) => m.path))) { + const out = apply(['auth-401'], p, {}) + expect(out.status, p).toBe(401) + expect((out.body as Any).error.type).toBe('authentication_error') + } + }) + + it('auth-403 returns 403 for every api path', () => { + expect(apply(['auth-403'], '/admin/api/overview', {}).status).toBe(403) + }) + + it('empty zeroes series and empties lists', () => { + const s = apply(['empty'], '/admin/api/usage/series', readFixture(manifest.find((m) => m.path.endsWith('/series'))!.file)).body as Any + expect(s.series.length).toBeGreaterThan(0) + for (const x of s.series) expect(x.points.every((n: number) => n === 0)).toBe(true) + expect((apply(['empty'], '/admin/api/usage/totals', { rows: [{ id: 'a', values: { req: 1 } }] }).body as Any).rows).toEqual([]) + expect((apply(['empty'], '/admin/api/usage/models', { models: [{ id: 'a' }] }).body as Any).models).toEqual([]) + expect((apply(['empty'], '/admin/api/events', readFixture('events__limit-200.json')).body as Any).events).toEqual([]) + const u = apply(['empty'], '/admin/api/usage', readFixture('usage.json')).body as Any + expect(u.total.requestsPerDay).toBe(0) + expect(u.users.every((x: Any) => x.requestsPerDay === 0)).toBe(true) + }) + + it('limits-hot sets requestsPerMinute near limit for 3 friends users and adds rate_limit/paced events', () => { + const u = apply(['limits-hot'], '/admin/api/usage', readFixture('usage.json')).body as Any + const hot = u.users.filter((x: Any) => x.limits?.requestsPerMinute > 0 && x.requestsPerMinute >= x.limits.requestsPerMinute * 0.8) + expect(hot).toHaveLength(3) + for (const h of hot) { + expect(h.groupName).toBe('friends') + expect(h.requestsPerMinute).toBeLessThanOrEqual(h.limits.requestsPerMinute) + } + const e = apply(['limits-hot'], '/admin/api/events', readFixture('events__limit-200.json')).body as Any + const kinds = new Set(e.events.map((x: Any) => x.kind)) + expect(kinds.has('rate_limit')).toBe(true) + expect(kinds.has('paced')).toBe(true) + expect(e.events.filter((x: Any) => hot.some((h: Any) => h.id === x.user)).length).toBeGreaterThan(0) + }) + + it('huge triples providers and models with unique ids', () => { + const base = overview() + const o = apply(['huge'], '/admin/api/overview', base).body as Any + expect(o.providers).toHaveLength(base.providers.length * 3) + expect(new Set(o.providers.map((p: Any) => p.name)).size).toBe(o.providers.length) + for (const p of o.providers) expect(new Set(p.models).size).toBe(p.models.length) + expect(o.providers[0].models).toHaveLength(base.providers[0].models.length * 3) + const m = apply(['huge'], '/admin/api/usage/models', readFixture(manifest.find((x) => x.path.endsWith('/usage/models') && x.status === 200)!.file)).body as Any + expect(new Set(m.models.map((x: Any) => x.id)).size).toBe(m.models.length) + }) + + it('slow reports a 1500ms delay', () => { + expect(scenarioDelayMs(['slow'])).toBe(1500) + expect(scenarioDelayMs([])).toBe(0) + }) + + it('leaves non-matching paths and scenarios untouched', () => { + const body = { a: 1 } + expect(apply([], '/admin/api/overview', body)).toEqual({ status: 200, body }) + expect(apply(['live'], '/admin/api/config', body).body).toEqual(body) + }) +}) diff --git a/webui/vite.config.ts b/webui/vite.config.ts index 2b739b1..ba8a9b1 100644 --- a/webui/vite.config.ts +++ b/webui/vite.config.ts @@ -8,6 +8,11 @@ import vue from '@vitejs/plugin-vue' // vitest.config.ts or a triple-slash type reference. import { defineConfig } from 'vitest/config' +import { mockAdminApi } from './mock/server.ts' + +// MOCK=1 serves /admin/api/* from webui/mock (dev server only; apply: 'serve' keeps it out of vite build). +const useMock = process.env.MOCK === '1' + // https://vite.dev/config/ export default defineConfig({ // admin.go serves this build's index.html at GET /admin and every hashed @@ -15,7 +20,7 @@ export default defineConfig({ // emitted index.html's own