feat(admin dashboard): add admin dashboard

This commit is contained in:
shay
2026-05-11 18:26:43 -04:00
parent 00bf46968a
commit ef48d2581b
14 changed files with 1225 additions and 0 deletions
@@ -0,0 +1,30 @@
import { useEffect, useState } from 'react'
import { fetchHealth, type Health } from '../lib/dev'
export function HealthStrip() {
const [h, setH] = useState<Health | null>(null)
useEffect(() => { fetchHealth().then(setH).catch(() => {}) }, [])
if (!h) return null
const pct = (n: number) => `${(n * 100).toFixed(1)}%`
return (
<div className="rounded-lg border border-white/10 bg-white/[0.02] p-4">
<div className="mb-3 text-sm text-white/70">Health</div>
<div className="grid grid-cols-3 gap-3 text-center">
<Pill label="Edge cache hit" value={pct(h.edge_cache_hit_rate)} />
<Pill label="Fetch error" value={pct(h.fetcher_error_rate)} tone={h.fetcher_error_rate > 0.05 ? 'warn' : 'ok'} />
<Pill label="Events dropped 24h" value={h.events_dropped_24h.toLocaleString()}
tone={h.events_dropped_24h > 0 ? 'warn' : 'ok'} />
</div>
</div>
)
}
function Pill({ label, value, tone = 'ok' }: { label: string; value: string; tone?: 'ok' | 'warn' }) {
const color = tone === 'warn' ? 'text-amber-400' : 'text-emerald-400'
return (
<div className="rounded bg-white/[0.03] px-2 py-2">
<div className="text-xs text-white/40">{label}</div>
<div className={`mt-1 font-mono text-lg ${color}`}>{value}</div>
</div>
)
}
@@ -0,0 +1,34 @@
import { useEffect, useState } from 'react'
import { fetchLatency, type LatencyRow } from '../lib/dev'
export function LatencyChart() {
const [rows, setRows] = useState<LatencyRow[]>([])
useEffect(() => { fetchLatency().then(setRows).catch(() => {}) }, [])
const max = Math.max(1, ...rows.map(r => r.p95))
return (
<div className="rounded-lg border border-white/10 bg-white/[0.02] p-4">
<div className="mb-3 text-sm text-white/70">Latency by endpoint</div>
{rows.length === 0 && <div className="text-xs text-white/40">no traffic yet</div>}
<div className="space-y-1.5">
{rows.map(r => (
<div key={r.endpoint} className="grid grid-cols-[1fr_auto] items-center gap-3 font-mono text-xs">
<div>
<div className="text-white/70">{r.endpoint}</div>
<div className="mt-1 h-1.5 w-full overflow-hidden rounded bg-white/[0.04]">
<div className="h-full bg-sky-400/60" style={{ width: `${(r.p50 / max) * 100}%` }} />
<div className="-mt-1.5 h-1.5 bg-sky-300/30" style={{ width: `${(r.p95 / max) * 100}%` }} />
</div>
</div>
<div className="text-right text-white/80 tabular-nums">
<span>{r.p50}</span><span className="text-white/30"> · </span>
<span>{r.p95}</span><span className="text-white/30"> · </span>
<span>{r.p99}ms</span>
</div>
</div>
))}
</div>
</div>
)
}
@@ -0,0 +1,17 @@
type Props = { values: number[]; width?: number; height?: number; stroke?: string }
export function Sparkline({ values, width = 140, height = 32, stroke = '#60a5fa' }: Props) {
if (values.length === 0) return <svg width={width} height={height} />
const max = Math.max(1, ...values)
const stepX = width / Math.max(1, values.length - 1)
const pts = values.map((v, i) => {
const x = i * stepX
const y = height - (v / max) * (height - 2) - 1
return `${x.toFixed(1)},${y.toFixed(1)}`
}).join(' ')
return (
<svg width={width} height={height} viewBox={`0 0 ${width} ${height}`}>
<polyline points={pts} fill="none" stroke={stroke} strokeWidth={1.5} strokeLinecap="round" strokeLinejoin="round" />
</svg>
)
}
@@ -0,0 +1,26 @@
import type { ReactNode } from 'react'
import { Sparkline } from './Sparkline'
import type { Summary } from '../lib/dev'
function Card({ label, value, sub }: { label: string; value: string; sub?: ReactNode }) {
return (
<div className="rounded-lg border border-white/10 bg-white/[0.02] px-4 py-3">
<div className="text-xs uppercase tracking-wide text-white/50">{label}</div>
<div className="mt-1 text-2xl font-mono text-white">{value}</div>
{sub && <div className="mt-1 text-xs text-white/40">{sub}</div>}
</div>
)
}
export function StatCards({ s }: { s: Summary }) {
const fmt = (n: number) => n.toLocaleString()
return (
<div className="grid grid-cols-1 gap-3 md:grid-cols-4">
<Card label="Requests 7d" value={fmt(s.requests_7d)}
sub={<Sparkline values={s.daily_requests.map(d => d.count)} />} />
<Card label="Active users 7d" value={fmt(s.active_users_7d)} />
<Card label="p50 / p95 latency" value={`${s.p50_ms}/${s.p95_ms}ms`} />
<Card label="Renders 7d" value={fmt(s.renders_7d)} sub={`avg ${s.avg_render_ms}ms`} />
</div>
)
}
@@ -0,0 +1,81 @@
import { useEffect, useMemo, useState } from 'react'
import { fetchUsers, type UserRow } from '../lib/dev'
function timeAgo(ts: number | null): string {
if (!ts) return '—'
const s = Math.max(0, Math.floor(Date.now() / 1000 - ts))
if (s < 60) return `${s}s ago`
if (s < 3600) return `${Math.floor(s / 60)}m ago`
if (s < 86400) return `${Math.floor(s / 3600)}h ago`
return `${Math.floor(s / 86400)}d ago`
}
export function UsersTable() {
const [q, setQ] = useState('')
const [sort, setSort] = useState<'requests' | 'latency' | 'last_seen'>('requests')
const [rows, setRows] = useState<UserRow[]>([])
const [loading, setLoading] = useState(true)
useEffect(() => {
let alive = true
const h = window.setTimeout(() => {
setLoading(true)
fetchUsers(q, sort).then(r => { if (alive) { setRows(r); setLoading(false) } })
.catch(() => { if (alive) setLoading(false) })
}, 200)
return () => { alive = false; window.clearTimeout(h) }
}, [q, sort])
const sorted = useMemo(() => rows, [rows])
return (
<div className="rounded-lg border border-white/10 bg-white/[0.02]">
<div className="flex items-center justify-between border-b border-white/10 px-4 py-2">
<div className="text-sm text-white/70">Users</div>
<div className="flex gap-2">
<select value={sort} onChange={e => setSort(e.target.value as 'requests' | 'latency' | 'last_seen')}
className="rounded bg-white/[0.04] px-2 py-1 text-xs text-white/80">
<option value="requests">requests</option>
<option value="latency">latency</option>
<option value="last_seen">last seen</option>
</select>
<input value={q} onChange={e => setQ(e.target.value)} placeholder="search…"
className="rounded bg-white/[0.04] px-2 py-1 text-xs text-white/80 placeholder:text-white/30" />
</div>
</div>
<table className="w-full text-left text-sm">
<thead className="text-xs uppercase text-white/40">
<tr>
<th className="px-4 py-2 font-normal">User</th>
<th className="px-4 py-2 font-normal">Req 7d</th>
<th className="px-4 py-2 font-normal">Last seen</th>
<th className="px-4 py-2 font-normal">Top endpoint</th>
<th className="px-4 py-2 text-right font-normal">Avg ms</th>
</tr>
</thead>
<tbody>
{loading && <tr><td colSpan={5} className="px-4 py-6 text-center text-white/40">loading…</td></tr>}
{!loading && sorted.length === 0 && (
<tr><td colSpan={5} className="px-4 py-6 text-center text-white/40">no users yet</td></tr>
)}
{sorted.map(u => (
<tr key={u.username} className="border-t border-white/5">
<td className="px-4 py-2 text-white/90">
<div className="flex items-center gap-2">
{u.github_avatar_url
? <img src={u.github_avatar_url} alt="" className="h-5 w-5 rounded-full" />
: <span className="inline-block h-5 w-5 rounded-full bg-white/10" />}
<span className="font-mono">{u.username}</span>
</div>
</td>
<td className="px-4 py-2 font-mono text-white/80">{u.requests_7d.toLocaleString()}</td>
<td className="px-4 py-2 text-white/60">{timeAgo(u.last_seen)}</td>
<td className="px-4 py-2 font-mono text-white/60">{u.top_endpoint || '—'}</td>
<td className="px-4 py-2 text-right font-mono text-white/80">{u.avg_latency_ms}</td>
</tr>
))}
</tbody>
</table>
</div>
)
}
+51
View File
@@ -0,0 +1,51 @@
// Read helpers for the /dev dashboard. All four endpoints require a
// Basic-auth session that the browser establishes via the WWW-Authenticate
// challenge the first time the SPA hits /api/dev/summary.
export type Summary = {
requests_7d: number
active_users_7d: number
p50_ms: number
p95_ms: number
renders_7d: number
avg_render_ms: number
daily_requests: { day: string; count: number }[]
}
export type UserRow = {
username: string
requests_7d: number
last_seen: number | null
avg_latency_ms: number
top_endpoint: string
github_avatar_url: string | null
}
export type LatencyRow = {
endpoint: string
count: number
p50: number
p95: number
p99: number
}
export type Health = {
edge_cache_hit_rate: number
fetcher_error_rate: number
events_dropped_24h: number
oldest_event_ts: number | null
}
async function getJSON<T>(path: string): Promise<T> {
const r = await fetch(path, { credentials: 'include' })
if (r.status === 401) throw new Error('unauthorized')
if (r.status === 503) throw new Error('dashboard_disabled')
if (!r.ok) throw new Error(`HTTP ${r.status}`)
return (await r.json()) as T
}
export const fetchSummary = () => getJSON<Summary>('/api/dev/summary')
export const fetchUsers = (q = '', sort = 'requests') =>
getJSON<UserRow[]>(`/api/dev/users?q=${encodeURIComponent(q)}&sort=${sort}`)
export const fetchLatency = () => getJSON<LatencyRow[]>('/api/dev/latency')
export const fetchHealth = () => getJSON<Health>('/api/dev/health')
@@ -0,0 +1,75 @@
import { useEffect, useState } from 'react'
import type { ReactNode } from 'react'
import { fetchSummary, type Summary } from '../lib/dev'
import { StatCards } from '../components/StatCards'
import { UsersTable } from '../components/UsersTable'
import { LatencyChart } from '../components/LatencyChart'
import { HealthStrip } from '../components/HealthStrip'
const REFRESH_MS = 15_000
export function DevScreen() {
const [s, setS] = useState<Summary | null>(null)
const [error, setError] = useState<string | null>(null)
const [lastRefresh, setLastRefresh] = useState<Date>(new Date())
useEffect(() => {
let alive = true
const load = () =>
fetchSummary()
.then(v => { if (!alive) return; setS(v); setError(null); setLastRefresh(new Date()) })
.catch(e => { if (alive) setError(e.message || 'error') })
load()
const h = window.setInterval(load, REFRESH_MS)
return () => { alive = false; window.clearInterval(h) }
}, [])
if (error === 'dashboard_disabled') {
return (
<Shell>
<div className="rounded-lg border border-amber-500/30 bg-amber-500/[0.06] p-6 text-amber-200">
The /dev dashboard is not configured on this deploy
(set DEV_DASHBOARD_USER and DEV_DASHBOARD_PASSWORD).
</div>
</Shell>
)
}
if (error === 'unauthorized') {
return (
<Shell>
<div className="text-white/60">Sign in to view the dashboard. Reload to retry.</div>
</Shell>
)
}
return (
<Shell lastRefresh={lastRefresh}>
{s ? <StatCards s={s} /> : <div className="text-white/40">loading…</div>}
<div className="mt-6">
<UsersTable />
</div>
<div className="mt-6 grid grid-cols-1 gap-4 md:grid-cols-2">
<LatencyChart />
<HealthStrip />
</div>
</Shell>
)
}
function Shell({ children, lastRefresh }: { children: ReactNode; lastRefresh?: Date }) {
return (
<div className="min-h-screen bg-[#0b0d10] px-6 py-6 text-white">
<div className="mx-auto max-w-6xl">
<header className="mb-6 flex items-baseline justify-between">
<h1 className="font-mono text-lg text-white/90">/dev · gh-stats analytics</h1>
{lastRefresh && (
<div className="text-xs text-white/40">
last refresh {lastRefresh.toLocaleTimeString()}
</div>
)}
</header>
{children}
</div>
</div>
)
}