mirror of
https://github.com/lukaszraczylo/traefik-llmgateway.git
synced 2026-11-26 10:06:31 +00:00
feat(webui): overview page
This commit is contained in:
@@ -0,0 +1,100 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
import { deriveAttention } from './attention'
|
||||
import type { AttentionEvents, AttentionOverview, AttentionRouter, AttentionUsage } from './attention'
|
||||
import { formatSel } from './panel-selection'
|
||||
|
||||
const provider = (over: Partial<AttentionOverview['providers'][number]> = {}) => ({ name: 'uni', healthState: 'closed' as const, ...over })
|
||||
const overview = (over: Partial<AttentionOverview> = {}): AttentionOverview => ({
|
||||
providers: [provider()],
|
||||
pricing: { unpriced: 0 },
|
||||
redis: { configured: true },
|
||||
...over,
|
||||
})
|
||||
const usage: AttentionUsage = { users: [{ id: 'alice' }, { id: 'bob' }] }
|
||||
const events = (over: Partial<AttentionEvents> = {}): AttentionEvents => ({ source: 'redis', events: [], ...over })
|
||||
const router = (over: Partial<AttentionRouter> = {}): AttentionRouter => ({ name: 'auto', stats: { escalations: [] }, ...over })
|
||||
|
||||
describe('deriveAttention', () => {
|
||||
it('returns nothing when nothing is wrong', () => {
|
||||
expect(deriveAttention(overview(), usage, events(), [router()])).toEqual([])
|
||||
})
|
||||
|
||||
it('returns nothing before data loads', () => {
|
||||
expect(deriveAttention(null, null, null, [])).toEqual([])
|
||||
})
|
||||
|
||||
it('flags an open breaker as danger linking to the provider', () => {
|
||||
const items = deriveAttention(overview({ providers: [provider({ healthState: 'open' })] }), usage, events(), [])
|
||||
expect(items).toHaveLength(1)
|
||||
expect(items[0]).toMatchObject({ severity: 'danger', link: { page: 'models', sel: formatSel('provider', 'uni') } })
|
||||
expect(items[0]?.text).toContain('uni')
|
||||
})
|
||||
|
||||
it('flags a provider lastErr as danger with the provider sel and the reason', () => {
|
||||
const items = deriveAttention(overview({ providers: [provider({ lastErr: 'HTTP 401 unauthorized' })] }), usage, events(), [])
|
||||
expect(items).toHaveLength(1)
|
||||
expect(items[0]).toMatchObject({ severity: 'danger', link: { page: 'models', sel: formatSel('provider', 'uni') } })
|
||||
expect(items[0]?.text).toContain('HTTP 401 unauthorized')
|
||||
})
|
||||
|
||||
it('merges breaker and lastErr of one provider into a single item', () => {
|
||||
const items = deriveAttention(overview({ providers: [provider({ healthState: 'open', lastErr: 'boom' })] }), usage, events(), [])
|
||||
expect(items).toHaveLength(1)
|
||||
expect(items[0]?.text).toContain('boom')
|
||||
})
|
||||
|
||||
it('groups rate_limit events per user as a warning with the user sel', () => {
|
||||
const ev = events({
|
||||
events: [
|
||||
{ kind: 'rate_limit', user: 'alice' },
|
||||
{ kind: 'rate_limit', user: 'alice' },
|
||||
{ kind: 'rate_limit', user: 'bob' },
|
||||
{ kind: 'upstream', user: 'bob' },
|
||||
],
|
||||
})
|
||||
const items = deriveAttention(overview(), usage, ev, [])
|
||||
expect(items.map((i) => i.link.sel)).toEqual([formatSel('user', 'alice'), formatSel('user', 'bob')])
|
||||
expect(items[0]).toMatchObject({ severity: 'warning', link: { page: 'users' } })
|
||||
expect(items[0]?.text).toContain('2')
|
||||
})
|
||||
|
||||
it('links a throttled user that no longer exists to the directory without a sel', () => {
|
||||
const items = deriveAttention(overview(), usage, events({ events: [{ kind: 'rate_limit', user: 'ghost' }] }), [])
|
||||
expect(items[0]?.link).toEqual({ page: 'users' })
|
||||
})
|
||||
|
||||
it('flags unpriced models as info linking to usage', () => {
|
||||
const items = deriveAttention(overview({ pricing: { unpriced: 3 } }), usage, events(), [])
|
||||
expect(items).toEqual([{ severity: 'info', text: expect.stringContaining('3'), link: { page: 'usage' } }])
|
||||
})
|
||||
|
||||
it('flags a configured redis that is not the event source as danger', () => {
|
||||
const items = deriveAttention(overview(), usage, events({ source: 'replica' }), [])
|
||||
expect(items).toHaveLength(1)
|
||||
expect(items[0]).toMatchObject({ severity: 'danger', link: { page: 'config' } })
|
||||
expect(items[0]?.text).toMatch(/redis/i)
|
||||
})
|
||||
|
||||
it('does not flag replica events when redis is not configured', () => {
|
||||
expect(deriveAttention(overview({ redis: { configured: false } }), usage, events({ source: 'replica' }), [])).toEqual([])
|
||||
})
|
||||
|
||||
it('flags router escalations as info linking to the router', () => {
|
||||
const r = router({ stats: { escalations: [{ count: 4 }, { count: 1 }] } })
|
||||
const items = deriveAttention(overview(), usage, events(), [r])
|
||||
expect(items).toHaveLength(1)
|
||||
expect(items[0]).toMatchObject({ severity: 'info', link: { page: 'routers', sel: formatSel('router', 'auto') } })
|
||||
expect(items[0]?.text).toContain('5')
|
||||
})
|
||||
|
||||
it('orders danger before warning before info', () => {
|
||||
const items = deriveAttention(
|
||||
overview({ pricing: { unpriced: 1 }, providers: [provider({ healthState: 'open' })] }),
|
||||
usage,
|
||||
events({ events: [{ kind: 'rate_limit', user: 'alice' }] }),
|
||||
[],
|
||||
)
|
||||
expect(items.map((i) => i.severity)).toEqual(['danger', 'warning', 'info'])
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,98 @@
|
||||
import type { PageId } from '@/lib/pages'
|
||||
import { formatSel, PANEL_PAGE } from '@/lib/panel-selection'
|
||||
import type { PanelKind } from '@/lib/panel-selection'
|
||||
|
||||
export type AttentionSeverity = 'danger' | 'warning' | 'info'
|
||||
|
||||
export interface AttentionLink {
|
||||
page: PageId
|
||||
sel?: string
|
||||
}
|
||||
|
||||
export interface AttentionItem {
|
||||
severity: AttentionSeverity
|
||||
text: string
|
||||
link: AttentionLink
|
||||
}
|
||||
|
||||
export interface AttentionOverview {
|
||||
providers: Array<{ name: string; healthState: string; lastErr?: string }>
|
||||
pricing: { unpriced: number }
|
||||
redis: { configured: boolean; lastErr?: string }
|
||||
}
|
||||
export interface AttentionUsage {
|
||||
users: Array<{ id: string }>
|
||||
}
|
||||
export interface AttentionEvents {
|
||||
source: string
|
||||
events: Array<{ kind: string; user?: string }>
|
||||
}
|
||||
export interface AttentionRouter {
|
||||
name: string
|
||||
stats?: { escalations: Array<{ count: number }> }
|
||||
}
|
||||
|
||||
const SEVERITY_ORDER: Record<AttentionSeverity, number> = { danger: 0, warning: 1, info: 2 }
|
||||
|
||||
function panelLink(kind: PanelKind, id: string): AttentionLink {
|
||||
return { page: PANEL_PAGE[kind], sel: formatSel(kind, id) }
|
||||
}
|
||||
|
||||
function providerItems(overview: AttentionOverview): AttentionItem[] {
|
||||
const out: AttentionItem[] = []
|
||||
for (const p of overview.providers) {
|
||||
const open = p.healthState === 'open'
|
||||
if (!open && !p.lastErr) continue
|
||||
const text = open ? `${p.name} breaker open${p.lastErr ? `: ${p.lastErr}` : ''}` : `${p.name} failing: ${p.lastErr}`
|
||||
out.push({ severity: 'danger', text, link: panelLink('provider', p.name) })
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
function throttledUserItems(usage: AttentionUsage | null, events: AttentionEvents): AttentionItem[] {
|
||||
const counts = new Map<string, number>()
|
||||
for (const e of events.events) {
|
||||
if (e.kind === 'rate_limit' && e.user) counts.set(e.user, (counts.get(e.user) ?? 0) + 1)
|
||||
}
|
||||
const known = new Set((usage?.users ?? []).map((u) => u.id))
|
||||
return [...counts.entries()]
|
||||
.sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))
|
||||
.map(([user, n]) => ({
|
||||
severity: 'warning' as const,
|
||||
text: `${user} rate limited ${n} time${n === 1 ? '' : 's'}`,
|
||||
link: known.has(user) ? panelLink('user', user) : { page: 'users' as const },
|
||||
}))
|
||||
}
|
||||
|
||||
function routerItems(routers: AttentionRouter[]): AttentionItem[] {
|
||||
const out: AttentionItem[] = []
|
||||
for (const r of routers) {
|
||||
const n = (r.stats?.escalations ?? []).reduce((sum, e) => sum + e.count, 0)
|
||||
if (n > 0) out.push({ severity: 'info', text: `${r.name} escalated ${n} request${n === 1 ? '' : 's'} to a higher tier`, link: panelLink('router', r.name) })
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/** Lists what an operator should look at first, most severe first; empty when the fleet is healthy. */
|
||||
export function deriveAttention(
|
||||
overview: AttentionOverview | null,
|
||||
usage: AttentionUsage | null,
|
||||
events: AttentionEvents | null,
|
||||
routers: AttentionRouter[],
|
||||
): AttentionItem[] {
|
||||
const items: AttentionItem[] = []
|
||||
if (overview) {
|
||||
items.push(...providerItems(overview))
|
||||
if (overview.redis.configured && events && events.source !== 'redis') {
|
||||
const why = overview.redis.lastErr ? `: ${overview.redis.lastErr}` : ''
|
||||
items.push({ severity: 'danger', text: `Redis unreachable, events served from this replica only${why}`, link: { page: 'config' } })
|
||||
}
|
||||
if (overview.pricing.unpriced > 0) {
|
||||
const n = overview.pricing.unpriced
|
||||
items.push({ severity: 'info', text: `${n} unpriced model${n === 1 ? '' : 's'}, spend is understated`, link: { page: 'usage' } })
|
||||
}
|
||||
}
|
||||
if (events) items.push(...throttledUserItems(usage, events))
|
||||
items.push(...routerItems(routers))
|
||||
return items.sort((a, b) => SEVERITY_ORDER[a.severity] - SEVERITY_ORDER[b.severity])
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
import { countThrottled, deltaOf, rangeMs, sumPoints, trafficSeries } from './overview-metrics'
|
||||
|
||||
describe('sumPoints', () => {
|
||||
it('sums and ignores non-finite values', () => {
|
||||
expect(sumPoints([1, 2, 3])).toBe(6)
|
||||
expect(sumPoints([1, Number.NaN, 2])).toBe(3)
|
||||
expect(sumPoints([])).toBe(0)
|
||||
})
|
||||
})
|
||||
|
||||
describe('deltaOf', () => {
|
||||
it('is null without a previous value to compare against', () => {
|
||||
expect(deltaOf(10, 0)).toBeNull()
|
||||
expect(deltaOf(10, null)).toBeNull()
|
||||
})
|
||||
it('formats a signed whole percent with its trend', () => {
|
||||
expect(deltaOf(112, 100)).toEqual({ text: '+12%', trend: 'up' })
|
||||
expect(deltaOf(50, 100)).toEqual({ text: '-50%', trend: 'down' })
|
||||
})
|
||||
it('reads under half a percent as flat', () => {
|
||||
expect(deltaOf(100.2, 100)).toEqual({ text: '0%', trend: 'flat' })
|
||||
})
|
||||
it('caps absurd swings so the tile never overflows', () => {
|
||||
expect(deltaOf(100000, 1)?.text).toBe('+999%')
|
||||
})
|
||||
})
|
||||
|
||||
describe('rangeMs', () => {
|
||||
it('converts each window to milliseconds', () => {
|
||||
expect(rangeMs('hour', 24)).toBe(24 * 3_600_000)
|
||||
expect(rangeMs('day', 7)).toBe(7 * 86_400_000)
|
||||
expect(rangeMs('month', 3)).toBe(3 * 30 * 86_400_000)
|
||||
})
|
||||
})
|
||||
|
||||
describe('countThrottled', () => {
|
||||
const now = Date.parse('2026-11-25T12:00:00Z')
|
||||
const at = (minsAgo: number) => new Date(now - minsAgo * 60_000).toISOString()
|
||||
it('counts rate_limit and paced events inside the range only', () => {
|
||||
const events = [
|
||||
{ kind: 'rate_limit', time: at(5) },
|
||||
{ kind: 'rate_limit', time: at(10) },
|
||||
{ kind: 'paced', time: at(20) },
|
||||
{ kind: 'rate_limit', time: at(500) },
|
||||
{ kind: 'upstream', time: at(1) },
|
||||
]
|
||||
expect(countThrottled(events, now, 60 * 60_000)).toEqual({ rateLimited: 2, paced: 1 })
|
||||
})
|
||||
it('skips events with an unparseable time', () => {
|
||||
expect(countThrottled([{ kind: 'rate_limit', time: 'nope' }], now, 60_000)).toEqual({ rateLimited: 0, paced: 0 })
|
||||
})
|
||||
})
|
||||
|
||||
describe('trafficSeries', () => {
|
||||
const top = [
|
||||
{ scope: 'model:a/x', points: [1, 2] },
|
||||
{ scope: 'model:b/y', points: [3, 4] },
|
||||
]
|
||||
it('stacks the top models, then the remainder as Other', () => {
|
||||
const s = trafficSeries(top, [10, 10], null)
|
||||
expect(s.map((x) => x.name)).toEqual(['a/x', 'b/y', 'Other'])
|
||||
expect(s[2]?.data).toEqual([6, 4])
|
||||
expect(s.every((x) => x.stack === undefined)).toBe(true)
|
||||
})
|
||||
it('omits Other when the top models cover all traffic', () => {
|
||||
expect(trafficSeries(top, [4, 6], null).map((x) => x.name)).toEqual(['a/x', 'b/y'])
|
||||
})
|
||||
it('adds the previous period as an unstacked series when compare is on', () => {
|
||||
const s = trafficSeries(top, [10, 10], [7, 8])
|
||||
expect(s.at(-1)).toMatchObject({ name: 'Previous period', data: [7, 8], stack: false })
|
||||
})
|
||||
it('is empty without any traffic', () => {
|
||||
expect(trafficSeries([], [0, 0], null)).toEqual([])
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,72 @@
|
||||
import { scopeId } from '@/lib/scope'
|
||||
import { other } from '@/lib/series'
|
||||
import type { Series } from '@/lib/series'
|
||||
import type { HistoryWindow } from '@/types/api'
|
||||
|
||||
export type Trend = 'up' | 'down' | 'flat'
|
||||
|
||||
export interface Delta {
|
||||
text: string
|
||||
trend: Trend
|
||||
}
|
||||
|
||||
export interface ChartLine {
|
||||
name: string
|
||||
data: number[]
|
||||
tone?: 'muted' | 'primary'
|
||||
stack?: false
|
||||
}
|
||||
|
||||
const MS_PER_HOUR = 3_600_000
|
||||
const MS_PER_DAY = 24 * MS_PER_HOUR
|
||||
const DAYS_PER_MONTH = 30
|
||||
const FLAT_BELOW_PCT = 0.5
|
||||
const DELTA_CAP_PCT = 999
|
||||
|
||||
export function sumPoints(points: readonly number[]): number {
|
||||
let total = 0
|
||||
for (const p of points) if (Number.isFinite(p)) total += p
|
||||
return total
|
||||
}
|
||||
|
||||
/** Signed whole-percent change against the previous period; null when there is nothing to compare. */
|
||||
export function deltaOf(current: number, previous: number | null): Delta | null {
|
||||
if (previous === null || !(previous > 0) || !Number.isFinite(current)) return null
|
||||
const pct = ((current - previous) / previous) * 100
|
||||
if (Math.abs(pct) < FLAT_BELOW_PCT) return { text: '0%', trend: 'flat' }
|
||||
const capped = Math.min(DELTA_CAP_PCT, Math.max(-DELTA_CAP_PCT, Math.round(pct)))
|
||||
return { text: `${capped > 0 ? '+' : ''}${capped}%`, trend: capped > 0 ? 'up' : 'down' }
|
||||
}
|
||||
|
||||
export function rangeMs(window: HistoryWindow, span: number): number {
|
||||
if (window === 'hour') return span * MS_PER_HOUR
|
||||
if (window === 'day') return span * MS_PER_DAY
|
||||
return span * DAYS_PER_MONTH * MS_PER_DAY
|
||||
}
|
||||
|
||||
/** Counts rate_limit and paced events whose time falls inside the last `windowMs`. */
|
||||
export function countThrottled(
|
||||
events: ReadonlyArray<{ kind: string; time: string }>,
|
||||
now: number,
|
||||
windowMs: number,
|
||||
): { rateLimited: number; paced: number } {
|
||||
let rateLimited = 0
|
||||
let paced = 0
|
||||
for (const e of events) {
|
||||
const at = Date.parse(e.time)
|
||||
if (!Number.isFinite(at) || at < now - windowMs) continue
|
||||
if (e.kind === 'rate_limit') rateLimited++
|
||||
else if (e.kind === 'paced') paced++
|
||||
}
|
||||
return { rateLimited, paced }
|
||||
}
|
||||
|
||||
/** Stacked traffic lines: the top models, the remainder as Other, and optionally the previous period as a plain line. */
|
||||
export function trafficSeries(top: Series[], totalPoints: number[], previous: number[] | null): ChartLine[] {
|
||||
const lines: ChartLine[] = top.map((s) => ({ name: scopeId(s.scope), data: s.points }))
|
||||
const rest = other(totalPoints, top)
|
||||
if (rest.some((v) => v > 0)) lines.push({ name: 'Other', data: rest, tone: 'muted' })
|
||||
if (lines.length === 0) return []
|
||||
if (previous) lines.push({ name: 'Previous period', data: previous, tone: 'primary', stack: false })
|
||||
return lines
|
||||
}
|
||||
Reference in New Issue
Block a user