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:
+1
-1
@@ -44,7 +44,7 @@ function lazyPage(loader: () => Promise<Component>): Component {
|
|||||||
// Legacy pages stand in until their redesigned replacements land: routers
|
// Legacy pages stand in until their redesigned replacements land: routers
|
||||||
// still lives inside the Models page and events inside Reliability.
|
// still lives inside the Models page and events inside Reliability.
|
||||||
const PAGES: Record<PageId, Component> = {
|
const PAGES: Record<PageId, Component> = {
|
||||||
overview: lazyPage(() => import('@/pages/HomePage.vue')),
|
overview: lazyPage(() => import('@/pages/OverviewPage.vue')),
|
||||||
usage: lazyPage(() => import('@/pages/SpendPage.vue')),
|
usage: lazyPage(() => import('@/pages/SpendPage.vue')),
|
||||||
reliability: lazyPage(() => import('@/pages/ReliabilityPage.vue')),
|
reliability: lazyPage(() => import('@/pages/ReliabilityPage.vue')),
|
||||||
users: lazyPage(() => import('@/pages/ConsumersPage.vue')),
|
users: lazyPage(() => import('@/pages/ConsumersPage.vue')),
|
||||||
|
|||||||
@@ -0,0 +1,26 @@
|
|||||||
|
import type { AttentionLink } from '@/lib/attention'
|
||||||
|
import { PANEL_PAGE, parseSel } from '@/lib/panel-selection'
|
||||||
|
import type { PanelKind } from '@/lib/panel-selection'
|
||||||
|
import { useNavStore } from '@/stores/nav'
|
||||||
|
|
||||||
|
/** Navigation helpers for rows that link to a directory page or one of its detail panels. */
|
||||||
|
export function useEntityLinks() {
|
||||||
|
const nav = useNavStore()
|
||||||
|
|
||||||
|
function openEntity(kind: PanelKind, id: string): void {
|
||||||
|
nav.goTo(PANEL_PAGE[kind])
|
||||||
|
nav.openPanel(kind, id)
|
||||||
|
}
|
||||||
|
|
||||||
|
function openLink(link: AttentionLink): void {
|
||||||
|
const sel = parseSel(link.sel)
|
||||||
|
if (!sel) {
|
||||||
|
nav.goTo(link.page, {}, { replace: false })
|
||||||
|
return
|
||||||
|
}
|
||||||
|
nav.goTo(link.page)
|
||||||
|
nav.openPanel(sel.kind, sel.id)
|
||||||
|
}
|
||||||
|
|
||||||
|
return { openEntity, openLink }
|
||||||
|
}
|
||||||
@@ -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
|
||||||
|
}
|
||||||
@@ -0,0 +1,336 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { ActivityFeed, Button, Card, CardAction, CardContent, CardHeader, CardTitle, KpiTile, LineChart, StatGroup } from '@perfect-design/ui'
|
||||||
|
import type { ActivityEvent } from '@perfect-design/ui'
|
||||||
|
import { computed, onMounted, onUnmounted, watch } from 'vue'
|
||||||
|
|
||||||
|
import { useEntityLinks } from '@/composables/useEntityLinks'
|
||||||
|
import { deriveAttention } from '@/lib/attention'
|
||||||
|
import { eventKindVariant, kindLabel } from '@/lib/events-filter'
|
||||||
|
import { formatBucketLabel, formatCompactCount, formatCostDisplay } from '@/lib/format'
|
||||||
|
import { errorRateTier, fleetErrorRate } from '@/lib/kpi'
|
||||||
|
import { loadState } from '@/lib/load-state'
|
||||||
|
import { countThrottled, deltaOf, rangeMs, sumPoints, trafficSeries } from '@/lib/overview-metrics'
|
||||||
|
import { formatErrorRatePercent } from '@/lib/provider-rate'
|
||||||
|
import { TOP_USERS_RANK_LIMIT, rankTopUsers } from '@/lib/top-users'
|
||||||
|
import { wbColumns } from '@/lib/wb-columns'
|
||||||
|
import { useDashboardStore } from '@/stores/dashboard'
|
||||||
|
import { useEventsStore } from '@/stores/events'
|
||||||
|
import { useFiltersStore } from '@/stores/filters'
|
||||||
|
import { useNavStore } from '@/stores/nav'
|
||||||
|
import { useOverviewStore } from '@/stores/overview'
|
||||||
|
import HealthStrip from '@/widgets/HealthStrip.vue'
|
||||||
|
import NeedsAttention from '@/widgets/NeedsAttention.vue'
|
||||||
|
import StateView from '@/widgets/StateView.vue'
|
||||||
|
import type { ViewState } from '@/widgets/StateView.vue'
|
||||||
|
import WbTable from '@/widgets/WbTable.vue'
|
||||||
|
|
||||||
|
const EVENT_ROWS = 8
|
||||||
|
const MIN_SPARK_POINTS = 2
|
||||||
|
|
||||||
|
type FeedTone = NonNullable<ActivityEvent['tone']>
|
||||||
|
const EVENT_TONE: Record<string, FeedTone> = { rate_limit: 'warning', budget: 'warning', timeout: 'warning', capacity: 'warning', store_down: 'danger', upstream: 'danger', unpriced: 'info', paced: 'info' }
|
||||||
|
|
||||||
|
interface RankRow {
|
||||||
|
id: string
|
||||||
|
name: string
|
||||||
|
value: number
|
||||||
|
share: number | null
|
||||||
|
}
|
||||||
|
|
||||||
|
const dashboard = useDashboardStore()
|
||||||
|
const events = useEventsStore()
|
||||||
|
const filters = useFiltersStore()
|
||||||
|
const nav = useNavStore()
|
||||||
|
const data = useOverviewStore()
|
||||||
|
const { openEntity } = useEntityLinks()
|
||||||
|
|
||||||
|
const overview = computed(() => dashboard.overview)
|
||||||
|
const pageState = computed<ViewState>(() => {
|
||||||
|
const s = loadState({ loading: true, hasData: dashboard.overview !== null && dashboard.usage !== null, error: dashboard.error })
|
||||||
|
return s === 'skeleton' ? 'loading' : s === 'ready' ? 'ready' : 'error'
|
||||||
|
})
|
||||||
|
|
||||||
|
function sectionState(loaded: boolean, error: string, empty: boolean): ViewState {
|
||||||
|
if (loaded) return empty ? 'empty' : 'ready'
|
||||||
|
return error ? 'error' : 'loading'
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Health + attention ---------------------------------------------------
|
||||||
|
|
||||||
|
const eventsSource = computed(() => (events.lastUpdated ? events.source : null))
|
||||||
|
const attention = computed(() =>
|
||||||
|
deriveAttention(
|
||||||
|
overview.value,
|
||||||
|
dashboard.usage,
|
||||||
|
events.lastUpdated ? { source: events.source, events: events.events } : null,
|
||||||
|
overview.value?.routers ?? [],
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
// --- KPI tiles --------------------------------------------------------------
|
||||||
|
|
||||||
|
const trafficPending = computed(() => !data.trafficLoaded && !data.error.traffic)
|
||||||
|
const rangeLabel = computed(() => `last ${filters.range}`)
|
||||||
|
|
||||||
|
function kpi(points: number[], previous: number[] | undefined) {
|
||||||
|
const total = data.trafficLoaded ? sumPoints(points) : null
|
||||||
|
const delta = total !== null && previous ? deltaOf(total, sumPoints(previous)) : null
|
||||||
|
return { total, delta, spark: points.length >= MIN_SPARK_POINTS && points.some((v) => v > 0) ? points : undefined }
|
||||||
|
}
|
||||||
|
|
||||||
|
const requests = computed(() => kpi(data.totals.req, data.previous?.req))
|
||||||
|
const tokensIn = computed(() => kpi(data.totals.tokin, data.previous?.tokin))
|
||||||
|
const spend = computed(() => kpi(data.totals.cost, data.previous?.cost))
|
||||||
|
const tokensOut = computed(() => (data.trafficLoaded ? sumPoints(data.totals.tokout) : null))
|
||||||
|
const monthSpend = computed(() => dashboard.usage?.total.costPerMonthMicroUsd ?? null)
|
||||||
|
|
||||||
|
const errorRate = computed(() => fleetErrorRate(overview.value?.providers ?? []))
|
||||||
|
const errorTone = computed(() => ({ ok: undefined, warn: 'warning', critical: 'danger' }) as const)
|
||||||
|
const throttled = computed(() => countThrottled(events.events, Date.now(), rangeMs(filters.window, filters.span)))
|
||||||
|
const throttledTotal = computed(() => (events.lastUpdated ? throttled.value.rateLimited + throttled.value.paced : null))
|
||||||
|
|
||||||
|
const count = (n: number | null) => (n === null ? null : formatCompactCount(n))
|
||||||
|
|
||||||
|
// --- Traffic chart ----------------------------------------------------------
|
||||||
|
|
||||||
|
const lines = computed(() => trafficSeries(data.topModelSeries, data.totals.req, filters.cmpSpec.requested ? (data.previous?.req ?? null) : null))
|
||||||
|
const labels = computed(() => data.buckets.map((b) => formatBucketLabel(b, filters.window)))
|
||||||
|
const trafficState = computed(() => sectionState(data.trafficLoaded, data.error.traffic, lines.value.length === 0))
|
||||||
|
|
||||||
|
// --- Top lists --------------------------------------------------------------
|
||||||
|
|
||||||
|
const userColumns = wbColumns<RankRow>([
|
||||||
|
{ key: 'name', header: 'User', kind: 'text', sortable: false },
|
||||||
|
{ key: 'value', header: 'Requests', kind: 'number', sortable: false },
|
||||||
|
{ key: 'share', header: 'Share', kind: 'share', sortable: false },
|
||||||
|
])
|
||||||
|
const modelColumns = wbColumns<RankRow>([
|
||||||
|
{ key: 'name', header: 'Model', kind: 'text', sortable: false },
|
||||||
|
{ key: 'value', header: 'Spend', kind: 'number', sortable: false },
|
||||||
|
{ key: 'share', header: 'Share', kind: 'share', sortable: false },
|
||||||
|
])
|
||||||
|
|
||||||
|
function share(value: number, total: number): number | null {
|
||||||
|
return total > 0 ? Math.min(1, value / total) : null
|
||||||
|
}
|
||||||
|
|
||||||
|
const topUsers = computed<RankRow[]>(() => {
|
||||||
|
const total = sumPoints(data.totals.req)
|
||||||
|
return rankTopUsers(data.topUserRows, 'req', TOP_USERS_RANK_LIMIT).map((r) => ({ id: r.id, name: r.id, value: r.value, share: share(r.value, total) }))
|
||||||
|
})
|
||||||
|
const topModels = computed<RankRow[]>(() => {
|
||||||
|
const total = sumPoints(data.totals.cost)
|
||||||
|
return data.topModelsByCost.filter((m) => m.value > 0).map((m) => ({ id: m.id, name: m.id, value: m.value, share: share(m.value, total) }))
|
||||||
|
})
|
||||||
|
const usersState = computed(() => sectionState(data.usersLoaded, data.error.users, topUsers.value.length === 0))
|
||||||
|
const modelsState = computed(() => sectionState(data.modelsLoaded, data.error.models, topModels.value.length === 0))
|
||||||
|
|
||||||
|
// --- Recent events ----------------------------------------------------------
|
||||||
|
|
||||||
|
const feed = computed<ActivityEvent[]>(() =>
|
||||||
|
events.events.slice(0, EVENT_ROWS).map((e, i) => ({
|
||||||
|
id: `${e.time}-${e.replica}-${i}`,
|
||||||
|
actor: e.user,
|
||||||
|
action: `${kindLabel(e.kind)}: ${e.message}`,
|
||||||
|
time: e.time,
|
||||||
|
tone: EVENT_TONE[e.kind] ?? (eventKindVariant(e.kind) === 'destructive' ? 'danger' : 'neutral'),
|
||||||
|
details: [e.provider, e.model, e.route].filter(Boolean).join(' · ') || e.route,
|
||||||
|
})),
|
||||||
|
)
|
||||||
|
const eventsState = computed<ViewState>(() => {
|
||||||
|
const s = loadState({ loading: events.refreshing, hasData: events.lastUpdated !== null, error: events.error })
|
||||||
|
if (s === 'ready') return feed.value.length === 0 ? 'empty' : 'ready'
|
||||||
|
return s === 'skeleton' ? 'loading' : s === 'error' ? 'error' : 'empty'
|
||||||
|
})
|
||||||
|
const eventById = computed(() => new Map(feed.value.map((f, i) => [f.id, events.events[i]])))
|
||||||
|
|
||||||
|
function eventLinks(id: string | number): Array<{ label: string; open: () => void }> {
|
||||||
|
const e = eventById.value.get(String(id))
|
||||||
|
if (!e) return []
|
||||||
|
const out: Array<{ label: string; open: () => void }> = []
|
||||||
|
if (e.user) out.push({ label: `Open ${e.user}`, open: () => openEntity('user', e.user as string) })
|
||||||
|
if (e.provider) out.push({ label: `Open ${e.provider}`, open: () => openEntity('provider', e.provider as string) })
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Lifecycle --------------------------------------------------------------
|
||||||
|
|
||||||
|
watch(
|
||||||
|
() => [filters.range, filters.cmp],
|
||||||
|
() => void data.refresh(),
|
||||||
|
)
|
||||||
|
onMounted(() => {
|
||||||
|
events.startPolling()
|
||||||
|
data.startPolling()
|
||||||
|
})
|
||||||
|
onUnmounted(() => {
|
||||||
|
events.stopPolling()
|
||||||
|
data.stopPolling()
|
||||||
|
})
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<StateView
|
||||||
|
:state="pageState"
|
||||||
|
:updated-at="dashboard.lastUpdated"
|
||||||
|
error-title="Could not load the overview"
|
||||||
|
:error-message="dashboard.error"
|
||||||
|
@retry="dashboard.refresh()"
|
||||||
|
>
|
||||||
|
<div v-if="overview" class="flex flex-col gap-4">
|
||||||
|
<HealthStrip :providers="overview.providers" :redis="overview.redis" :events-source="eventsSource" />
|
||||||
|
|
||||||
|
<StatGroup :columns="5" gap="sm" aria-label="Key metrics">
|
||||||
|
<KpiTile
|
||||||
|
label="Requests"
|
||||||
|
size="compact"
|
||||||
|
:value="count(requests.total)"
|
||||||
|
:loading="trafficPending"
|
||||||
|
:delta="requests.delta?.text"
|
||||||
|
:trend="requests.delta?.trend"
|
||||||
|
good-when="none"
|
||||||
|
:sparkline="requests.spark"
|
||||||
|
:hint="rangeLabel"
|
||||||
|
/>
|
||||||
|
<KpiTile
|
||||||
|
label="Input tokens"
|
||||||
|
size="compact"
|
||||||
|
:value="count(tokensIn.total)"
|
||||||
|
:loading="trafficPending"
|
||||||
|
:delta="tokensIn.delta?.text"
|
||||||
|
:trend="tokensIn.delta?.trend"
|
||||||
|
good-when="none"
|
||||||
|
:sparkline="tokensIn.spark"
|
||||||
|
:hint="tokensOut === null ? rangeLabel : `${formatCompactCount(tokensOut)} output`"
|
||||||
|
/>
|
||||||
|
<KpiTile
|
||||||
|
label="Spend"
|
||||||
|
size="compact"
|
||||||
|
:value="spend.total === null ? null : formatCostDisplay(spend.total)"
|
||||||
|
:loading="trafficPending"
|
||||||
|
:delta="spend.delta?.text"
|
||||||
|
:trend="spend.delta?.trend"
|
||||||
|
good-when="down"
|
||||||
|
:sparkline="spend.spark"
|
||||||
|
:hint="monthSpend === null ? rangeLabel : `${formatCostDisplay(monthSpend)} this month`"
|
||||||
|
/>
|
||||||
|
<KpiTile
|
||||||
|
label="Error rate"
|
||||||
|
size="compact"
|
||||||
|
:value="formatErrorRatePercent(errorRate.rate, 'no traffic')"
|
||||||
|
:tone="errorTone[errorRateTier(errorRate.rate)]"
|
||||||
|
good-when="down"
|
||||||
|
:hint="`${errorRate.failures}/${errorRate.attempts} attempts, last minute`"
|
||||||
|
/>
|
||||||
|
<KpiTile
|
||||||
|
label="Throttled"
|
||||||
|
size="compact"
|
||||||
|
:value="count(throttledTotal)"
|
||||||
|
:loading="events.lastUpdated === null && !events.error"
|
||||||
|
good-when="down"
|
||||||
|
:hint="`${throttled.rateLimited} rate limited · ${throttled.paced} paced`"
|
||||||
|
/>
|
||||||
|
</StatGroup>
|
||||||
|
|
||||||
|
<div class="grid grid-cols-1 gap-4 lg:grid-cols-[minmax(0,1fr)_minmax(0,22rem)]">
|
||||||
|
<Card size="sm">
|
||||||
|
<CardHeader><CardTitle>Traffic by model</CardTitle></CardHeader>
|
||||||
|
<CardContent>
|
||||||
|
<StateView
|
||||||
|
:state="trafficState"
|
||||||
|
empty-title="No traffic in this range"
|
||||||
|
:error-message="data.error.traffic"
|
||||||
|
@retry="data.refresh()"
|
||||||
|
>
|
||||||
|
<div data-wb-ignore-numeric>
|
||||||
|
<LineChart
|
||||||
|
:labels="labels"
|
||||||
|
:series="lines"
|
||||||
|
variant="area"
|
||||||
|
stacked
|
||||||
|
:height="240"
|
||||||
|
:value-formatter="formatCompactCount"
|
||||||
|
label="Requests per bucket by model"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</StateView>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
<Card size="sm">
|
||||||
|
<CardHeader><CardTitle>Needs attention</CardTitle></CardHeader>
|
||||||
|
<CardContent><NeedsAttention :items="attention" /></CardContent>
|
||||||
|
</Card>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="grid grid-cols-1 items-start gap-4 lg:grid-cols-3">
|
||||||
|
<Card size="sm">
|
||||||
|
<CardHeader>
|
||||||
|
<CardTitle>Top users</CardTitle>
|
||||||
|
<CardAction><Button variant="ghost" size="sm" @click="nav.goTo('users', {}, { replace: false })">View all</Button></CardAction>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent>
|
||||||
|
<StateView
|
||||||
|
:state="usersState"
|
||||||
|
empty-title="No user traffic in this range"
|
||||||
|
:error-message="data.error.users"
|
||||||
|
:retryable="data.usersLoaded || data.error.users !== ''"
|
||||||
|
@retry="data.refresh()"
|
||||||
|
>
|
||||||
|
<WbTable
|
||||||
|
:columns="userColumns"
|
||||||
|
:rows="topUsers"
|
||||||
|
row-key="id"
|
||||||
|
label="Top users by requests"
|
||||||
|
@row-activate="(row: RankRow) => openEntity('user', row.id)"
|
||||||
|
>
|
||||||
|
<template #cell-value="{ value }">{{ formatCompactCount(value as number) }}</template>
|
||||||
|
</WbTable>
|
||||||
|
</StateView>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
<Card size="sm">
|
||||||
|
<CardHeader>
|
||||||
|
<CardTitle>Top models</CardTitle>
|
||||||
|
<CardAction><Button variant="ghost" size="sm" @click="nav.goTo('models', {}, { replace: false })">View all</Button></CardAction>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent>
|
||||||
|
<StateView
|
||||||
|
:state="modelsState"
|
||||||
|
empty-title="No model spend in this range"
|
||||||
|
:error-message="data.error.models"
|
||||||
|
@retry="data.refresh()"
|
||||||
|
>
|
||||||
|
<WbTable
|
||||||
|
:columns="modelColumns"
|
||||||
|
:rows="topModels"
|
||||||
|
row-key="id"
|
||||||
|
label="Top models by spend"
|
||||||
|
@row-activate="(row: RankRow) => openEntity('model', row.id)"
|
||||||
|
>
|
||||||
|
<template #cell-value="{ value }">{{ formatCostDisplay(value as number) }}</template>
|
||||||
|
</WbTable>
|
||||||
|
</StateView>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
<Card size="sm">
|
||||||
|
<CardHeader>
|
||||||
|
<CardTitle>Recent events</CardTitle>
|
||||||
|
<CardAction><Button variant="ghost" size="sm" @click="nav.goTo('events', {}, { replace: false })">View all</Button></CardAction>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent>
|
||||||
|
<StateView :state="eventsState" empty-title="No events recorded" :error-message="events.error" @retry="events.refresh()">
|
||||||
|
<ActivityFeed :events="feed" label="Recent events" variant="compact" size="sm" density="compact">
|
||||||
|
<template #details="{ event }">
|
||||||
|
<p class="text-muted-foreground m-0 text-xs">{{ event.details }}</p>
|
||||||
|
<div class="flex flex-wrap gap-2 pt-1">
|
||||||
|
<Button v-for="l in eventLinks(event.id)" :key="l.label" variant="outline" size="sm" @click="l.open()">{{ l.label }}</Button>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
</ActivityFeed>
|
||||||
|
</StateView>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</StateView>
|
||||||
|
</template>
|
||||||
@@ -0,0 +1,81 @@
|
|||||||
|
import { createPinia, setActivePinia } from 'pinia'
|
||||||
|
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||||
|
|
||||||
|
vi.mock('@/lib/api', async () => {
|
||||||
|
const actual = await vi.importActual<typeof import('@/lib/api')>('@/lib/api')
|
||||||
|
return { ...actual, adminFetch: vi.fn() }
|
||||||
|
})
|
||||||
|
|
||||||
|
import { adminFetch } from '@/lib/api'
|
||||||
|
import { useAuthStore } from '@/stores/auth'
|
||||||
|
import { useFiltersStore } from '@/stores/filters'
|
||||||
|
import { useOverviewStore } from '@/stores/overview'
|
||||||
|
|
||||||
|
const mocked = vi.mocked(adminFetch)
|
||||||
|
|
||||||
|
function route(url: string): unknown {
|
||||||
|
const u = new URL(url, 'http://x')
|
||||||
|
const q = u.searchParams
|
||||||
|
if (u.pathname.endsWith('/usage/series')) {
|
||||||
|
const scopes = q.getAll('scope')
|
||||||
|
const off = q.get('offset') ? 100 : 0
|
||||||
|
return { metric: q.get('metric'), buckets: ['a', 'b'], series: scopes.map((scope) => ({ scope, points: [1 + off, 2 + off] })), unknown: [] }
|
||||||
|
}
|
||||||
|
if (u.pathname.endsWith('/usage/models')) return { models: [{ id: 'p/m1', value: 5 }, { id: 'p/m2', value: 3 }] }
|
||||||
|
if (u.pathname.endsWith('/usage/totals')) return { rows: [{ id: 'alice', values: { req: 9 } }] }
|
||||||
|
throw new Error(`unexpected ${url}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('useOverviewStore.refresh', () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
setActivePinia(createPinia())
|
||||||
|
mocked.mockReset()
|
||||||
|
mocked.mockImplementation(async (url: string) => route(url) as never)
|
||||||
|
useAuthStore().submit('test-admin-key')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('loads totals, top models and top users for the range', async () => {
|
||||||
|
const s = useOverviewStore()
|
||||||
|
await s.refresh()
|
||||||
|
expect(s.totals.req).toEqual([1, 2])
|
||||||
|
expect(s.topModelSeries.map((m) => m.scope)).toEqual(['model:p/m1', 'model:p/m2'])
|
||||||
|
expect(s.topModelsByCost.map((m) => m.id)).toEqual(['p/m1', 'p/m2'])
|
||||||
|
expect(s.topUserRows).toHaveLength(1)
|
||||||
|
expect(s.previous).toBeNull()
|
||||||
|
expect(s.error).toEqual({ traffic: '', models: '', users: '' })
|
||||||
|
expect(s.lastUpdated).not.toBeNull()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('fetches the previous period only when compare is requested', async () => {
|
||||||
|
useFiltersStore().cmp = 'prev'
|
||||||
|
const s = useOverviewStore()
|
||||||
|
await s.refresh()
|
||||||
|
expect(s.previous?.req).toEqual([101, 102])
|
||||||
|
expect(mocked.mock.calls.some(([u]) => String(u).includes('offset='))).toBe(true)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('keeps the last good data and records the error when a group fails', async () => {
|
||||||
|
const s = useOverviewStore()
|
||||||
|
await s.refresh()
|
||||||
|
mocked.mockImplementation(async (url: string) => {
|
||||||
|
if (url.includes('/usage/totals')) throw new Error('503')
|
||||||
|
return route(url) as never
|
||||||
|
})
|
||||||
|
await s.refresh()
|
||||||
|
expect(s.error.users).toContain('503')
|
||||||
|
expect(s.topUserRows).toHaveLength(1)
|
||||||
|
expect(s.totals.req).toEqual([1, 2])
|
||||||
|
})
|
||||||
|
|
||||||
|
it('drops the old selection when the range changes', async () => {
|
||||||
|
const s = useOverviewStore()
|
||||||
|
await s.refresh()
|
||||||
|
mocked.mockImplementation(async () => {
|
||||||
|
throw new Error('503')
|
||||||
|
})
|
||||||
|
useFiltersStore().range = '24h'
|
||||||
|
await s.refresh()
|
||||||
|
expect(s.totals.req).toEqual([])
|
||||||
|
expect(s.error.traffic).toContain('503')
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -0,0 +1,136 @@
|
|||||||
|
import { defineStore } from 'pinia'
|
||||||
|
|
||||||
|
import { adminFetch, isAuthRejection, messageOf } from '@/lib/api'
|
||||||
|
import { createVisibilityPoller } from '@/lib/polling'
|
||||||
|
import type { VisibilityPoller } from '@/lib/polling'
|
||||||
|
import { seriesUrl } from '@/lib/range'
|
||||||
|
import { TOP_USERS_METRICS_BY_MODE, topUsersCapCheckResult, topUsersTotalsUrl } from '@/lib/top-users'
|
||||||
|
import type { Series } from '@/lib/series'
|
||||||
|
import { useAuthStore } from '@/stores/auth'
|
||||||
|
import { useDashboardStore } from '@/stores/dashboard'
|
||||||
|
import { useFiltersStore } from '@/stores/filters'
|
||||||
|
import type { AdminSeriesResponse, AdminTotalsResponse, AdminUsageModelsResponse, HistoryMetric, HistoryWindow } from '@/types/api'
|
||||||
|
|
||||||
|
const REFRESH_MS = 60_000
|
||||||
|
const TOP_N = 5
|
||||||
|
const TOTAL_SCOPE = 'total'
|
||||||
|
const TOTAL_METRICS = ['req', 'tokin', 'tokout', 'cost'] as const
|
||||||
|
const COMPARED_METRICS = ['req', 'tokin', 'cost'] as const
|
||||||
|
|
||||||
|
type TotalMetric = (typeof TOTAL_METRICS)[number]
|
||||||
|
type Points = Record<TotalMetric, number[]>
|
||||||
|
|
||||||
|
const emptyPoints = (): Points => ({ req: [], tokin: [], tokout: [], cost: [] })
|
||||||
|
const emptyError = () => ({ traffic: '', models: '', users: '' })
|
||||||
|
|
||||||
|
export const RANGE_TOO_LARGE = 'Too many configured users to rank for this range. Pick a shorter range.'
|
||||||
|
|
||||||
|
export const useOverviewStore = defineStore('overview', {
|
||||||
|
state: () => ({
|
||||||
|
buckets: [] as string[],
|
||||||
|
totals: emptyPoints(),
|
||||||
|
previous: null as Pick<Points, 'req' | 'tokin' | 'cost'> | null,
|
||||||
|
topModelSeries: [] as Series[],
|
||||||
|
topModelsByCost: [] as AdminUsageModelsResponse['models'],
|
||||||
|
topUserRows: [] as AdminTotalsResponse['rows'],
|
||||||
|
trafficLoaded: false,
|
||||||
|
modelsLoaded: false,
|
||||||
|
usersLoaded: false,
|
||||||
|
error: emptyError(),
|
||||||
|
lastUpdated: null as Date | null,
|
||||||
|
fetchedFor: '',
|
||||||
|
reqId: 0,
|
||||||
|
poller: undefined as VisibilityPoller | undefined,
|
||||||
|
}),
|
||||||
|
actions: {
|
||||||
|
async refresh(): Promise<void> {
|
||||||
|
if (!useAuthStore().isAuthenticated) return
|
||||||
|
const filters = useFiltersStore()
|
||||||
|
const key = `${filters.window}:${filters.span}:${filters.cmpSpec.requested}`
|
||||||
|
if (key !== this.fetchedFor) this.clearData()
|
||||||
|
this.fetchedFor = key
|
||||||
|
const id = ++this.reqId
|
||||||
|
const { window, span } = filters
|
||||||
|
const offset = filters.cmpSpec.requested ? filters.cmpSpec.offset : 0
|
||||||
|
await Promise.all([this.loadTraffic(id, window, span, offset), this.loadModels(id, window, span), this.loadUsers(id, window, span)])
|
||||||
|
if (id === this.reqId) this.lastUpdated = new Date()
|
||||||
|
},
|
||||||
|
clearData(): void {
|
||||||
|
this.buckets = []
|
||||||
|
this.totals = emptyPoints()
|
||||||
|
this.previous = null
|
||||||
|
this.topModelSeries = []
|
||||||
|
this.topModelsByCost = []
|
||||||
|
this.topUserRows = []
|
||||||
|
this.trafficLoaded = this.modelsLoaded = this.usersLoaded = false
|
||||||
|
this.error = emptyError()
|
||||||
|
},
|
||||||
|
async series(scope: string[], metric: HistoryMetric, window: HistoryWindow, span: number, offset: number): Promise<AdminSeriesResponse> {
|
||||||
|
return adminFetch<AdminSeriesResponse>(seriesUrl({ scope, metric, window, span, offset: offset || undefined }))
|
||||||
|
},
|
||||||
|
async loadTraffic(id: number, window: HistoryWindow, span: number, offset: number): Promise<void> {
|
||||||
|
try {
|
||||||
|
const totalOf = async (metric: HistoryMetric, off: number) => {
|
||||||
|
const res = await this.series([TOTAL_SCOPE], metric, window, span, off)
|
||||||
|
return { buckets: res.buckets, points: res.series.find((s) => s.scope === TOTAL_SCOPE)?.points ?? [] }
|
||||||
|
}
|
||||||
|
const current = await Promise.all(TOTAL_METRICS.map((m) => totalOf(m, 0)))
|
||||||
|
const prior = offset > 0 ? await Promise.all(COMPARED_METRICS.map((m) => totalOf(m, offset))) : null
|
||||||
|
const ranking = await adminFetch<AdminUsageModelsResponse>(
|
||||||
|
`/admin/api/usage/models?metric=req&window=${window}&span=${span}&limit=${TOP_N}`,
|
||||||
|
)
|
||||||
|
const scopes = ranking.models.map((m) => `model:${m.id}`)
|
||||||
|
const top = scopes.length > 0 ? (await this.series(scopes, 'req', window, span, 0)).series : []
|
||||||
|
if (id !== this.reqId) return
|
||||||
|
this.buckets = current[0]?.buckets ?? []
|
||||||
|
this.totals = { req: current[0]!.points, tokin: current[1]!.points, tokout: current[2]!.points, cost: current[3]!.points }
|
||||||
|
this.previous = prior ? { req: prior[0]!.points, tokin: prior[1]!.points, cost: prior[2]!.points } : null
|
||||||
|
this.topModelSeries = top
|
||||||
|
this.trafficLoaded = true
|
||||||
|
this.error.traffic = ''
|
||||||
|
} catch (err) {
|
||||||
|
if (id === this.reqId && !isAuthRejection(err)) this.error.traffic = messageOf(err)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
async loadModels(id: number, window: HistoryWindow, span: number): Promise<void> {
|
||||||
|
try {
|
||||||
|
const res = await adminFetch<AdminUsageModelsResponse>(
|
||||||
|
`/admin/api/usage/models?metric=cost&window=${window}&span=${span}&limit=${TOP_N}`,
|
||||||
|
)
|
||||||
|
if (id !== this.reqId) return
|
||||||
|
this.topModelsByCost = res.models
|
||||||
|
this.modelsLoaded = true
|
||||||
|
this.error.models = ''
|
||||||
|
} catch (err) {
|
||||||
|
if (id === this.reqId && !isAuthRejection(err)) this.error.models = messageOf(err)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
async loadUsers(id: number, window: HistoryWindow, span: number): Promise<void> {
|
||||||
|
const configured = useDashboardStore().usage?.users.length ?? null
|
||||||
|
if (topUsersCapCheckResult(configured, TOP_USERS_METRICS_BY_MODE.req.length, span)) {
|
||||||
|
this.topUserRows = []
|
||||||
|
this.usersLoaded = false
|
||||||
|
this.error.users = RANGE_TOO_LARGE
|
||||||
|
return
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const res = await adminFetch<AdminTotalsResponse>(topUsersTotalsUrl(window, span, 'req'))
|
||||||
|
if (id !== this.reqId) return
|
||||||
|
this.topUserRows = res.rows
|
||||||
|
this.usersLoaded = true
|
||||||
|
this.error.users = ''
|
||||||
|
} catch (err) {
|
||||||
|
if (id === this.reqId && !isAuthRejection(err)) this.error.users = messageOf(err)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
startPolling(): void {
|
||||||
|
if (this.poller) return
|
||||||
|
this.poller = createVisibilityPoller({ intervalMs: REFRESH_MS, tick: () => this.refresh() })
|
||||||
|
this.poller.start()
|
||||||
|
},
|
||||||
|
stopPolling(): void {
|
||||||
|
this.poller?.stop()
|
||||||
|
this.poller = undefined
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
@@ -4,6 +4,7 @@ import { useConsumersStore } from '@/stores/consumers'
|
|||||||
import { useDashboardStore } from '@/stores/dashboard'
|
import { useDashboardStore } from '@/stores/dashboard'
|
||||||
import { useEventsStore } from '@/stores/events'
|
import { useEventsStore } from '@/stores/events'
|
||||||
import { useModelsStore } from '@/stores/models'
|
import { useModelsStore } from '@/stores/models'
|
||||||
|
import { useOverviewStore } from '@/stores/overview'
|
||||||
import { useReliabilityStore } from '@/stores/reliability'
|
import { useReliabilityStore } from '@/stores/reliability'
|
||||||
import { useSpendStore } from '@/stores/spend'
|
import { useSpendStore } from '@/stores/spend'
|
||||||
|
|
||||||
@@ -16,6 +17,7 @@ export function resetSessionData(): void {
|
|||||||
useDashboardStore(),
|
useDashboardStore(),
|
||||||
useEventsStore(),
|
useEventsStore(),
|
||||||
useModelsStore(),
|
useModelsStore(),
|
||||||
|
useOverviewStore(),
|
||||||
useReliabilityStore(),
|
useReliabilityStore(),
|
||||||
useSpendStore(),
|
useSpendStore(),
|
||||||
]) {
|
]) {
|
||||||
|
|||||||
@@ -0,0 +1,67 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { StatusDot } from '@perfect-design/ui'
|
||||||
|
import { computed } from 'vue'
|
||||||
|
|
||||||
|
import { useEntityLinks } from '@/composables/useEntityLinks'
|
||||||
|
import { openBreakerCount } from '@/lib/kpi'
|
||||||
|
import type { AdminProviderView, AdminRedisView } from '@/types/api'
|
||||||
|
|
||||||
|
type ChipTone = 'success' | 'warning' | 'danger' | 'neutral'
|
||||||
|
interface Chip {
|
||||||
|
key: string
|
||||||
|
tone: ChipTone
|
||||||
|
text: string
|
||||||
|
title?: string
|
||||||
|
provider?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
const MAX_FAILING_CHIPS = 3
|
||||||
|
|
||||||
|
const props = defineProps<{ providers: AdminProviderView[]; redis: AdminRedisView; eventsSource: 'redis' | 'replica' | null }>()
|
||||||
|
const { openEntity } = useEntityLinks()
|
||||||
|
|
||||||
|
const failing = computed(() => props.providers.filter((p) => p.healthState !== 'closed' || !!p.lastErr))
|
||||||
|
const healthy = computed(() => props.providers.length - failing.value.length)
|
||||||
|
const breakers = computed(() => openBreakerCount(props.providers))
|
||||||
|
|
||||||
|
const chips = computed<Chip[]>(() => {
|
||||||
|
const total = props.providers.length
|
||||||
|
const out: Chip[] = []
|
||||||
|
const providerTone: ChipTone = total === 0 ? 'neutral' : healthy.value === total ? 'success' : healthy.value === 0 ? 'danger' : 'warning'
|
||||||
|
out.push({ key: 'providers', tone: providerTone, text: total === 0 ? 'No providers' : `${healthy.value} of ${total} providers healthy` })
|
||||||
|
for (const p of failing.value.slice(0, MAX_FAILING_CHIPS)) {
|
||||||
|
const reason = p.lastErr || 'breaker open'
|
||||||
|
out.push({ key: `fail-${p.name}`, tone: 'danger', text: `${p.name}: ${reason}`, title: `${p.name}: ${reason}`, provider: p.name })
|
||||||
|
}
|
||||||
|
const more = failing.value.length - MAX_FAILING_CHIPS
|
||||||
|
if (more > 0) out.push({ key: 'more', tone: 'danger', text: `+${more} more failing` })
|
||||||
|
if (!props.redis.configured) out.push({ key: 'redis', tone: 'neutral', text: 'Redis not configured' })
|
||||||
|
else if (props.eventsSource === null) out.push({ key: 'redis', tone: 'neutral', text: 'Redis checking' })
|
||||||
|
else if (props.eventsSource === 'redis') out.push({ key: 'redis', tone: 'success', text: 'Redis connected' })
|
||||||
|
else out.push({ key: 'redis', tone: 'danger', text: 'Redis unreachable', title: props.redis.lastErr })
|
||||||
|
out.push({
|
||||||
|
key: 'breakers',
|
||||||
|
tone: breakers.value > 0 ? 'danger' : 'success',
|
||||||
|
text: breakers.value > 0 ? `${breakers.value} open breaker${breakers.value === 1 ? '' : 's'}` : 'No open breakers',
|
||||||
|
})
|
||||||
|
return out
|
||||||
|
})
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<ul class="m-0 flex list-none flex-wrap gap-2 p-0" aria-label="Fleet health">
|
||||||
|
<li v-for="chip in chips" :key="chip.key" class="min-w-0 max-w-full">
|
||||||
|
<component
|
||||||
|
:is="chip.provider ? 'button' : 'span'"
|
||||||
|
class="border-border bg-card text-foreground inline-flex h-8 max-w-full sm:max-w-md items-center gap-2 rounded-md border px-3 text-sm"
|
||||||
|
:class="chip.provider ? 'hover:bg-accent cursor-pointer' : ''"
|
||||||
|
:title="chip.title"
|
||||||
|
:type="chip.provider ? 'button' : undefined"
|
||||||
|
@click="chip.provider && openEntity('provider', chip.provider)"
|
||||||
|
>
|
||||||
|
<StatusDot :tone="chip.tone" size="md" />
|
||||||
|
<span class="truncate">{{ chip.text }}</span>
|
||||||
|
</component>
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
</template>
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { StatusDot } from '@perfect-design/ui'
|
||||||
|
|
||||||
|
import { useEntityLinks } from '@/composables/useEntityLinks'
|
||||||
|
import type { AttentionItem, AttentionSeverity } from '@/lib/attention'
|
||||||
|
|
||||||
|
const TONE: Record<AttentionSeverity, 'danger' | 'warning' | 'info'> = { danger: 'danger', warning: 'warning', info: 'info' }
|
||||||
|
|
||||||
|
defineProps<{ items: AttentionItem[] }>()
|
||||||
|
const { openLink } = useEntityLinks()
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<p v-if="items.length === 0" class="text-muted-foreground m-0 flex h-8 items-center gap-2 text-sm">
|
||||||
|
<StatusDot tone="success" size="md" />
|
||||||
|
Nothing needs attention
|
||||||
|
</p>
|
||||||
|
<ul v-else class="m-0 flex list-none flex-col p-0" aria-label="Needs attention">
|
||||||
|
<li v-for="(item, i) in items" :key="`${item.severity}-${i}`">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="hover:bg-accent flex min-h-8 w-full items-start gap-2 rounded-md px-2 py-1 text-left text-sm"
|
||||||
|
:data-severity="item.severity"
|
||||||
|
@click="openLink(item.link)"
|
||||||
|
>
|
||||||
|
<StatusDot class="mt-1.5 shrink-0" :tone="TONE[item.severity]" size="md" />
|
||||||
|
<span class="min-w-0 break-words">{{ item.text }}</span>
|
||||||
|
</button>
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
</template>
|
||||||
Reference in New Issue
Block a user