mirror of
https://github.com/lukaszraczylo/traefik-llmgateway.git
synced 2026-11-26 10:06:31 +00:00
feat(webui): usage and spend page
This commit is contained in:
@@ -732,3 +732,68 @@ describe('useSpendStore.refresh: breakdown depends on the ranking', () => {
|
||||
expect(spend.breakdown.map((s) => s.scope)).toContain('group:a')
|
||||
})
|
||||
})
|
||||
|
||||
describe('useSpendStore detail fallback', () => {
|
||||
const tooLarge = () => new AdminApiError('range too large; narrow span or filter', 400)
|
||||
|
||||
it('retries the ranking without detail on a 400 and flags detailAvailable false', async () => {
|
||||
const urls: string[] = []
|
||||
mockedAdminFetch.mockImplementation((async (path: string) => {
|
||||
urls.push(path)
|
||||
if (path.includes('detail=1')) throw tooLarge()
|
||||
return { ...rankingWith(['a/one']), detail: false, models: [{ id: 'a/one', value: 5 }] }
|
||||
}) as typeof adminFetch)
|
||||
const spend = useSpendStore()
|
||||
await spend.fetchModelRanking()
|
||||
expect(urls).toHaveLength(2)
|
||||
expect(urls[1]).not.toContain('detail=1')
|
||||
expect(spend.modelRanking.map((m) => m.id)).toEqual(['a/one'])
|
||||
expect(spend.detailAvailable).toBe(false)
|
||||
expect(spend.rankingError).toBe('')
|
||||
})
|
||||
|
||||
it('does the same for the pricing-health ranking', async () => {
|
||||
mockedAdminFetch.mockImplementation((async (path: string) => {
|
||||
if (path.includes('detail=1')) throw tooLarge()
|
||||
return { ...rankingWith(['a/one']), detail: false, models: [{ id: 'a/one', value: 5 }] }
|
||||
}) as typeof adminFetch)
|
||||
const spend = useSpendStore()
|
||||
await spend.fetchPricingHealthRanking()
|
||||
expect(spend.pricingHealthRanking).toHaveLength(1)
|
||||
expect(spend.pricingHealthError).toBe('')
|
||||
expect(spend.detailAvailable).toBe(false)
|
||||
})
|
||||
|
||||
it('keeps surfacing non-400 failures', async () => {
|
||||
mockedAdminFetch.mockRejectedValue(new AdminApiError('boom', 503))
|
||||
const spend = useSpendStore()
|
||||
await spend.fetchModelRanking()
|
||||
expect(spend.rankingError).toBe('boom')
|
||||
expect(mockedAdminFetch).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('stays detailAvailable when the server accepts detail', async () => {
|
||||
mockRoutes({ models: () => rankingWith(['a/one']) })
|
||||
const spend = useSpendStore()
|
||||
await spend.fetchModelRanking()
|
||||
expect(spend.detailAvailable).toBe(true)
|
||||
})
|
||||
|
||||
it('skips the doomed detail request on 48h and 30d', async () => {
|
||||
const urls: string[] = []
|
||||
mockedAdminFetch.mockImplementation((async (path: string) => {
|
||||
urls.push(path)
|
||||
return { ...rankingWith(['a/one']), detail: false, models: [{ id: 'a/one', value: 5 }] }
|
||||
}) as typeof adminFetch)
|
||||
const filters = useFiltersStore()
|
||||
const spend = useSpendStore()
|
||||
for (const range of ['48h', '30d'] as const) {
|
||||
urls.length = 0
|
||||
filters.setFilters({ range })
|
||||
await spend.fetchModelRanking()
|
||||
expect(urls).toHaveLength(1)
|
||||
expect(urls[0]).not.toContain('detail=1')
|
||||
expect(spend.detailAvailable).toBe(false)
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
@@ -3,7 +3,7 @@ import { defineStore } from 'pinia'
|
||||
import { AdminApiError, adminFetch, isAuthRejection, messageOf } from '@/lib/api'
|
||||
import { currentMonthDaySpan } from '@/lib/burndown'
|
||||
import { createVisibilityPoller, type VisibilityPoller } from '@/lib/polling'
|
||||
import { dayOrMonthWindow, seriesUrl, totalsUrl } from '@/lib/range'
|
||||
import { dayOrMonthWindow, modelDetailSupported, seriesUrl, totalsUrl } from '@/lib/range'
|
||||
import type { TotalsUrlParams } from '@/lib/range'
|
||||
import { drilldownLevel, scopeBudgetLimits } from '@/lib/scope'
|
||||
import { other, stackTopN, sumByProvider, type Series } from '@/lib/series'
|
||||
@@ -130,6 +130,8 @@ export const useSpendStore = defineStore('spend', {
|
||||
* longer discards a row specifically BECAUSE it is unpriced.
|
||||
*/
|
||||
pricingHealthRanking: [] as AdminUsageModelsResponse['models'],
|
||||
/** False when the server refused `detail=1` for this range (400 range too large) and the rankings fell back to value-only rows, so per-model tokens, cost and free flags are absent. */
|
||||
detailAvailable: true,
|
||||
|
||||
// --- burn-down (BurnDownChart) ---
|
||||
burndownBuckets: [] as string[],
|
||||
@@ -312,11 +314,10 @@ export const useSpendStore = defineStore('spend', {
|
||||
const filters = useFiltersStore()
|
||||
const requestId = ++this.rankingReqId
|
||||
try {
|
||||
const res = await adminFetch<AdminUsageModelsResponse>(
|
||||
`/admin/api/usage/models?metric=${this.metric}&window=${filters.window}&span=${filters.span}&limit=${MODEL_RANKING_LIMIT}&detail=1`,
|
||||
)
|
||||
const { res, detail } = await fetchModelsRanking(this.metric, filters.window, filters.span)
|
||||
if (requestId !== this.rankingReqId) return false
|
||||
this.modelRanking = res.models
|
||||
this.detailAvailable = detail
|
||||
this.rankingError = ''
|
||||
return true
|
||||
} catch (err) {
|
||||
@@ -344,11 +345,10 @@ export const useSpendStore = defineStore('spend', {
|
||||
const requestId = ++this.pricingHealthReqId
|
||||
this.pricingHealthLoading = true
|
||||
try {
|
||||
const res = await adminFetch<AdminUsageModelsResponse>(
|
||||
`/admin/api/usage/models?metric=req&window=${filters.window}&span=${filters.span}&limit=${MODEL_RANKING_LIMIT}&detail=1`,
|
||||
)
|
||||
const { res, detail } = await fetchModelsRanking('req', filters.window, filters.span)
|
||||
if (requestId !== this.pricingHealthReqId) return
|
||||
this.pricingHealthRanking = res.models
|
||||
this.detailAvailable = detail
|
||||
this.pricingHealthError = ''
|
||||
this.pricingHealthLoaded = true
|
||||
} catch (err) {
|
||||
@@ -628,6 +628,18 @@ export const useSpendStore = defineStore('spend', {
|
||||
},
|
||||
})
|
||||
|
||||
/** fetchModelsRanking asks for `detail=1` except on ranges the server is known to refuse (48h, 30d); a 400 elsewhere retries once without detail. Reports which form it got. */
|
||||
async function fetchModelsRanking(metric: string, window: HistoryWindow, span: number): Promise<{ res: AdminUsageModelsResponse; detail: boolean }> {
|
||||
const base = `/admin/api/usage/models?metric=${metric}&window=${window}&span=${span}&limit=${MODEL_RANKING_LIMIT}`
|
||||
if (!modelDetailSupported(window, span)) return { res: await adminFetch<AdminUsageModelsResponse>(base), detail: false }
|
||||
try {
|
||||
return { res: await adminFetch<AdminUsageModelsResponse>(`${base}&detail=1`), detail: true }
|
||||
} catch (err) {
|
||||
if (!(err instanceof AdminApiError) || err.status !== 400) throw err
|
||||
return { res: await adminFetch<AdminUsageModelsResponse>(base), detail: false }
|
||||
}
|
||||
}
|
||||
|
||||
/** burndownScopeParam maps the global scope filter to the /usage/series scope this store's burn-down line requests — null for a provider scope, which has no cost series and no budget concept (see useSpendStore's own doc comment). */
|
||||
function burndownScopeParam(filtersScope: string): string | null {
|
||||
if (filtersScope === 'all') return 'total'
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
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 { AdminApiError, adminFetch } from '@/lib/api'
|
||||
import { useAuthStore } from '@/stores/auth'
|
||||
import { useDashboardStore } from '@/stores/dashboard'
|
||||
import { USERS_RANGE_TOO_LARGE, useUsageUsersStore } from '@/stores/usage-users'
|
||||
|
||||
const mocked = vi.mocked(adminFetch)
|
||||
|
||||
function route(url: string): unknown {
|
||||
const u = new URL(url, 'http://x')
|
||||
if (u.pathname.endsWith('/usage/totals')) {
|
||||
return { rows: [{ id: 'bob', values: { cost: 3 } }, { id: 'alice', values: { cost: 9 } }, { id: 'idle', values: { cost: 0 } }] }
|
||||
}
|
||||
const scopes = u.searchParams.getAll('scope')
|
||||
return { series: scopes.map((scope) => ({ scope, points: scope === 'total' ? [20, 20] : [4, 4] })) }
|
||||
}
|
||||
|
||||
describe('useUsageUsersStore.refresh', () => {
|
||||
beforeEach(() => {
|
||||
setActivePinia(createPinia())
|
||||
mocked.mockReset()
|
||||
mocked.mockImplementation(async (url: string) => route(url) as never)
|
||||
useAuthStore().submit('test-admin-key')
|
||||
})
|
||||
|
||||
it('ranks active users by the metric and derives the other bucket from the total', async () => {
|
||||
const s = useUsageUsersStore()
|
||||
await s.refresh('cost')
|
||||
expect(s.rows).toEqual([{ id: 'alice', value: 9 }, { id: 'bob', value: 3 }])
|
||||
expect(s.series.map((x) => x.scope)).toEqual(['user:alice', 'user:bob'])
|
||||
expect(s.otherPoints).toEqual([12, 12])
|
||||
expect(s.loaded).toBe(true)
|
||||
expect(s.error).toBe('')
|
||||
})
|
||||
|
||||
it('refuses ranges whose user count would exceed the per-request key cap', async () => {
|
||||
const dashboard = useDashboardStore()
|
||||
dashboard.usage = { users: new Array(20000).fill({ id: 'u' }) } as never
|
||||
const s = useUsageUsersStore()
|
||||
await s.refresh('cost')
|
||||
expect(s.error).toBe(USERS_RANGE_TOO_LARGE)
|
||||
expect(mocked).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('reports a fetch failure and stays unloaded', async () => {
|
||||
mocked.mockRejectedValue(new AdminApiError('boom', 503))
|
||||
const s = useUsageUsersStore()
|
||||
await s.refresh('cost')
|
||||
expect(s.error).toBe('boom')
|
||||
expect(s.loaded).toBe(false)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,78 @@
|
||||
import { defineStore } from 'pinia'
|
||||
|
||||
import { adminFetch, isAuthRejection, messageOf } from '@/lib/api'
|
||||
import { seriesUrl } from '@/lib/range'
|
||||
import { other } from '@/lib/series'
|
||||
import type { Series } from '@/lib/series'
|
||||
import { topUsersCapCheckResult } from '@/lib/top-users'
|
||||
import { useAuthStore } from '@/stores/auth'
|
||||
import { useDashboardStore } from '@/stores/dashboard'
|
||||
import { useFiltersStore } from '@/stores/filters'
|
||||
import type { AdminSeriesResponse, AdminTotalsResponse, HistoryMetric } from '@/types/api'
|
||||
|
||||
/** Users given their own chart series; the rest fold into "Other". */
|
||||
export const USER_SERIES_LIMIT = 10
|
||||
const TOTALS_LIMIT = 1000
|
||||
const TOTAL_SCOPE = 'total'
|
||||
|
||||
export const USERS_RANGE_TOO_LARGE = 'Too many configured users to rank for this range. Pick a shorter range.'
|
||||
|
||||
export interface UserRow {
|
||||
id: string
|
||||
value: number
|
||||
}
|
||||
|
||||
/** Per-user ranking and top-user series for the Usage page's user breakdown. */
|
||||
export const useUsageUsersStore = defineStore('usage-users', {
|
||||
state: () => ({
|
||||
rows: [] as UserRow[],
|
||||
series: [] as Series[],
|
||||
otherPoints: null as number[] | null,
|
||||
loaded: false,
|
||||
error: '',
|
||||
fetchedFor: '',
|
||||
reqId: 0,
|
||||
}),
|
||||
actions: {
|
||||
async refresh(metric: HistoryMetric): Promise<void> {
|
||||
if (!useAuthStore().isAuthenticated) return
|
||||
const { window, span } = useFiltersStore()
|
||||
const key = `${metric}:${window}:${span}`
|
||||
if (key !== this.fetchedFor) {
|
||||
this.rows = []
|
||||
this.series = []
|
||||
this.otherPoints = null
|
||||
this.loaded = false
|
||||
}
|
||||
this.fetchedFor = key
|
||||
const id = ++this.reqId
|
||||
const configured = useDashboardStore().usage?.users.length ?? null
|
||||
if (topUsersCapCheckResult(configured, 1, span)) {
|
||||
this.error = USERS_RANGE_TOO_LARGE
|
||||
return
|
||||
}
|
||||
try {
|
||||
const q = new URLSearchParams({ kind: 'user', window, span: String(span), offset: '0', metrics: metric, limit: String(TOTALS_LIMIT) })
|
||||
const totals = await adminFetch<AdminTotalsResponse>(`/admin/api/usage/totals?${q.toString()}`)
|
||||
const rows = totals.rows.map((r) => ({ id: r.id, value: r.values[metric] ?? 0 })).filter((r) => r.value > 0).sort((a, b) => b.value - a.value)
|
||||
const top = rows.slice(0, USER_SERIES_LIMIT)
|
||||
const scopes = top.map((r) => `user:${r.id}`)
|
||||
let series: Series[] = []
|
||||
let totalPoints: number[] = []
|
||||
if (scopes.length > 0) {
|
||||
const res = await adminFetch<AdminSeriesResponse>(seriesUrl({ scope: [TOTAL_SCOPE, ...scopes], metric, window, span }))
|
||||
series = res.series.filter((s) => s.scope !== TOTAL_SCOPE)
|
||||
totalPoints = res.series.find((s) => s.scope === TOTAL_SCOPE)?.points ?? []
|
||||
}
|
||||
if (id !== this.reqId) return
|
||||
this.rows = rows
|
||||
this.series = series
|
||||
this.otherPoints = totalPoints.length > 0 ? other(totalPoints, series) : null
|
||||
this.loaded = true
|
||||
this.error = ''
|
||||
} catch (err) {
|
||||
if (id === this.reqId && !isAuthRejection(err)) this.error = messageOf(err)
|
||||
}
|
||||
},
|
||||
},
|
||||
})
|
||||
Reference in New Issue
Block a user