mirror of
https://github.com/lukaszraczylo/traefik-llmgateway.git
synced 2026-11-26 10:06:31 +00:00
fix(admin-ui): stale-data notice, request timeout and dedupe, hash and format edge cases
Show a persistent notice when a refresh fails while old data is on screen. Add retry to the Targets and Access Matrix error states. Give tables names, skeletons a status role and CSV export a live region. Abort admin requests after 15 seconds and share concurrent identical GETs. Show a reload prompt when a lazy page chunk fails to load. Ignore prototype keys in the location hash. Stop formatContextWindow emitting 1000k, round latency before the 1s cutoff, and treat NaN as not enough data in the month projection. Regenerate admin_assets_gen.go.
This commit is contained in:
@@ -101,3 +101,78 @@ describe('isAuthRejection', () => {
|
||||
expect(isAuthRejection('nope')).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('adminFetch resilience', () => {
|
||||
beforeEach(() => {
|
||||
setActivePinia(createPinia())
|
||||
useAuthStore().submit('test-admin-key')
|
||||
vi.stubGlobal('fetch', vi.fn())
|
||||
})
|
||||
|
||||
it('passes an abort signal so a hung request cannot block polling forever', async () => {
|
||||
vi.mocked(fetch).mockResolvedValue(jsonResponse(200, {}))
|
||||
await adminFetch('/admin/api/overview')
|
||||
const init = vi.mocked(fetch).mock.calls[0][1]
|
||||
expect(init?.signal).toBeInstanceOf(AbortSignal)
|
||||
})
|
||||
|
||||
it('turns a timeout into an AdminApiError naming the path', async () => {
|
||||
vi.mocked(fetch).mockRejectedValue(new DOMException('timed out', 'TimeoutError'))
|
||||
await expect(adminFetch('/admin/api/overview')).rejects.toMatchObject({
|
||||
name: 'AdminApiError',
|
||||
message: expect.stringContaining('/admin/api/overview'),
|
||||
})
|
||||
})
|
||||
|
||||
it('turns a 200 with a non-JSON body into an AdminApiError, not a raw SyntaxError', async () => {
|
||||
vi.mocked(fetch).mockResolvedValue({
|
||||
ok: true,
|
||||
status: 200,
|
||||
json: () => Promise.reject(new SyntaxError('Unexpected token <')),
|
||||
} as Response)
|
||||
await expect(adminFetch('/admin/api/overview')).rejects.toBeInstanceOf(AdminApiError)
|
||||
})
|
||||
|
||||
it('rethrows network errors unchanged', async () => {
|
||||
vi.mocked(fetch).mockRejectedValue(new TypeError('Failed to fetch'))
|
||||
await expect(adminFetch('/admin/api/overview')).rejects.toThrow('Failed to fetch')
|
||||
})
|
||||
})
|
||||
|
||||
describe('adminFetch in-flight dedupe', () => {
|
||||
beforeEach(() => {
|
||||
setActivePinia(createPinia())
|
||||
useAuthStore().submit('test-admin-key')
|
||||
vi.stubGlobal('fetch', vi.fn())
|
||||
})
|
||||
|
||||
it('shares one request between concurrent calls for the same path', async () => {
|
||||
vi.mocked(fetch).mockResolvedValue(jsonResponse(200, { n: 1 }))
|
||||
const [a, b] = await Promise.all([adminFetch('/admin/api/x'), adminFetch('/admin/api/x')])
|
||||
expect(fetch).toHaveBeenCalledTimes(1)
|
||||
expect(a).toEqual({ n: 1 })
|
||||
expect(b).toEqual({ n: 1 })
|
||||
})
|
||||
|
||||
it('does not share between different paths', async () => {
|
||||
vi.mocked(fetch).mockResolvedValue(jsonResponse(200, {}))
|
||||
await Promise.all([adminFetch('/admin/api/x'), adminFetch('/admin/api/y')])
|
||||
expect(fetch).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
|
||||
it('issues a fresh request once the first settles, including after failure', async () => {
|
||||
vi.mocked(fetch).mockRejectedValueOnce(new TypeError('down')).mockResolvedValue(jsonResponse(200, { ok: true }))
|
||||
await expect(adminFetch('/admin/api/x')).rejects.toThrow('down')
|
||||
await expect(adminFetch('/admin/api/x')).resolves.toEqual({ ok: true })
|
||||
expect(fetch).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
|
||||
it('does not share across different admin keys', async () => {
|
||||
vi.mocked(fetch).mockResolvedValue(jsonResponse(200, {}))
|
||||
const first = adminFetch('/admin/api/x')
|
||||
useAuthStore().submit('other-key')
|
||||
const second = adminFetch('/admin/api/x')
|
||||
await Promise.all([first, second])
|
||||
expect(fetch).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
})
|
||||
|
||||
+31
-4
@@ -1,5 +1,11 @@
|
||||
import { useAuthStore } from '@/stores/auth'
|
||||
|
||||
/** Upper bound on one admin request; a hung socket would otherwise pin a store's in-flight guard and freeze polling. */
|
||||
const ADMIN_FETCH_TIMEOUT_MS = 15_000
|
||||
|
||||
/** Concurrent GETs for the same key and path share one request (spend.ts asks twice for the default metric). */
|
||||
const inFlight = new Map<string, Promise<unknown>>()
|
||||
|
||||
/** AdminApiError carries the HTTP status alongside the message, so callers
|
||||
* can tell an auth failure (already handled by adminFetch itself) apart
|
||||
* from any other fetch failure without re-parsing the message string. */
|
||||
@@ -41,12 +47,29 @@ async function serverErrorMessage(resp: Response, path: string): Promise<string>
|
||||
* poll timer should not spam the status line with "unauthorized" on every
|
||||
* tick once the gate is already showing) can catch and check `status`.
|
||||
*/
|
||||
export async function adminFetch<T>(path: string): Promise<T> {
|
||||
export function adminFetch<T>(path: string): Promise<T> {
|
||||
const key = useAuthStore().apiKey
|
||||
const flightKey = `${key}\0${path}`
|
||||
const existing = inFlight.get(flightKey)
|
||||
if (existing) return existing as Promise<T>
|
||||
const request = doAdminFetch<T>(path, key).finally(() => inFlight.delete(flightKey))
|
||||
inFlight.set(flightKey, request)
|
||||
return request
|
||||
}
|
||||
|
||||
async function doAdminFetch<T>(path: string, key: string): Promise<T> {
|
||||
const auth = useAuthStore()
|
||||
const key = auth.apiKey
|
||||
const headers: HeadersInit = key ? { 'x-api-key': key } : {}
|
||||
|
||||
const resp = await fetch(path, { credentials: 'same-origin', headers })
|
||||
let resp: Response
|
||||
try {
|
||||
resp = await fetch(path, { credentials: 'same-origin', headers, signal: AbortSignal.timeout(ADMIN_FETCH_TIMEOUT_MS) })
|
||||
} catch (err) {
|
||||
if (err instanceof DOMException && err.name === 'TimeoutError') {
|
||||
throw new AdminApiError(`${path}: no response after ${ADMIN_FETCH_TIMEOUT_MS / 1000}s`, 0)
|
||||
}
|
||||
throw err
|
||||
}
|
||||
|
||||
if (!resp.ok) {
|
||||
const message = await serverErrorMessage(resp, path)
|
||||
@@ -59,7 +82,11 @@ export async function adminFetch<T>(path: string): Promise<T> {
|
||||
}
|
||||
throw new AdminApiError(message, resp.status)
|
||||
}
|
||||
return (await resp.json()) as T
|
||||
try {
|
||||
return (await resp.json()) as T
|
||||
} catch {
|
||||
throw new AdminApiError(`${path}: response was not valid JSON`, resp.status)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -137,3 +137,9 @@ describe('NOT_ENOUGH_DATA', () => {
|
||||
expect(NOT_ENOUGH_DATA).toBeTruthy()
|
||||
})
|
||||
})
|
||||
|
||||
describe('projectMonthEnd non-finite input', () => {
|
||||
it.each([NaN, Infinity * 0, -1])('returns null for elapsedFraction %s', (f) => {
|
||||
expect(projectMonthEnd(5, f)).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -70,7 +70,7 @@ export function monthProgress(now: Date): number {
|
||||
* infinite figure for the first sliver of a month.
|
||||
*/
|
||||
export function projectMonthEnd(mtdMicros: number, elapsedFraction: number): number | null {
|
||||
if (elapsedFraction < MIN_PROJECTION_FRACTION) return null
|
||||
if (!(elapsedFraction >= MIN_PROJECTION_FRACTION)) return null
|
||||
return Math.round(mtdMicros / elapsedFraction)
|
||||
}
|
||||
|
||||
|
||||
@@ -250,3 +250,22 @@ describe('formatElapsedAgo', () => {
|
||||
expect(formatElapsedAgo(iso)).toMatch(/^\d+s ago$/)
|
||||
})
|
||||
})
|
||||
|
||||
describe('rounding boundaries', () => {
|
||||
it.each([
|
||||
{ name: 'k rounding never reaches 1000k', tokens: 999_999, want: '1M' },
|
||||
{ name: 'just under the cutoff stays k', tokens: 999_499, want: '999k' },
|
||||
{ name: 'cutoff moves to M', tokens: 999_500, want: '1M' },
|
||||
])('formatContextWindow: $name', ({ tokens, want }) => {
|
||||
expect(formatContextWindow(tokens)).toBe(want)
|
||||
})
|
||||
|
||||
it.each([
|
||||
{ name: 'rounds before the second cutoff', ms: 999.6, want: '1.0s' },
|
||||
{ name: 'plain ms', ms: 120, want: '120ms' },
|
||||
{ name: 'NaN', ms: NaN, want: '—' },
|
||||
{ name: 'Infinity', ms: Infinity, want: '—' },
|
||||
])('formatLatencyMs: $name', ({ ms, want }) => {
|
||||
expect(formatLatencyMs(ms)).toBe(want)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -162,7 +162,8 @@ export function formatContextWindow(tokens: number): string {
|
||||
return `${Math.round(tokens / (1024 * 1024))}M`
|
||||
}
|
||||
|
||||
if (tokens < 1_000_000) return `${Math.round(tokens / 1_000)}k`
|
||||
// 999_500+ would round to "1000k"; the M branch renders it as "1M".
|
||||
if (tokens < 999_500) return `${Math.round(tokens / 1_000)}k`
|
||||
return `${Math.round(tokens / 1_000_000)}M`
|
||||
}
|
||||
|
||||
@@ -195,7 +196,9 @@ export function formatModelCostHover(inputUsd: number, outputUsd: number): strin
|
||||
* crossed, just a plain rounded reading.
|
||||
*/
|
||||
export function formatLatencyMs(ms: number): string {
|
||||
if (ms < 1000) return `${Math.round(ms)}ms`
|
||||
if (!Number.isFinite(ms)) return '—'
|
||||
const rounded = Math.round(ms)
|
||||
if (rounded < 1000) return `${rounded}ms`
|
||||
return `${(ms / 1000).toFixed(1)}s`
|
||||
}
|
||||
|
||||
|
||||
@@ -130,3 +130,12 @@ describe('parsePageParams', () => {
|
||||
expect(parsePageParams(new URLSearchParams())).toEqual({})
|
||||
})
|
||||
})
|
||||
|
||||
describe('parseHashState prototype keys', () => {
|
||||
it.each(['constructor', 'toString', '__proto__', 'hasOwnProperty'])('#%s falls back to the default page', (key) => {
|
||||
const state = parseHashState(`#${key}?range=7d`)
|
||||
expect(typeof state.page).toBe('string')
|
||||
expect(PAGE_IDS).toContain(state.page)
|
||||
expect(state.query.get('range')).toBe('7d')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -53,7 +53,7 @@ export function parseHashState(hash: string): HashState {
|
||||
|
||||
if (isPageId(pagePart)) return { page: pagePart, query: new URLSearchParams(queryPart) }
|
||||
|
||||
const legacy = LEGACY_PAGE_MAP[pagePart]
|
||||
const legacy = Object.hasOwn(LEGACY_PAGE_MAP, pagePart) ? LEGACY_PAGE_MAP[pagePart] : undefined
|
||||
if (legacy) return { page: legacy, query: new URLSearchParams() }
|
||||
|
||||
return { page: DEFAULT_PAGE, query: new URLSearchParams(queryPart) }
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
import { loadState } from './load-state'
|
||||
import { staleNotice } from './stale-notice'
|
||||
|
||||
const at = new Date('2026-11-08T10:11:12Z')
|
||||
|
||||
describe('staleNotice', () => {
|
||||
it.each([
|
||||
{ name: 'no data, error', hasData: false, error: 'boom', want: null },
|
||||
{ name: 'data, no error', hasData: true, error: '', want: null },
|
||||
{ name: 'no data, no error', hasData: false, error: '', want: null },
|
||||
])('is null: $name', ({ hasData, error, want }) => {
|
||||
expect(staleNotice(hasData, error, at)).toBe(want)
|
||||
})
|
||||
|
||||
it('names the error and the data age when data is shown and refresh fails', () => {
|
||||
const msg = staleNotice(true, 'HTTP 503', at)
|
||||
expect(msg).toContain('HTTP 503')
|
||||
expect(msg).toContain(at.toLocaleTimeString())
|
||||
})
|
||||
|
||||
it('omits the age when lastUpdated is unknown', () => {
|
||||
expect(staleNotice(true, 'x', null)).toBe('Refresh failing: x.')
|
||||
})
|
||||
|
||||
// Lean gate Gateway.Ui.Stale.no_silent_stale: ready + error always has a notice.
|
||||
it.each([true, false])('never silent when ready with error (loading=%s)', (loading) => {
|
||||
const state = loadState({ loading, hasData: true, error: 'e' })
|
||||
expect(state).toBe('ready')
|
||||
expect(staleNotice(true, 'e', at)).not.toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,6 @@
|
||||
/** staleNotice returns the text for a "showing old data" banner, or null. Shown only when data is on screen and the latest refresh failed. */
|
||||
export function staleNotice(hasData: boolean, error: string, lastUpdated: Date | null): string | null {
|
||||
if (!hasData || !error) return null
|
||||
const at = lastUpdated ? ` Data from ${lastUpdated.toLocaleTimeString()}.` : ''
|
||||
return `Refresh failing: ${error}.${at}`
|
||||
}
|
||||
Reference in New Issue
Block a user