mirror of
https://github.com/lukaszraczylo/traefik-llmgateway.git
synced 2026-11-26 10:06:31 +00:00
feat(webui): mock admin API with scenarios for local development
Serve captured fixtures from the Vite dev server under MOCK=1. Synthesise missing ranges from the nearest fixture and select failure scenarios with ?mock=.
This commit is contained in:
@@ -0,0 +1,169 @@
|
||||
import { WINDOW_HOURS, type MockWindow } from './time-shift.ts'
|
||||
|
||||
export interface Fixture {
|
||||
file: string
|
||||
path: string
|
||||
query: Record<string, string | string[]>
|
||||
status: number
|
||||
}
|
||||
|
||||
/** Query params that decide which fixture answers; anything else (limit, cache busters) never affects matching. */
|
||||
const SIGNIFICANT: Record<string, string[]> = {
|
||||
'/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<string, string[]> = {
|
||||
'/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<string, number> = {
|
||||
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<string, string[]>
|
||||
|
||||
export function normaliseQuery(path: string, query: URLSearchParams | Record<string, string | string[]>): 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
|
||||
}
|
||||
@@ -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<string, any> // 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<string, number> = { 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) }
|
||||
}
|
||||
@@ -0,0 +1,297 @@
|
||||
type Obj = Record<string, any> // 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 = <T>(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 }
|
||||
}
|
||||
@@ -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)`)
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -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<string, any> // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
|
||||
const COUNT_KEYS = ['count', 'attempts', 'failures', 'timeouts', 'failovers']
|
||||
const MODEL_FIELDS: Record<string, string> = { 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<number>(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 }
|
||||
}
|
||||
@@ -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<MockWindow, number> = { 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<number, MockWindow> = { 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<string, unknown> = {}
|
||||
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, '')
|
||||
}
|
||||
Reference in New Issue
Block a user