Bring the console onto the contract the Go side now pins
build / build-push (push) Failing after 25s

internal/app/contract_test.go asserts the exact JSON key set of every admin
endpoint, and the console was reading fields that shape does not contain —
which is how a page can be entirely blank while the Go suite is green. The
types file is rewritten against the canonical shapes and every consumer is
fixed onto it.

The page bugs that came out of it:

The cache "Lookups" column read `count` and "Last seen" read `last_seen`; the
cache tracks a hit counter and a byte count per name and sends `hits`, so
there is no last-seen data to show at all. Lookups now reads hits, Last seen
is gone, and the row's bytes are shown. The "Size" card shows bytes_human,
with size as the entry-budget hint it actually is.

The Sources table read `item.enabled`, `item.rules`, `item.bytes`,
`item.updated_at` and `item.err`; those live under `item.meta`, so the table
was blank and the per-row toggle posted `name: undefined`. The refresh toast
counted the names echoed back and said "every source" for an empty list.

The dashboard read `qps` and `total_queries` where the server sends
`queries_per_sec` and `queries_total`, and rendered a `latency`/`p99` block
the dashboard response never contained. The `Partial<Dashboard>`-and-cast
that papered over this is gone. `blocked_pct` arrives as 0..100 from REST and
0..1 over SSE, so formatPercent is 0..100 only and a new formatFraction
handles the SSE frame.

Logs rendered `qtype` as a string; it is a number, with `qtype_name`
alongside, so there is a formatQtype that prefers the name. The Domains page
read `item.list` where the server sends `source`, and showed an Updated column
with no timestamp behind it.

Upstreams treated `healthcheck_interval` and `breaker_cooldown` as numbers of
seconds; they are duration strings now, so the page parses them like the
bootstrap refresh it already handled and the write payload no longer sends the
runtime health fields the server ignores. A group edit stripped the four
server-owned counters before writing, because config.Group would reject them.

`whoami.can_write` and `whoami.read_only` were fetched and never used, so a
read-only API key still showed every Save control. A single whoami fetch now
lives in a session provider behind the app shell, every write control is
gated on it, and a banner says why when the key is read-only. It fails open:
an unreachable probe must not lock an operator out of their own console.

Two server fixes the console work exposed, both pinned by the contract test:

POST /api/blocklists/refresh with a body that omits `names` answered
{"names": null}, and the console counts the names it gets back to build its
toast — so "refresh everything" said "0 sources". A nil slice now becomes an
empty one and the key set does not depend on the request.

blocklist.SourceMeta.duration was a raw time.Duration, so it went out as a
nanosecond count and the console divided by 1e6 to compensate — the only
duration on the wire that was not a duration string. It is a config.Duration
now, and formatDuration parses it like the others.

The contract test grew to cover what the first pass left out: the domain
check in all three of its shapes (match, miss, and an error delivered as 200),
the log clear, the settings validate in both the valid and the malformed case,
the settings save and reload, and the first SSE frame.
This commit is contained in:
developer committed 2026-09-27 18:53:43 +00:00
1 parent 9881d2a095
commit 70d85eac59
21 files changed
+1171 -397

No files matched your search

+28 -2
View File
@@ -7,6 +7,7 @@ import {
Globe,
LayoutDashboard,
ListChecks,
Lock,
LogOut,
Menu,
Network,
@@ -18,9 +19,11 @@ import {
} from 'lucide-react'
import { cn } from '../../lib/cn.ts'
import { logout } from '../../lib/api.ts'
import { useWhoami } from '../../lib/session.ts'
import type { Health } from '../../lib/types.ts'
import { HealthPill } from './HealthPill.tsx'
import { ThemeToggle } from './ThemeToggle.tsx'
import { WhoamiProvider } from './WhoamiProvider.tsx'
import { Tooltip } from '../ui/Tooltip.tsx'
interface NavItem {
@@ -58,6 +61,8 @@ export function AppShell({
const [signingOut, setSigningOut] = useState(false)
const location = useLocation()
const navigate = useNavigate()
// The provider is the app's own, so the shell's header can read it too.
const { readOnly, identity } = useWhoami()
useEffect(() => {
const query = window.matchMedia(MOBILE_QUERY)
@@ -104,7 +109,8 @@ export function AppShell({
const rail = !isMobile && collapsed
return (
<div className="min-h-svh bg-canvas">
<WhoamiProvider>
<div className="min-h-svh bg-canvas">
{/* Desktop rail toggle lives in the top bar; on mobile the bar carries
the hamburger that opens the sheet instead. */}
<header className="fixed inset-x-0 top-0 z-40 flex h-14 items-center gap-2 border-b border-line bg-surface-2 px-3">
@@ -253,10 +259,30 @@ export function AppShell({
)}
>
<div className="mx-auto flex w-full max-w-[1600px] flex-col gap-4 p-3 sm:p-4 lg:p-6">
{readOnly && (
<p
role="status"
className="flex items-start gap-2 rounded-lg border border-warn/40 bg-warn-soft px-3 py-2 text-xs text-fg"
>
<Lock size={14} className="mt-0.5 shrink-0 text-warn" aria-hidden="true" />
<span>
Read-only session
{identity !== '' && (
<>
{' '}
as <span className="font-mono">{identity}</span>
</>
)}
: this credential may read the node but not change it, so every write control
below is disabled. The daemon answers 403 on the write routes for this key.
</span>
</p>
)}
{children}
</div>
</main>
</div>
</div>
</WhoamiProvider>
)
}
@@ -0,0 +1,24 @@
import type { ReactNode } from 'react'
import { useMemo } from 'react'
import { whoami } from '../../lib/api.ts'
import { WhoamiContext } from '../../lib/session.ts'
import type { WhoamiState } from '../../lib/session.ts'
import { useApi } from '../../hooks/useApi.ts'
/**
* Fetches `/api/whoami` once for the whole console and shares it.
*
* The response is the only thing that tells the UI whether this credential may
* change anything: `read_only` on a key makes the API answer 403 on every
* write route, so a console that ignores it offers a Save button that can only
* ever fail. One provider, one request, every page reading the same answer.
*/
export function WhoamiProvider({ children }: { children: ReactNode }) {
const { data, error, loading, refetch } = useApi(() => whoami(), [])
const value = useMemo<WhoamiState>(
() => ({ who: data, error, loading, refetch }),
[data, error, loading, refetch],
)
return <WhoamiContext.Provider value={value}>{children}</WhoamiContext.Provider>
}
+30 -90
View File
@@ -7,30 +7,36 @@
*/
import type {
AddDomainInput,
AddDomainResponse,
BlocklistsResponse,
CacheResponse,
CacheTopResponse,
ClientsPayload,
ClientsResponse,
ClientGroup,
Dashboard,
DefaultPolicy,
DomainAction,
DomainCheck,
DomainCheckResponse,
DomainFilters,
DomainsResponse,
FlushCacheResponse,
LoginInput,
LoginResponse,
LogFilters,
LogItem,
LoginResponse,
LogsResponse,
LiveStats,
OkResponse,
RefreshBlocklistsResponse,
ReloadSettingsResponse,
SaveResponse,
SaveSettingsResponse,
SettingsResponse,
UpstreamBootstrap,
UpstreamPolicy,
UpstreamServer,
StreamReady,
ToggleBlocklistResponse,
UpstreamsPayload,
UpstreamsResponse,
ValidateResponse,
Whoami,
} from './types.ts'
const TOKEN_KEY = 'fancydns.token'
@@ -73,78 +79,10 @@ export function clearToken(): void {
}
}
/** Types the API returns for endpoints the shared types.ts does not name. */
export interface WhoamiResponse {
name: string
mode: string
read_only: boolean
can_write: boolean
auth_mode: string
base_path: string
}
export interface LoginInput {
api_key?: string
username?: string
password?: string
}
export interface RefreshBlocklistsResponse {
started: boolean
names: string[]
}
export interface ToggleBlocklistResponse {
ok: boolean
name: string
enabled: boolean
}
export interface AddDomainInput {
name: string
action: DomainAction | string
list?: string
source?: string
content?: string
}
/** A lookup failure comes back 200 with an `error` string, not a 4xx. */
export type DomainCheckResponse = DomainCheck & { error?: string }
export interface ClientsPayload {
groups: ClientGroup[]
default_policy: DefaultPolicy | string
}
export interface UpstreamsPayload {
policy: UpstreamPolicy | string
servers: UpstreamServer[]
bootstraps: UpstreamBootstrap[]
healthcheck_interval_s?: number
max_attempts?: number
breaker_threshold?: number
}
export interface SaveResponse {
ok: boolean
version: string
warnings?: string[]
}
export interface FlushCacheResponse {
ok: boolean
entries: number
}
export interface ReloadSettingsResponse {
ok: boolean
version: string
}
export type LogStreamHandlers = {
onEntry: (entry: LogItem) => void
onStats: (stats: LiveStats) => void
onReady: (info: { at?: string; version?: string }) => void
onReady: (info: StreamReady) => void
onError: (message: string) => void
onOpen: () => void
}
@@ -280,8 +218,8 @@ export async function logout(): Promise<OkResponse> {
}
}
export function whoami(): Promise<WhoamiResponse> {
return apiFetch<WhoamiResponse>('/api/whoami')
export function whoami(): Promise<Whoami> {
return apiFetch<Whoami>('/api/whoami')
}
export function getDashboard(range: string): Promise<Dashboard> {
@@ -292,14 +230,16 @@ export function getBlocklists(): Promise<BlocklistsResponse> {
return apiFetch<BlocklistsResponse>('/api/blocklists')
}
export async function refreshBlocklists(names?: string[]): Promise<RefreshBlocklistsResponse> {
if (names && names.length > 0) {
return apiFetch<RefreshBlocklistsResponse>('/api/blocklists/refresh', {
method: 'POST',
body: JSON.stringify({ names }),
})
}
return apiFetch<RefreshBlocklistsResponse>('/api/blocklists/refresh', { method: 'POST' })
/**
* A refresh with no names recompiles every source. The body always carries the
* key: the daemon echoes back the list it queued, and an omitted one arrives as
* `null`, which is what made the toast count "0 sources queued".
*/
export async function refreshBlocklists(names: string[] = []): Promise<RefreshBlocklistsResponse> {
return apiFetch<RefreshBlocklistsResponse>('/api/blocklists/refresh', {
method: 'POST',
body: JSON.stringify({ names }),
})
}
export function toggleBlocklist(
@@ -316,8 +256,8 @@ export function getDomains(filters: DomainFilters = {}): Promise<DomainsResponse
return apiFetch<DomainsResponse>(apiUrl('/api/domains', { ...filters }))
}
export function addDomain(input: AddDomainInput): Promise<OkResponse> {
return apiFetch<OkResponse>('/api/domains', {
export function addDomain(input: AddDomainInput): Promise<AddDomainResponse> {
return apiFetch<AddDomainResponse>('/api/domains', {
method: 'POST',
body: JSON.stringify(input),
})
@@ -526,7 +466,7 @@ async function readSse(
} else if (event === 'stats') {
handlers.onStats(payload as LiveStats)
} else if (event === 'ready') {
handlers.onReady(payload as { at?: string; version?: string })
handlers.onReady(payload as StreamReady)
}
}
+100 -10
View File
@@ -23,16 +23,39 @@ export function formatNumber(value: number | null | undefined): string {
return n.toLocaleString('en-US')
}
/** 0.9432 -> "94.3%". Accepts 0..1 (fractions) and 0..100 (percents). */
export function formatPercent(fraction: number | null | undefined, digits = 1): string {
const n = typeof fraction === 'number' && Number.isFinite(fraction) ? fraction : 0
const scaled = n > 1 ? n : n * 100
return `${scaled.toFixed(digits)}%`
/**
* 0.9432 -> "94.3%": a value the server already scaled to 0..100, like
* `blocked_pct` in the dashboard payload. Do not hand it a 0..1 fraction.
*/
export function formatPercent(points: number | null | undefined, digits = 1): string {
const n = typeof points === 'number' && Number.isFinite(points) ? points : 0
return `${n.toFixed(digits)}%`
}
/** 0.043 -> "4.3%" — for rates the API reports as 0..1. */
export function formatRate(fraction: number | null | undefined, digits = 1): string {
return formatPercent(fraction, digits)
/**
* 0.043 -> "4.3%": a 0..1 fraction, which is how the API reports rates
* (`cache_hit_rate`, `fail_rate`) and `blocked_pct` in the SSE stats frame.
* The same key is 0..100 in the dashboard payload, so the unit has to be
* chosen per call site rather than guessed from the value.
*/
export function formatFraction(fraction: number | null | undefined, digits = 1): string {
const n = typeof fraction === 'number' && Number.isFinite(fraction) ? fraction : 0
return formatPercent(n * 100, digits)
}
/**
* A duration STRING from the API ("1.5s", "24h0m0s", "0s") -> a compact
* human form. The Go side marshals every duration that way, so this is the
* only duration form that should appear in a response.
*/
export function formatDuration(value: string | null | undefined): string {
if (!value) return '—'
const m = /^(-?\d+(?:\.\d+)?)(ns|us|µs|ms|s|m|h)(.*)$/.exec(value.trim())
if (!m) return value
const n = Number.parseFloat(m[1])
if (!Number.isFinite(n)) return value
if (n === 0) return '0 ms'
return formatMs(m[2] === 'ns' || m[2] === 'us' || m[2] === 'µs' ? n / 1e6 : n * 1000)
}
/** Milliseconds: 0.42 -> "420 µs", 12.5 -> "12.5 ms", 2400 -> "2.40 s". */
@@ -58,7 +81,14 @@ export function formatUptime(seconds: number | null | undefined): string {
return `${secs}s`
}
/** Parses RFC3339 strings and epoch numbers (seconds or milliseconds). */
/**
* Parses RFC3339 strings and epoch numbers (seconds or milliseconds).
*
* A Go zero time ("0001-01-01T00:00:00Z") is what an unwritten timestamp
* looks like on the wire — `cache.persisted.last_snapshot` before the first
* snapshot, for one — and is not a date, so it reads as "never" rather than
* as a date two thousand years ago.
*/
export function toDate(value: string | number | null | undefined): Date | null {
if (value === null || value === undefined || value === '') return null
if (typeof value === 'number') {
@@ -68,7 +98,9 @@ export function toDate(value: string | number | null | undefined): Date | null {
return Number.isNaN(d.getTime()) ? null : d
}
const d = new Date(value)
return Number.isNaN(d.getTime()) ? null : d
if (Number.isNaN(d.getTime())) return null
if (d.getUTCFullYear() <= 1) return null
return d
}
/** "3 minutes ago" / "in 2 hours". */
@@ -131,6 +163,64 @@ export function formatRcode(rcode: number | string | null | undefined): string {
return `${code} ${RCODE_NAMES[code] ?? 'UNKNOWN'}`
}
/** DNS qtype number -> short name, e.g. 1 -> "A". */
export const QTYPE_NAMES: Record<number, string> = {
1: 'A',
2: 'NS',
3: 'MD',
4: 'MF',
5: 'CNAME',
6: 'SOA',
7: 'MB',
8: 'MG',
9: 'MR',
10: 'NULL',
12: 'PTR',
13: 'HINFO',
15: 'MX',
16: 'TXT',
17: 'RP',
18: 'AFSDB',
24: 'SIG',
25: 'KEY',
28: 'AAAA',
29: 'LOC',
33: 'SRV',
35: 'NAPTR',
39: 'DNAME',
41: 'OPT',
43: 'DS',
44: 'SSHFP',
46: 'RRSIG',
47: 'NSEC',
48: 'DNSKEY',
50: 'NSEC3',
51: 'NSEC3PARAM',
52: 'TLSA',
59: 'CDS',
64: 'SVCB',
65: 'HTTPS',
99: 'SPF',
250: 'TSIG',
251: 'IXFR',
252: 'AXFR',
255: 'ANY',
257: 'CAA',
}
/**
* The qtype of a log row or a cached name: a NUMBER on the wire, with the
* server's own spelling in `name`. Rendering the number alone shows "1" where
* the operator expects "A", so prefer the name and fall back to the number.
*/
export function formatQtype(qtype: number | null | undefined, name?: string | null): string {
if (typeof name === 'string' && name !== '') return name
if (typeof qtype === 'number' && Number.isFinite(qtype)) {
return QTYPE_NAMES[qtype] ?? `TYPE${qtype}`
}
return '—'
}
export const RCODE_NAMES: Record<number, string> = {
0: 'NOERROR',
1: 'FORMERR',
+61
View File
@@ -0,0 +1,61 @@
import { createContext, useContext } from 'react'
import type { Whoami } from './types.ts'
export interface WhoamiState {
who: Whoami | null
error: string | null
loading: boolean
refetch: () => void
}
const noop = (): void => undefined
/**
* Filled in by <WhoamiProvider> once per console. A consumer rendered outside
* it (the login page) sees the defaults, which read as "not known yet".
*/
export const WhoamiContext = createContext<WhoamiState>({
who: null,
error: null,
loading: false,
refetch: noop,
})
export interface Session {
who: Whoami | null
/** The credential is a read-only key: the API answers 403 on every write. */
readOnly: boolean
/** False means "do not offer a write control", not "hide the page". */
canWrite: boolean
/** The key's or user's name, for the read-only banner. */
identity: string
error: string | null
loading: boolean
refetch: () => void
}
/**
* What `/api/whoami` said about the caller.
*
* The two flags are belt and braces — `read_only` is the property of the
* credential and `can_write` is the server's own answer to "may this session
* mutate anything" — so either one being true means read-only.
*
* A failed or absent probe reports `canWrite: true`: the session is then
* unknown rather than read-only, and a write that the server refuses comes
* back as an error toast, which is a better failure than a console that
* hides every control because a probe timed out.
*/
export function useWhoami(): Session {
const { who, error, loading, refetch } = useContext(WhoamiContext)
return {
who,
readOnly: who?.read_only === true || who?.can_write === false,
canWrite: who === null || (who.can_write && !who.read_only),
identity: who?.name ?? '',
error,
loading,
refetch,
}
}
+382 -69
View File
@@ -1,15 +1,61 @@
/** API shapes, mirroring the Go JSON tags exactly. */
/**
* API shapes, mirroring the Go JSON tags exactly.
*
* The server is the authority here. `internal/app/contract_test.go` asserts the
* exact top-level key set of every admin endpoint against a fully wired app, so
* a rename on the Go side fails there with a readable diff; `DUMP_SHAPES=1 go
* test ./internal/app -run TestDumpShapes` prints the real payloads to diff
* against this file. Changing a field name or type below therefore means
* changing that test too — never adding a cast at a call site to quiet the
* typechecker. A type that does not match the wire is worse than a missing one:
* the missing one fails the build, the wrong one ships an empty table.
*
* Two rules the wire forces on this file:
*
* - a field is optional only where the Go side omits it (an `omitempty` tag);
* - a field whose Go type is a slice is `T[] | null`, because a nil slice
* marshals to `null` and not to `[]`.
*/
/** How a whole node is doing; the dashboard's health pill. */
export type Health = 'ok' | 'degraded' | 'down'
/** One upstream server's circuit-breaker view. */
export type UpstreamHealth = 'up' | 'down' | 'degraded'
export type LogAction = 'allow' | 'block' | 'cached' | 'error' | 'drop'
export type DomainAction = 'allow' | 'block'
export type ListFormat = 'auto' | 'hosts' | 'adblock' | 'plain' | 'rpz'
/** The decision the pipeline reached for a query (qlog.Action). */
export type LogAction = 'allow' | 'block' | 'cached' | 'error' | 'drop' | 'refused'
/** What a rule does to the name it matches (blocklist.ParseAction). */
export type DomainAction =
| 'allow'
| 'block'
| 'drop'
| 'nxdomain'
| 'redirect'
| 'passthrough'
| 'zero'
| 'cname'
/** Free-form: config sets a format per source and the manager detects it. */
export type ListFormat = string
export type UpstreamProto = 'udp' | 'tcp' | 'tls'
export type UpstreamPolicy = 'parallel' | 'random' | 'failover'
export type GroupPolicy = 'allow' | 'block_only' | 'deny'
export type DefaultPolicy = 'allow' | 'deny' | 'block_only'
/** The transport a listener was bound with. */
export type ListenerTransport = 'udp' | 'tcp' | 'dot'
/** The identity the server resolved for the caller (GET /api/whoami). */
export interface Whoami {
name: string
mode: string
/** The credential is a read-only key: the API answers 403 on every write. */
read_only: boolean
can_write: boolean
auth_mode: string
base_path: string
}
// --- GET /api/dashboard ----------------------------------------------------
/** One 5s bucket of the rolling counters. `t` is a unix timestamp in seconds. */
export interface SeriesPoint {
t: number
queries: number
@@ -18,61 +64,175 @@ export interface SeriesPoint {
cache_hits: number
}
/** Dashboard top_blocked[] entry. `qtype` is a number; there is no name field. */
export interface TopBlockedDomain {
domain: string
count: number
list: string
qtype: number
}
/** Dashboard top_queried[] entry. */
export interface TopQueriedDomain {
domain: string
count: number
qtype: string
qtype: number
blocked: boolean
}
export interface UpstreamStat {
/** A bound listener, as reported by both /api/dashboard and /api/status. */
export interface ListenerInfo {
transport: ListenerTransport | string
addr: string
proto: string
health: UpstreamHealth
latency_ms: number
fail_rate: number
enabled: boolean
running: boolean
err: string
}
/** Per-transport counters, keyed by transport (udp, tcp, dot, doh). */
export interface TransportStat {
queries: number
avg_ms: number
p95_ms: number
answers: number
dropped: number
errors: number
cache_hits: number
blocked: number
allow: number
sent: number
received: number
}
export interface Dashboard {
/** "ok", "degraded" or "down"; anything else is reported as degraded. */
health: Health
/** A semicolon-joined list of the problems behind a degraded health. */
degraded_reason: string
version: string
node_id: string
uptime_seconds: number
queries_total: number
queries_per_sec: number
errors_total: number
/** Queries in the pipeline right now. */
inflight: number
/** 0..1: hits / (hits + misses). */
cache_hit_rate: number
blocked_total: number
/** 0..100 here, but 0..1 in the SSE stats frame — see formatFraction. */
blocked_pct: number
/** Compiled blocklist rules and live cache entries, for the header line. */
blocklist_rules: number
cache_entries: number
config_version: number
/** Config swaps so far; the cluster uses it to detect divergence. */
generation: number
series: SeriesPoint[]
top_blocked: TopBlockedDomain[]
top_queried: TopQueriedDomain[]
/** Runtime view of the pool, the same objects GET /api/upstreams serves. */
upstreams: UpstreamStat[]
listeners: ListenerInfo[]
transports: Record<string, TransportStat>
/** Only present when the daemon has no query log at all. */
recent?: LogItem[]
}
export interface BlocklistItem {
// --- GET /api/logs and the SSE entry frame ---------------------------------
/**
* One logged query. Every key is always present — the Go struct has no
* `omitempty` — so an absent ACL group is an empty string, not a missing key.
* `qtype`/`rcode` are numbers; `qtype_name`/`rcode_name` are their spellings.
*/
export interface LogItem {
id: number
/** RFC 3339. */
ts: string
client: string
client_group: string
name: string
format: ListFormat | string
qtype: number
qtype_name: string
rcode: number
rcode_name: string
action: LogAction
response: string
duration_ms: number
upstream: string
list: string
protocol: string
blocked: boolean
}
export interface LogsResponse {
items: LogItem[]
total: number
offset: number
limit: number
has_more: boolean
}
/**
* The `stats` frame of GET /api/logs/stream. `blocked_pct` and
* `cache_hit_rate` are 0..1 fractions here, where the dashboard reports
* blocked_pct as 0..100 — so formatFraction, never formatPercentPoints.
*/
export interface LiveStats {
qps: number
blocked_pct: number
cache_hit_rate: number
queries_total: number
blocked_total: number
errors_total: number
inflight: number
uptime_s: number
}
/** The `ready` frame of the stream. */
export interface StreamReady {
at?: string
version?: string
}
// --- GET /api/blocklists ---------------------------------------------------
/** Per-source fetch/parse state, nested under items[].meta. */
export interface BlocklistSourceMeta {
name: string
format: string
enabled: boolean
url: string
path: string
rules: number
bytes: number
updated_at: string
duration_ms: number
/** Fetch+compile time as a duration STRING, like every other duration. */
duration: string
err: string
etag: string
categories: string[]
http_status: number
last_mod: string
stale: boolean
last_modified: string
}
/** What one source's parse produced (blocklist.ParseStats). */
export interface BlocklistParseStats {
format: string
rules: number
comments: number
skipped: number
malformed: number
duplicates: number
bytes: number
duration_ms: number
}
export interface BlocklistItem {
name: string
format: ListFormat
digest: string
meta: BlocklistSourceMeta
stats: BlocklistParseStats
}
export interface BlocklistStats {
@@ -82,24 +242,34 @@ export interface BlocklistStats {
root_rules: number
allow: number
block: number
passthrough: number
drop: number
duplicates: number
sources: number
built_at: string
/** Per-source meta keyed by source name. */
sources_detail: Record<string, BlocklistSourceMeta>
}
export interface BlocklistsResponse {
items: BlocklistItem[]
stats: BlocklistStats
/** Digest of the compiled set, for spotting a mid-roll divergence. */
digest: string
/** Fetch or parse errors keyed by source name. */
errors: Record<string, string>
}
// --- GET /api/domains ------------------------------------------------------
/** One compiled rule. `rule` is the wire form (`*.`/`**.` prefixed). */
export interface DomainItem {
name: string
action: DomainAction | string
list: string
source: string
categories: string[]
categories: string[] | null
hits: number
updated_at: string
rule: string
}
export interface DomainsResponse {
@@ -107,113 +277,191 @@ export interface DomainsResponse {
total: number
page: number
per_page: number
/** The server hit its scan cap, so total is a lower bound. */
truncated: boolean
}
export interface DomainCheck {
/**
* GET /api/domains/check on a name that matched a rule. The keys below are the
* ones the matching path sets; the miss shape has no rule or hits at all.
*/
export interface DomainCheckMatch {
name: string
action: DomainAction | string
query: string
matched: true
action: DomainAction
source: string
categories: string[]
categories: string[] | null
hits: number
rule: string
matched_pattern: string
match_kind: string
}
/** ...and on a name that did not match anything. */
export interface DomainCheckMiss {
name: string
query: string
matched: false
action: 'none'
source: string
}
/** The lookup answers 200 with an error string rather than a 4xx. */
export interface DomainCheckError {
name: string
error: string
}
export type DomainCheckResponse = DomainCheckMatch | DomainCheckMiss | DomainCheckError
// --- GET /api/clients ------------------------------------------------------
export interface ClientMatch {
cidrs: string[]
ptr_suffixes: string[]
tags: string[]
cidrs: string[] | null
ptr_suffixes: string[] | null
tags: string[] | null
any: boolean
}
/** The server's own view of a group, including counters the UI cannot set. */
export interface ClientGroup {
name: string
comment: string
policy: GroupPolicy | string
/** Omitted when the group has none, so it has to stay optional. */
comment?: string
policy: GroupPolicy
match: ClientMatch
allow_domains: string[]
deny_domains: string[]
allow_domains: string[] | null
deny_domains: string[] | null
skip_blocklist: boolean
skip_cache: boolean
rate_limit: number
max_concurrent: number
log_queries: boolean
upstreams: string[]
upstreams: string[] | null
client_count: number
query_count: number
blocked_count: number
matched: boolean
}
export interface ClientsResponse {
groups: ClientGroup[]
default_policy: DefaultPolicy | string
default_policy: DefaultPolicy
default_rate_limit: number
}
export interface UpstreamServer {
/**
* What PUT /api/clients accepts: config.Group and nothing else. The four
* server-owned counters of ClientGroup are refused on a write, so the editor
* must not send them back.
*/
export interface ClientGroupInput {
name: string
comment?: string
policy: GroupPolicy
match: ClientMatch
allow_domains: string[] | null
deny_domains: string[] | null
skip_blocklist: boolean
skip_cache: boolean
rate_limit: number
max_concurrent: number
log_queries: boolean
upstreams: string[] | null
}
export interface ClientsPayload {
groups: ClientGroupInput[]
default_policy: DefaultPolicy
}
// --- GET /api/upstreams ----------------------------------------------------
/**
* One server in the pool, with its runtime health. `comment` and `last_error`
* are omitted when empty.
*/
export interface UpstreamStat {
addr: string
proto: UpstreamProto | string
proto: UpstreamProto
server_name: string
weight: number
comment: string
comment?: string
health: UpstreamHealth
latency_ms: number
fail_rate: number
queries: number
avg_ms: number
p95_ms: number
fail_rate: number
queries: number
failures: number
breaker_open: boolean
last_error?: string
}
export interface UpstreamBootstrap {
name: string
addresses: string[]
addresses: string[] | null
/** A duration STRING ("24h0m0s"), like every other duration on the wire. */
refresh: string
}
export interface UpstreamsResponse {
policy: UpstreamPolicy | string
servers: UpstreamServer[]
policy: UpstreamPolicy
servers: UpstreamStat[]
bootstraps: UpstreamBootstrap[]
/** Duration strings ("30s", "24h0m0s"), not seconds. */
healthcheck_interval: string
breaker_cooldown: string
max_attempts: number
breaker_threshold: number
}
export interface LogItem {
id: number | string
ts: string
client: string
client_group: string
name: string
qtype: string
rcode: number
action: LogAction | string
response: string
duration_ms: number
upstream: string
list: string
/** What PUT /api/upstreams accepts for one server (config.UpstreamServer). */
export interface UpstreamServerInput {
addr: string
proto: UpstreamProto
server_name: string
insecure_skip_verify: boolean
health_name?: string
max_fails?: number
weight: number
comment?: string
}
export interface LogsResponse {
items: LogItem[]
total: number
offset: number
export interface UpstreamsPayload {
policy: UpstreamPolicy
servers: UpstreamServerInput[]
bootstraps: UpstreamBootstrap[]
/**
* The console edits the interval in seconds; the server also accepts the
* duration string under `healthcheck_interval`, and keeps the current value
* when neither is supplied.
*/
healthcheck_interval_s?: number
max_attempts?: number
breaker_threshold?: number
}
export interface LiveStats {
qps: number
blocked_pct: number
cache_hit_rate: number
}
// --- GET /api/cache --------------------------------------------------------
export interface CachePersisted {
enabled: boolean
path: string
bytes: number
entries: number
/** Count of snapshot write errors; there is no error string on the wire. */
errors: number
/** A Go zero time ("0001-01-01T00:00:00Z") until the first snapshot. */
last_snapshot: string
/** True when the warm start read a snapshot at boot. */
loaded: boolean
writes: number
}
export interface CacheResponse {
enabled: boolean
/** Entry budget, not a byte count. */
size: number
entries: number
shards: number
@@ -221,28 +469,40 @@ export interface CacheResponse {
max_ttl_ms: number
serve_stale_ms: number
negative_ttl_ms: number
/** 0..1 fraction. */
hit_rate: number
hits: number
misses: number
stale_hits: number
evictions: number
/** Bytes actually held by cached answers. */
bytes: number
bytes_human: string
persisted: CachePersisted
}
/**
* One cached name. The cache counts hits and bytes per name; it has never
* tracked a lookup count or a last-seen timestamp, so the console must not
* invent columns for them.
*/
export interface CacheTopEntry {
name: string
qtype: string
count: number
qtype: number
qtype_name: string
hits: number
last_seen: string
bytes: number
}
export interface CacheTopResponse {
items: CacheTopEntry[]
}
// --- GET /api/settings -----------------------------------------------------
export interface SettingsResponse {
version: string
/** A config revision counter (an int, not a hash). */
version: number
path: string
config_yaml: string
effective_yaml: string
@@ -254,7 +514,7 @@ export interface SettingsResponse {
export interface SaveSettingsResponse {
ok: boolean
version: string
version: number
warnings: string[]
}
@@ -269,13 +529,58 @@ export interface ValidateResponse {
warnings: ConfigIssue[]
}
// --- Write responses -------------------------------------------------------
export interface OkResponse {
ok: boolean
name?: string
}
export interface AddDomainResponse {
ok: boolean
name: string
/** Rules written, which is more than one for a bulk paste. */
count: number
}
export interface SaveResponse {
ok: boolean
version: number
}
/** `names` is always an array, never null: the source count is real. */
export interface RefreshBlocklistsResponse {
started: boolean
names: string[]
}
export interface ToggleBlocklistResponse {
ok: boolean
name: string
enabled: boolean
}
export interface FlushCacheResponse {
ok: boolean
entries: number
}
export interface ReloadSettingsResponse {
ok: boolean
version: number
}
export interface LoginResponse {
ok: boolean
token?: string
token: string
}
// --- Request bodies the console builds ------------------------------------
export interface LoginInput {
api_key?: string
username?: string
password?: string
}
export interface DomainFilters {
@@ -292,7 +597,15 @@ export interface LogFilters {
q?: string
action?: string
client?: string
rcode?: string
rcode?: number
blocked?: boolean
since?: string
}
export interface AddDomainInput {
name: string
action: DomainAction
list?: string
source?: string
content?: string
}
+56 -44
View File
@@ -11,11 +11,12 @@ import type { ReactNode } from 'react'
import { AlertTriangle, Clock, Layers, RefreshCw, ShieldCheck, Split, Trash2 } from 'lucide-react'
import { checkDomain, getBlocklists, refreshBlocklists, toggleBlocklist } from '../lib/api'
import type { BlocklistItem, BlocklistStats, DomainCheck } from '../lib/types'
import { useWhoami } from '../lib/session.ts'
import type { BlocklistItem, BlocklistStats } from '../lib/types'
import { useApi, useAsyncAction } from '../hooks/useApi'
import { useAutoRefresh } from '../hooks/useAutoRefresh'
import { useDebounced } from '../hooks/useDebounced'
import { formatBytes, formatMs, formatNumber, formatRelative, toDate } from '../lib/format'
import { formatBytes, formatDuration, formatNumber, formatRelative, toDate } from '../lib/format'
import {
Badge,
Button,
@@ -53,24 +54,12 @@ const EMPTY_STATS: BlocklistStats = {
root_rules: 0,
allow: 0,
block: 0,
passthrough: 0,
drop: 0,
duplicates: 0,
sources: 0,
built_at: '',
}
type CheckView = Partial<DomainCheck> & {
list?: string
pattern?: string
error?: string
/** Older daemons called the matched rule "rule". */
rule?: string
matched_pattern?: string
}
/** The lookup endpoint answers 200 with an `error` string, not a 4xx. */
function checkView(value: unknown): CheckView | null {
if (!value || typeof value !== 'object') return null
return value as CheckView
sources_detail: {},
}
function truncate(value: string, max = 42): string {
@@ -80,6 +69,7 @@ function truncate(value: string, max = 42): string {
export default function Blocklists() {
const { toast } = useToast()
const { canWrite } = useWhoami()
const { data, error, loading, refetch } = useApi(() => getBlocklists(), [])
useAutoRefresh(refetch, 15000)
@@ -93,15 +83,16 @@ export default function Blocklists() {
() => (name.length > 0 ? checkDomain(name) : Promise.resolve(null)),
[name],
)
const result = checkView(checked)
const result = checked
const stats = (data?.stats as BlocklistStats | undefined) ?? EMPTY_STATS
const stats = data?.stats ?? EMPTY_STATS
const items: BlocklistItem[] = useMemo(() => data?.items ?? [], [data])
const compiledAgo = useMemo(() => {
const built = toDate(stats.built_at)
if (built) return formatRelative(built.toISOString())
// Fall back to the newest per-source fetch when the set was never compiled.
const newest = items
.map((i) => toDate(i.updated_at))
.map((i) => toDate(i.meta.updated_at))
.filter((d): d is Date => d !== null)
.sort((a, b) => b.getTime() - a.getTime())[0]
return newest ? formatRelative(newest.toISOString()) : 'never'
@@ -136,11 +127,14 @@ export default function Blocklists() {
notify(toast, 'fail', refresh.error ?? 'blocklist refresh failed')
return
}
// The response echoes the names the daemon queued, and an empty list means
// "every source" — counting it would be a toast that says "0 sources".
const queued = res.names ?? []
notify(
toast,
'ok',
names && names.length > 0
? `refresh started for ${names.join(', ')}`
queued.length > 0
? `refresh started for ${queued.join(', ')}`
: 'refresh started for every source',
)
refetch()
@@ -161,41 +155,48 @@ export default function Blocklists() {
]
const rows: Row[] = items.map((item) => {
const enabled = overrides[item.name] ?? item.enabled
// Everything about a source except its name and parse stats lives under
// meta; before that nested shape these columns read fields that never
// arrived, so they rendered blank.
const { meta } = item
const enabled = overrides[item.name] ?? meta.enabled
const busy = pendingRows[item.name] === true
return {
__key: item.name,
name: (
<span className="flex min-w-0 flex-col">
<span className="truncate font-medium">{item.name}</span>
{item.err ? (
<span className="truncate text-xs text-red-600 dark:text-red-400">{item.err}</span>
{meta.err ? (
<span className="truncate text-xs text-red-600 dark:text-red-400">{meta.err}</span>
) : null}
</span>
),
format: <Badge tone="muted">{item.format}</Badge>,
format: <Badge tone="muted">{item.format || meta.format}</Badge>,
enabled: (
<Switch
checked={enabled}
onChange={(next) => void onToggle(item, next)}
label={enabled ? 'on' : 'off'}
disabled={!canWrite}
/>
),
rules: <span className="font-mono text-xs">{formatNumber(item.rules)}</span>,
size: <span className="font-mono text-xs">{formatBytes(item.bytes)}</span>,
rules: <span className="font-mono text-xs">{formatNumber(meta.rules)}</span>,
size: <span className="font-mono text-xs">{formatBytes(meta.bytes)}</span>,
updated: (
<span className="flex items-center gap-1.5 whitespace-nowrap text-xs">
{formatRelative(item.updated_at)}
{item.stale ? <Badge tone="warn">stale</Badge> : null}
{formatRelative(meta.updated_at)}
{meta.stale ? <Badge tone="warn">stale</Badge> : null}
</span>
),
duration: <span className="font-mono text-xs">{formatMs(item.duration_ms)}</span>,
// meta.duration is a duration string on the wire, like every other
// duration the API serves.
duration: <span className="font-mono text-xs">{formatDuration(meta.duration)}</span>,
source: (
<span
className="block max-w-[240px] truncate font-mono text-xs text-slate-500 dark:text-slate-400"
title={item.url || item.path}
title={meta.url || meta.path}
>
{truncate(item.url || item.path)}
{truncate(meta.url || meta.path)}
</span>
),
refresh: (
@@ -203,16 +204,20 @@ export default function Blocklists() {
icon={RefreshCw}
label={`refresh ${item.name}`}
variant="ghost"
disabled={busy}
disabled={busy || !canWrite}
onClick={() => void onRefresh([item.name])}
/>
),
}
})
const action = result?.action ?? null
const matchedList = result?.source || result?.list || ''
const matchedPattern = result?.matched_pattern || result?.rule || result?.pattern || ''
// The lookup answers 200 with an error string instead of a 4xx, so its three
// shapes are told apart by their keys rather than by the status code.
const lookupError = result !== null && 'error' in result ? result.error : null
const match = result !== null && 'matched' in result && result.matched ? result : null
const action = match?.action ?? null
const matchedList = match?.source ?? ''
const matchedPattern = match?.matched_pattern ?? ''
return (
<div className="space-y-4">
@@ -224,6 +229,8 @@ export default function Blocklists() {
icon={RefreshCw}
onClick={() => void onRefresh()}
loading={refresh.pending}
disabled={!canWrite}
title={canWrite ? undefined : 'This API key is read-only'}
>
Refresh all
</Button>
@@ -232,7 +239,12 @@ export default function Blocklists() {
<div className="grid grid-cols-2 gap-3 lg:grid-cols-3 xl:grid-cols-5">
<StatCard label="Total rules" value={formatNumber(stats.total)} icon={Layers} />
<StatCard label="Sources" value={formatNumber(stats.sources)} hint={`${items.filter((i) => i.enabled).length} enabled`} />
<StatCard
label="Sources"
value={formatNumber(stats.sources)}
hint={`${items.filter((i) => i.meta.enabled).length} enabled`}
icon={Layers}
/>
<StatCard
label="Allow rules"
value={formatNumber(stats.allow)}
@@ -280,12 +292,12 @@ export default function Blocklists() {
<p className="text-sm text-slate-500">Checking {name}…</p>
) : checkError ? (
<p className="text-sm text-red-600 dark:text-red-400">{checkError}</p>
) : result?.error ? (
) : lookupError !== null ? (
<p className="flex items-center gap-2 text-sm text-red-600 dark:text-red-400">
<AlertTriangle size={14} aria-hidden="true" />
{result.error}
{lookupError}
</p>
) : result ? (
) : match !== null ? (
<div className="flex flex-wrap items-center gap-2 text-sm">
<Badge tone={action === 'allow' ? 'default' : 'warn'}>{action ?? 'unknown'}</Badge>
<span className="font-mono text-xs">{name}</span>
@@ -296,11 +308,11 @@ export default function Blocklists() {
rule: <span className="font-mono">{matchedPattern || '—'}</span>
</span>
<span className="text-xs text-slate-500 dark:text-slate-400">
hits: <span className="font-mono">{formatNumber(result.hits ?? 0)}</span>
hits: <span className="font-mono">{formatNumber(match.hits)}</span>
</span>
{Array.isArray(result.categories) && result.categories.length > 0 ? (
{match.categories !== null && match.categories.length > 0 ? (
<span className="flex flex-wrap gap-1">
{result.categories.map((c) => (
{match.categories.map((c) => (
<Badge key={c} tone="info">
{c}
</Badge>
+41 -26
View File
@@ -18,10 +18,18 @@ import {
import { Database, FileClock, Gauge, HardDrive, Layers, RefreshCw, Timer } from 'lucide-react'
import { flushCache, getCache, getCacheTop } from '../lib/api'
import { useWhoami } from '../lib/session.ts'
import type { CachePersisted, CacheTopEntry } from '../lib/types'
import { useApi, useAsyncAction } from '../hooks/useApi'
import { useAutoRefresh } from '../hooks/useAutoRefresh'
import { formatBytes, formatMs, formatNumber, formatRate, formatRelative } from '../lib/format'
import {
formatBytes,
formatFraction,
formatMs,
formatNumber,
formatQtype,
formatRelative,
} from '../lib/format'
import {
Badge,
Button,
@@ -44,11 +52,16 @@ const TOP_LIMIT = 50
const HITS = '#34d399'
const MISSES = '#f87171'
/** `persisted` gained fields over time; read defensively. */
type PersistedView = Partial<CachePersisted> & {
errors?: number
error?: string
last_error?: string
/** What the page renders before the first response lands. */
const EMPTY_PERSISTED: CachePersisted = {
enabled: false,
path: '',
bytes: 0,
entries: 0,
errors: 0,
last_snapshot: '',
loaded: false,
writes: 0,
}
type PieSlice = { name: string; value: number; fill: string }
@@ -81,6 +94,7 @@ function ChartTip({ active, payload }: TipProps) {
export default function Cache() {
const { toast } = useToast()
const { canWrite } = useWhoami()
const notify = (title: string, description?: string, tone: 'ok' | 'fail' = 'fail'): void =>
toast({ title, description, tone: tone === 'ok' ? 'ok' : 'danger' })
@@ -113,9 +127,8 @@ export default function Cache() {
[hits, misses],
)
const persisted: PersistedView = (data?.persisted ?? {}) as PersistedView
const persistErrors = persisted.errors ?? 0
const persistMessage = persisted.last_error ?? persisted.error ?? ''
const persisted: CachePersisted = data?.persisted ?? EMPTY_PERSISTED
const persistErrors = persisted.errors
const entries: CacheTopEntry[] = useMemo(() => top?.items ?? [], [top])
@@ -137,12 +150,13 @@ export default function Cache() {
if (error) return <PageError error={error} onRetry={refetch} />
// The cache counts hits and bytes per name and tracks no timestamp at all,
// so those are the only two columns the ranking can honestly show.
const topColumns = [
{ key: 'name', header: 'Name', width: '48%' },
{ key: 'name', header: 'Name', width: '54%' },
{ key: 'qtype', header: 'Type', width: '10%' },
{ key: 'count', header: 'Lookups', width: '14%', align: 'right' as const },
{ key: 'hits', header: 'Served from cache', width: '14%', align: 'right' as const },
{ key: 'last_seen', header: 'Last seen', width: '14%', align: 'right' as const },
{ key: 'hits', header: 'Lookups', width: '18%', align: 'right' as const },
{ key: 'bytes', header: 'Size', width: '18%', align: 'right' as const },
]
const topRows: Row[] = entries.map((entry) => ({
@@ -152,10 +166,9 @@ export default function Cache() {
{entry.name}
</span>
),
qtype: <span className="font-mono text-xs">{entry.qtype || '—'}</span>,
count: <span className="font-mono text-xs">{formatNumber(entry.count)}</span>,
qtype: <span className="font-mono text-xs">{formatQtype(entry.qtype, entry.qtype_name)}</span>,
hits: <span className="font-mono text-xs">{formatNumber(entry.hits)}</span>,
last_seen: <span className="text-xs text-fg-muted">{formatRelative(entry.last_seen)}</span>,
bytes: <span className="font-mono text-xs">{formatBytes(entry.bytes)}</span>,
}))
return (
@@ -169,6 +182,8 @@ export default function Cache() {
icon={RefreshCw}
onClick={() => setConfirmFlush(true)}
loading={flush.pending}
disabled={!canWrite}
title={canWrite ? undefined : 'This API key is read-only'}
>
Flush cache
</Button>
@@ -185,9 +200,9 @@ export default function Cache() {
/>
<StatCard
label="Size"
value={formatBytes(data?.size ?? 0)}
value={data?.bytes_human || formatBytes(data?.bytes ?? 0)}
icon={HardDrive}
hint={`${formatNumber(lookups)} lookups`}
hint={`budget of ${formatNumber(data?.size ?? 0)} entries`}
/>
<StatCard
label="Shards"
@@ -218,7 +233,7 @@ export default function Cache() {
<div className="grid grid-cols-1 gap-3 xl:grid-cols-2">
<Card
title="Hit rate"
subtitle={`${formatRate(hitRate)} of ${formatNumber(lookups)} lookups served from memory`}
subtitle={`${formatFraction(hitRate)} of ${formatNumber(lookups)} lookups served from memory`}
>
<CardBody>
<div className="flex flex-col items-center gap-3 sm:flex-row">
@@ -244,7 +259,7 @@ export default function Cache() {
</ResponsiveContainer>
<div className="pointer-events-none absolute inset-0 grid place-items-center">
<div className="text-center">
<p className="tabular text-xl font-semibold text-fg">{formatRate(hitRate, 0)}</p>
<p className="tabular text-xl font-semibold text-fg">{formatFraction(hitRate, 0)}</p>
<p className="text-xs text-fg-muted">hit rate</p>
</div>
</div>
@@ -340,18 +355,18 @@ export default function Cache() {
<dd className="mt-0.5 text-sm">{formatRelative(persisted.last_snapshot)}</dd>
</div>
</dl>
{persistMessage !== '' && (
<p className="mt-3 rounded-lg border border-danger/30 bg-danger-soft px-3 py-2 text-xs text-danger">
{persistMessage}
</p>
)}
<p className="mt-3 rounded-lg border border-line bg-surface-2 px-3 py-2 text-xs text-fg-muted">
{persisted.loaded
? 'The daemon loaded a snapshot at boot, so the cache was warm on the first query.'
: 'No snapshot was loaded at boot: the first query after a restart went upstream.'}
</p>
</CardBody>
</Card>
</div>
<Card
title="Most requested"
subtitle={`Top ${TOP_LIMIT} names by lookups`}
subtitle={`Top ${TOP_LIMIT} names by the cache's own hit counter`}
padded={false}
actions={<Badge tone="muted">auto-refresh every 15s</Badge>}
>
+74 -18
View File
@@ -11,9 +11,10 @@ import { useMemo, useState } from 'react'
import { Copy, Pencil, Plus, Trash2, Users } from 'lucide-react'
import { ApiError, getClients, putClients } from '../lib/api'
import type { ClientGroup, ClientMatch } from '../lib/types'
import { useWhoami } from '../lib/session.ts'
import type { ClientGroup, ClientGroupInput, ClientsPayload, DefaultPolicy, GroupPolicy } from '../lib/types'
import { useApi, useAsyncAction } from '../hooks/useApi'
import { fromLines, toLines } from '../lib/format'
import { fromLines, toLines, formatNumber } from '../lib/format'
import {
Badge,
Button,
@@ -97,7 +98,15 @@ function toNumber(value: string): number {
return Number.isFinite(n) && n > 0 ? n : 0
}
function matchOf(g: ClientGroup): ClientMatch {
/** A match with every list present; the API sends null for an empty one. */
interface MatchLists {
cidrs: string[]
ptr_suffixes: string[]
tags: string[]
any: boolean
}
function matchOf(g: ClientGroup): MatchLists {
const m = g.match
return {
cidrs: m?.cidrs ?? [],
@@ -143,11 +152,11 @@ function fromGroup(g: ClientGroup): GroupDraft {
}
}
function toGroup(d: GroupDraft): ClientGroup {
function toGroup(d: GroupDraft): ClientGroupInput {
return {
name: d.name.trim(),
comment: d.comment,
policy: d.policy,
policy: d.policy as GroupPolicy,
match: {
cidrs: toLines(d.cidrs),
ptr_suffixes: toLines(d.ptr_suffixes),
@@ -165,6 +174,33 @@ function toGroup(d: GroupDraft): ClientGroup {
}
}
/**
* The write shape of a group read from the server.
*
* A summary carries four server-owned counters (client_count, query_count,
* blocked_count, matched) that config.Group does not have; sending them back
* is exactly what the API answers 400 to, so they are dropped here rather
* than quietly riding along.
*/
function toInput(g: ClientGroup): ClientGroupInput {
return {
name: g.name,
comment: g.comment,
policy: g.policy,
// The match lists are normalised, so a null from the API cannot be echoed
// straight back into the write payload.
match: matchOf(g),
allow_domains: g.allow_domains,
deny_domains: g.deny_domains,
skip_blocklist: g.skip_blocklist,
skip_cache: g.skip_cache,
rate_limit: g.rate_limit,
max_concurrent: g.max_concurrent,
log_queries: g.log_queries,
upstreams: g.upstreams,
}
}
/** `groups[2].match.cidrs` -> `cidrs`. */
function fieldLeaf(path: string): string {
const cleaned = path.replace(/^groups\[\d+\]\.?/, '').replace(/^groups\.\d+\.?/, '')
@@ -174,6 +210,7 @@ function fieldLeaf(path: string): string {
export default function Clients() {
const { toast } = useToast()
const { canWrite } = useWhoami()
const { data, error, loading, refetch } = useApi(() => getClients(), [])
const groups = useMemo<ClientGroup[]>(() => data?.groups ?? [], [data])
@@ -187,7 +224,7 @@ export default function Clients() {
const effectiveDefault = defaultDraft ?? defaultPolicy ?? String(data?.default_policy ?? 'allow')
const save = useAsyncAction(async (payload: { groups: ClientGroup[]; default_policy: string }) => {
const save = useAsyncAction(async (payload: ClientsPayload) => {
try {
return await putClients(payload)
} catch (err) {
@@ -214,11 +251,14 @@ export default function Clients() {
}
const commit = async (
nextGroups: ClientGroup[],
nextGroups: ClientGroupInput[],
nextDefault: string,
message: string,
): Promise<boolean> => {
const res = await save.run({ groups: nextGroups, default_policy: nextDefault })
const res = await save.run({
groups: nextGroups,
default_policy: nextDefault as DefaultPolicy,
})
if (res === null) {
notify(toast, 'fail', save.error ?? 'the server rejected the client groups')
return false
@@ -261,7 +301,7 @@ export default function Clients() {
return
}
const group = toGroup(draft)
const next = [...groups]
const next = groups.map(toInput)
if (editingIndex !== null && next[editingIndex]) {
next[editingIndex] = group
} else {
@@ -278,7 +318,7 @@ export default function Clients() {
if (index === null) return
const group = groups[index]
if (!group) return
const next = groups.filter((_, i) => i !== index)
const next = groups.filter((_, i) => i !== index).map(toInput)
if (await commit(next, effectiveDefault, `deleted ${group.name}`)) {
setPendingDelete(null)
}
@@ -286,7 +326,7 @@ export default function Clients() {
const saveDefault = async (next: string): Promise<void> => {
setDefaultDraft(next)
const ok = await commit(groups, next, `default policy set to ${next}`)
const ok = await commit(groups.map(toInput), next, `default policy set to ${next}`)
if (!ok) {
setDefaultDraft(null)
return
@@ -302,18 +342,28 @@ export default function Clients() {
title="Clients"
description="Group clients by network, reverse-DNS name or tag and give each group its own policy."
actions={
<Button icon={Plus} onClick={openNew}>
<Button
icon={Plus}
onClick={openNew}
disabled={!canWrite}
title={canWrite ? undefined : 'This API key is read-only'}
>
Add group
</Button>
}
/>
<Card title="Default policy" subtitle="Applied to clients that match no group.">
<Card
title="Default policy"
subtitle={`Applied to clients that match no group. Default rate limit: ${
formatNumber(data?.default_rate_limit ?? 0)
} qps`}
>
<div className="w-full sm:max-w-xs">
<Select
label="Policy"
value={effectiveDefault}
disabled={loading || save.pending}
disabled={loading || save.pending || !canWrite}
onChange={(e) => void saveDefault(e.target.value)}
options={DEFAULT_POLICIES}
/>
@@ -326,7 +376,12 @@ export default function Clients() {
title="No client groups"
description="Without a group every client gets the default policy."
action={
<Button icon={Plus} onClick={openNew}>
<Button
icon={Plus}
onClick={openNew}
disabled={!canWrite}
title={canWrite ? undefined : 'This API key is read-only'}
>
Add the first group
</Button>
}
@@ -362,12 +417,13 @@ export default function Clients() {
</div>
</div>
<div className="flex shrink-0 gap-1">
<IconButton icon={Pencil} label={`edit ${group.name}`} variant="ghost" onClick={() => openEdit(i)} />
<IconButton icon={Copy} label={`duplicate ${group.name}`} variant="ghost" onClick={() => duplicate(i)} />
<IconButton icon={Pencil} label={`edit ${group.name}`} variant="ghost" disabled={!canWrite} onClick={() => openEdit(i)} />
<IconButton icon={Copy} label={`duplicate ${group.name}`} variant="ghost" disabled={!canWrite} onClick={() => duplicate(i)} />
<IconButton
icon={Trash2}
label={`delete ${group.name}`}
variant="ghost"
disabled={!canWrite}
onClick={() => setPendingDelete(i)}
/>
</div>
@@ -388,7 +444,7 @@ export default function Clients() {
<Button variant="ghost" onClick={() => setEditorOpen(false)} disabled={save.pending}>
Cancel
</Button>
<Button onClick={() => void saveGroup()} loading={save.pending}>
<Button onClick={() => void saveGroup()} loading={save.pending} disabled={!canWrite}>
{editingIndex === null ? 'Create group' : 'Save changes'}
</Button>
</div>
+60 -43
View File
@@ -3,8 +3,10 @@
*
* Everything on it is a single `/api/dashboard` fetch for the selected range;
* the charts are pure functions of `series`, so they never need their own
* polling. The server builds that payload, so every field is read defensively:
* a node running an older build simply shows less, it never throws.
* polling. The field names below are the ones the server sends, and they are
* pinned by `internal/app/contract_test.go` — renaming one here means renaming
* it there. Note the two units the same key arrives in: `blocked_pct` is 0..100
* from this endpoint and 0..1 in the SSE stats frame the Logs page reads.
*/
import { useMemo } from 'react'
@@ -34,7 +36,8 @@ import {
formatMs,
formatNumber,
formatPercent,
formatRate,
formatFraction,
formatQtype,
formatUptime,
} from '../lib/format'
import { Badge, Button, Card, CardBody, EmptyState, Progress, StatCard, Table } from '../components/ui'
@@ -48,21 +51,35 @@ const CACHED = '#34d399'
const BLOCKED = '#f59e0b'
const ERRORS = '#f87171'
/** The parts of the dashboard payload that older daemons may not send. */
type DashboardView = Partial<DashboardData> & {
degraded_reason?: string
reason?: string
message?: string
latency?: { p50_ms?: number; p95_ms?: number; p99_ms?: number }
recent?: LogItem[]
/** The typed payload; the only drift allowed is a build that predates a key. */
const EMPTY_DASHBOARD: DashboardData = {
health: 'ok',
degraded_reason: '',
version: '',
node_id: '',
uptime_seconds: 0,
queries_total: 0,
queries_per_sec: 0,
errors_total: 0,
inflight: 0,
cache_hit_rate: 0,
blocked_total: 0,
blocked_pct: 0,
blocklist_rules: 0,
cache_entries: 0,
config_version: 0,
generation: 0,
series: [],
top_blocked: [],
top_queried: [],
upstreams: [],
listeners: [],
transports: {},
recent: [],
}
type Row = Record<string, ReactNode>
function view(data: DashboardData | null): DashboardView {
return (data ?? {}) as DashboardView
}
type TipProps = {
active?: boolean
label?: number | string
@@ -98,36 +115,33 @@ function healthTone(health: string | undefined): 'default' | 'ok' | 'warn' | 'da
return 'danger'
}
function seriesOf(d: DashboardView) {
return d.series ?? []
}
export default function Dashboard() {
const { range, setRange } = useTimeRange('1h')
const { data, error, loading, refetch } = useApi(() => getDashboard(range), [range])
useAutoRefresh(refetch, 5000)
const d = view(data)
// Typed end to end: the server builds this payload, so there is no reason
// to read it defensively. A node running an older build shows less.
const d = data ?? EMPTY_DASHBOARD
const series = useMemo(() => seriesOf(d), [d])
const upstreams = useMemo(() => d.upstreams ?? [], [d])
const series = d.series
const upstreams = d.upstreams
const slowest = useMemo(
() => upstreams.reduce((max, u) => Math.max(max, u.latency_ms || 0), 0),
[upstreams],
)
const topBlocked = useMemo(() => d.top_blocked ?? [], [d])
const topQueried = useMemo(() => d.top_queried ?? [], [d])
const topBlocked = d.top_blocked
const topQueried = d.top_queried
const hitRate = d.cache_hit_rate ?? 0
const p99 = d.latency?.p99_ms
const p95Fallback = useMemo(() => {
const hitRate = d.cache_hit_rate
// The dashboard reports the slowest upstream's p95, because it has no
// end-to-end latency series; the number is real either way.
const p95 = useMemo(() => {
const values = upstreams.map((u) => u.p95_ms || 0).filter((v) => v > 0)
return values.length > 0 ? Math.max(...values) : undefined
}, [upstreams])
const latencyValue = p99 ?? p95Fallback
const latencyLabel = p99 != null ? 'p99 latency' : 'p95 latency'
const degraded = d.health != null && d.health !== 'ok'
const degraded = d.health !== 'ok'
const degradedReason =
d.degraded_reason ?? d.reason ?? d.message ?? 'no reason reported by the server'
d.degraded_reason !== '' ? d.degraded_reason : 'no reason reported by the server'
if (error) return <PageError error={error} onRetry={refetch} />
@@ -160,7 +174,7 @@ export default function Dashboard() {
</span>
),
fail: (
<span className="font-mono text-xs">{u.fail_rate > 0 ? formatRate(u.fail_rate) : '—'}</span>
<span className="font-mono text-xs">{u.fail_rate > 0 ? formatFraction(u.fail_rate) : '—'}</span>
),
queries: <span className="font-mono text-xs">{formatNumber(u.queries)}</span>,
}))
@@ -234,34 +248,37 @@ export default function Dashboard() {
<div className="grid grid-cols-1 gap-3 sm:grid-cols-2 xl:grid-cols-4">
<StatCard
label="Queries / s"
value={formatCompact(d.queries_per_sec ?? 0)}
hint={`${formatNumber(d.queries_total ?? 0)} total`}
value={formatCompact(d.queries_per_sec)}
hint={`${formatNumber(d.queries_total)} total`}
icon={Activity}
/>
<StatCard
label="Cache hit rate"
value={formatRate(hitRate)}
value={formatFraction(hitRate)}
hint="higher is better"
icon={Gauge}
tone={hitRate >= 0.7 ? 'ok' : hitRate >= 0.4 ? 'warn' : 'danger'}
/>
<StatCard
label="Blocked"
value={formatPercent(d.blocked_pct ?? 0)}
hint={`${formatNumber(d.blocked_total ?? 0)} queries`}
value={formatPercent(d.blocked_pct)}
hint={`${formatNumber(d.blocked_total)} queries`}
icon={Ban}
/>
<StatCard
label={latencyLabel}
value={latencyValue != null ? formatMs(latencyValue) : '—'}
hint={p99 != null ? 'from the server' : 'slowest upstream p95'}
label="p95 latency"
value={p95 != null ? formatMs(p95) : '—'}
hint="slowest upstream"
icon={Timer}
/>
</div>
<p className="text-xs text-slate-500 dark:text-slate-400">
version {d.version || 'unknown'} · up {formatUptime(d.uptime_seconds ?? 0)}
{d.node_id ? ` · node ${d.node_id}` : ''} · auto-refreshing every 5s
version {d.version || 'unknown'} · up {formatUptime(d.uptime_seconds)}
{d.node_id !== '' ? ` · node ${d.node_id}` : ''} · {formatNumber(d.blocklist_rules)} rules
· {formatNumber(d.cache_entries)} cached · {formatNumber(d.errors_total)} errors ·{' '}
{formatNumber(d.inflight)} in flight · config v{formatNumber(d.config_version)}
{` (generation ${formatNumber(d.generation)})`} · auto-refreshing every 5s
</p>
<div className="grid grid-cols-1 gap-3 xl:grid-cols-2">
@@ -434,7 +451,7 @@ export default function Dashboard() {
<Card
title="Upstreams"
subtitle="Health, latency relative to the slowest server, and fail rate"
actions={<HealthPill health={d.health ?? 'down'} />}
actions={<HealthPill health={d.health} />}
>
<CardBody>
<div className="overflow-x-auto">
@@ -459,7 +476,7 @@ export default function Dashboard() {
{topQueried.slice(0, 15).map((q) => (
<li key={`${q.domain}-${q.qtype}`} className="flex items-center gap-2 px-4 py-2 text-sm">
<Badge tone={q.blocked ? 'warn' : 'default'}>
{q.qtype || '?'}
{formatQtype(q.qtype)}
</Badge>
<span className="min-w-0 flex-1 truncate font-mono text-xs">{q.domain}</span>
<span className="font-mono text-xs text-slate-500">{formatNumber(q.count)}</span>
+36 -26
View File
@@ -11,11 +11,11 @@ import type { ReactNode } from 'react'
import { Plus, Search, Trash2 } from 'lucide-react'
import { addDomain, deleteDomain, getDomains } from '../lib/api'
import type { AddDomainInput } from '../lib/api'
import type { DomainItem } from '../lib/types'
import { useWhoami } from '../lib/session.ts'
import type { AddDomainInput, DomainAction, DomainItem } from '../lib/types'
import { useApi, useAsyncAction } from '../hooks/useApi'
import { useDebounced } from '../hooks/useDebounced'
import { formatNumber, formatRelative, toLines } from '../lib/format'
import { formatNumber, toLines } from '../lib/format'
import {
Badge,
Button,
@@ -90,6 +90,7 @@ const EMPTY_FORM: AddForm = { name: '', action: 'block', list: '', bulk: '', adv
export default function Domains() {
const { toast } = useToast()
const { canWrite } = useWhoami()
const [search, setSearch] = useState('')
const [action, setAction] = useState('')
const [list, setList] = useState('')
@@ -130,7 +131,6 @@ export default function Domains() {
const lists = useMemo(() => {
const seen = new Set<string>()
for (const item of items) {
if (item.list) seen.add(item.list)
if (item.source) seen.add(item.source)
}
return Array.from(seen).sort()
@@ -153,7 +153,7 @@ export default function Domains() {
if (ruleName === '') continue
const res = await add.run({
name: ruleName,
action: allow ? 'allow' : form.action,
action: allow ? 'allow' : (form.action as DomainAction),
list: form.list.trim() || undefined,
source: 'console',
content: '',
@@ -167,7 +167,7 @@ export default function Domains() {
} else {
const res = await add.run({
name: form.name.trim(),
action: form.action,
action: form.action as DomainAction,
list: form.list.trim() || undefined,
source: 'console',
content: '',
@@ -187,7 +187,7 @@ export default function Domains() {
const confirmDelete = async (): Promise<void> => {
const target = pendingDelete
if (!target) return
const res = await remove.run(target.name, String(target.action), target.list || target.source)
const res = await remove.run(target.name, String(target.action), target.source)
if (res === null) {
notify(toast, 'fail', remove.error ?? `could not delete ${target.name}`)
return
@@ -199,31 +199,36 @@ export default function Domains() {
if (error) return <PageError error={error} onRetry={refetch} />
// The rule list has no per-rule timestamp to show — the API reports name,
// action, source, categories, hits and the wire form, and nothing else.
const columns = [
{ key: 'name', header: 'Domain', width: '40%' },
{ key: 'name', header: 'Domain', width: '46%' },
{ key: 'action', header: 'Action', width: '16%' },
{ key: 'source', header: 'List', width: '20%' },
{ key: 'source', header: 'List', width: '22%' },
{ key: 'hits', header: 'Hits', width: '10%', align: 'right' as const },
{ key: 'updated', header: 'Updated', width: '10%' },
{ key: 'delete', header: '', width: '4%', align: 'right' as const },
]
const rows: Row[] = items.map((item, i) => ({
__key: `${item.name}-${item.action}-${item.list}-${i}`,
name: <span className="block max-w-[320px] truncate font-mono text-xs">{item.name}</span>,
__key: `${item.name}-${item.action}-${item.source}-${i}`,
name: (
<span className="block max-w-[320px] truncate font-mono text-xs" title={item.rule}>
{item.name}
</span>
),
action: <Badge tone={actionTone(String(item.action))}>{item.action}</Badge>,
source: (
<span className="block max-w-[200px] truncate text-xs text-slate-500 dark:text-slate-400">
{item.list || item.source || '—'}
{item.source || '—'}
</span>
),
hits: <span className="font-mono text-xs">{formatNumber(item.hits)}</span>,
updated: <span className="whitespace-nowrap text-xs">{formatRelative(item.updated_at)}</span>,
delete: (
<IconButton
icon={Trash2}
label={`delete ${item.name}`}
variant="ghost"
disabled={!canWrite}
onClick={() => setPendingDelete(item)}
/>
),
@@ -235,7 +240,12 @@ export default function Domains() {
title="Domains"
description="Inline allow and block rules, checked before the downloaded lists."
actions={
<Button icon={Plus} onClick={() => setAddOpen(true)}>
<Button
icon={Plus}
onClick={() => setAddOpen(true)}
disabled={!canWrite}
title={canWrite ? undefined : 'This API key is read-only'}
>
Add rule
</Button>
}
@@ -301,7 +311,7 @@ export default function Domains() {
<Button variant="ghost" onClick={() => setAddOpen(false)} disabled={add.pending}>
Cancel
</Button>
<Button onClick={() => void submit()} loading={add.pending} disabled={!canSubmit}>
<Button onClick={() => void submit()} loading={add.pending} disabled={!canSubmit || !canWrite}>
{bulkLines.length > 0 ? `Add ${bulkLines.length} rules` : 'Add rule'}
</Button>
</div>
@@ -313,16 +323,16 @@ export default function Domains() {
{formError}
</p>
) : null}
<Input
label="Domain"
placeholder="ads.example.com"
hint={NAME_HINT}
value={form.name}
onChange={(e) => setForm((f) => ({ ...f, name: e.target.value }))}
disabled={form.advanced}
autoComplete="off"
spellCheck={false}
/>
<Input
label="Domain"
placeholder="ads.example.com"
hint={NAME_HINT}
value={form.name}
onChange={(e) => setForm((f) => ({ ...f, name: e.target.value }))}
disabled={form.advanced}
autoComplete="off"
spellCheck={false}
/>
<div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
<Select
label="Action"
+2 -2
View File
@@ -13,7 +13,7 @@ import { Globe, KeyRound, LogIn, ShieldCheck, Terminal } from 'lucide-react'
import { useSearchParams } from 'react-router-dom'
import { ApiError, login, whoami } from '../lib/api'
import type { WhoamiResponse } from '../lib/api'
import type { Whoami } from '../lib/types'
import { Button, Card, CardBody, Input } from '../components/ui'
import { Spinner } from '../components/ui'
@@ -36,7 +36,7 @@ export default function Login() {
useEffect(() => {
let live = true
whoami()
.then((who: WhoamiResponse) => {
.then((who: Whoami) => {
if (live) setMode(who.auth_mode ?? 'apikey')
})
.catch(() => {
+18 -15
View File
@@ -13,6 +13,7 @@ import type { ReactNode } from 'react'
import { Eraser, Radio, Search, Signal, WifiOff } from 'lucide-react'
import { clearLogs, getLogs, streamLogs } from '../lib/api'
import { useWhoami } from '../lib/session.ts'
import type { LogFilters, LogItem, LiveStats } from '../lib/types'
import { useApi, useAsyncAction } from '../hooks/useApi'
import { useAutoRefresh } from '../hooks/useAutoRefresh'
@@ -20,10 +21,10 @@ import { useDebounced } from '../hooks/useDebounced'
import {
formatClock,
formatCompact,
formatFraction,
formatMs,
formatNumber,
formatPercent,
formatRate,
formatQtype,
formatRcode,
} from '../lib/format'
import { cn } from '../lib/cn'
@@ -112,17 +113,9 @@ function matches(entry: LogItem, filter: Filter): boolean {
return true
}
/** Older daemons omit stats fields; a missing counter reads as zero, not NaN. */
function liveStats(stats: LiveStats): LiveStats {
return {
qps: Number(stats.qps) || 0,
blocked_pct: Number(stats.blocked_pct) || 0,
cache_hit_rate: Number(stats.cache_hit_rate) || 0,
}
}
export default function Logs() {
const { toast } = useToast()
const { canWrite } = useWhoami()
const notify = (title: string, description?: string, tone: 'ok' | 'fail' = 'fail'): void =>
toast({ title, description, tone: tone === 'ok' ? 'ok' : 'danger' })
@@ -185,7 +178,7 @@ export default function Logs() {
if (!matches(entry, filterRef.current)) return
setLiveRows((prev) => [entry, ...prev].slice(0, MAX_ROWS))
},
onStats: (next) => setStats(liveStats(next)),
onStats: (next) => setStats(next),
onReady: () => setConnected(true),
onOpen: () => {
setConnected(true)
@@ -251,7 +244,9 @@ export default function Logs() {
{entry.name}
</span>
),
qtype: <span className="font-mono text-xs">{entry.qtype || '—'}</span>,
qtype: (
<span className="font-mono text-xs">{formatQtype(entry.qtype, entry.qtype_name)}</span>
),
rcode: <span className="font-mono text-xs text-fg-muted">{formatRcode(entry.rcode)}</span>,
action: <Badge tone={actionTone(entry.action)}>{entry.action || 'unknown'}</Badge>,
duration: <span className="font-mono text-xs">{formatMs(entry.duration_ms)}</span>,
@@ -267,9 +262,12 @@ export default function Logs() {
),
}))
// The stats frame is a 1s sample. Its qps and rates are 0..1 fractions, which
// is not the unit blocked_pct has on the dashboard payload.
const qps = stats?.qps ?? 0
const blockedPct = stats?.blocked_pct ?? 0
const hitRate = stats?.cache_hit_rate ?? 0
const inflight = stats?.inflight ?? 0
return (
<div className="space-y-4">
@@ -302,6 +300,8 @@ export default function Logs() {
icon={Eraser}
onClick={() => setConfirmClear(true)}
loading={clear.pending}
disabled={!canWrite}
title={canWrite ? undefined : 'This API key is read-only'}
>
Clear
</Button>
@@ -316,11 +316,14 @@ export default function Logs() {
<span className="tabular font-mono text-fg">{formatCompact(qps)}</span> qps
</span>
<span className="text-fg-muted">
<span className="tabular font-mono text-fg">{formatPercent(blockedPct)}</span>{' '}
<span className="tabular font-mono text-fg">{formatFraction(blockedPct)}</span>{' '}
blocked
</span>
<span className="text-fg-muted">
<span className="tabular font-mono text-fg">{formatRate(hitRate)}</span> cache hits
<span className="tabular font-mono text-fg">{formatFraction(hitRate)}</span> cache hits
</span>
<span className="text-fg-muted">
<span className="tabular font-mono text-fg">{formatNumber(inflight)}</span> in flight
</span>
<span className="text-fg-subtle">sampled by the daemon every few seconds</span>
{streamError !== null && (
+42 -12
View File
@@ -29,6 +29,7 @@ import {
reloadSettings,
validateSettings,
} from '../lib/api'
import { useWhoami } from '../lib/session.ts'
import type { ConfigIssue } from '../lib/types'
import { useApi, useAsyncAction } from '../hooks/useApi'
import { formatNumber } from '../lib/format'
@@ -82,6 +83,7 @@ function IssueList({ issues: list, tone }: { issues: ConfigIssue[]; tone: 'dange
export default function Settings() {
const { toast } = useToast()
const { canWrite, readOnly } = useWhoami()
const notify = (title: string, description?: string, tone: 'ok' | 'fail' = 'fail'): void =>
toast({ title, description, tone: tone === 'ok' ? 'ok' : 'danger' })
@@ -89,7 +91,7 @@ export default function Settings() {
// The draft is keyed by the version it was started from: once the server
// reports a different version the edit is dropped, so a refetch can never
// stomp on an editor that is mid-change.
const [draft, setDraft] = useState<{ version: string; text: string } | null>(null)
const [draft, setDraft] = useState<{ version: number; text: string } | null>(null)
const gutter = useRef<HTMLDivElement | null>(null)
const [report, setReport] = useState<Report | null>(null)
const [confirmReload, setConfirmReload] = useState(false)
@@ -101,10 +103,15 @@ export default function Settings() {
const refreshLists = useAsyncAction(async () => refreshBlocklists())
const pristine = data?.config_yaml ?? ''
const version = data?.version ?? ''
// A config revision counter, so a number: the draft is keyed by it to make
// sure a refetch can never stomp on an edit in progress.
const version = data?.version ?? 0
const value = draft !== null && draft.version === version ? draft.text : pristine
const dirty = data !== null && value !== pristine
// Two independent reasons a write cannot land: the file is not writable, or
// this credential is read-only and the API would answer 403.
const writable = data?.writable !== false
const canSave = writable && canWrite
const lineCount = useMemo(() => value.split('\n').length, [value])
const gutterLines = useMemo(() => Array.from({ length: lineCount }, (_, i) => i + 1), [lineCount])
@@ -150,7 +157,7 @@ export default function Settings() {
'Configuration saved',
list.length > 0
? `${list.length} ${list.length === 1 ? 'warning' : 'warnings'}: ${list.join('; ')}`
: `version ${res.version || 'unknown'}`,
: `version ${formatNumber(res.version)}`,
'ok',
)
setDraft(null)
@@ -167,7 +174,7 @@ export default function Settings() {
}
setDraft(null)
setReport(null)
notify('Configuration reloaded', `running version ${res.version || 'unknown'}`, 'ok')
notify('Configuration reloaded', `running version ${formatNumber(res.version)}`, 'ok')
refetch()
}
@@ -190,7 +197,14 @@ export default function Settings() {
notify('Refresh failed', refreshLists.error ?? 'the server rejected the request')
return
}
notify('Refresh started', `${res.names?.length ?? 0} sources queued`, 'ok')
// `names` is what the daemon queued; an empty list means every source, so
// counting it would announce "0 sources queued".
const queued = res.names ?? []
notify(
'Refresh started',
queued.length > 0 ? `${queued.length}: ${queued.join(', ')}` : 'every source queued',
'ok',
)
}
if (error) return <PageError error={error} onRetry={refetch} />
@@ -224,7 +238,8 @@ export default function Settings() {
icon={RefreshCw}
onClick={() => setConfirmReload(true)}
loading={reload.pending}
disabled={data?.reload_available === false}
disabled={data?.reload_available === false || !canWrite}
title={canWrite ? undefined : 'This API key is read-only'}
>
Reload from disk
</Button>
@@ -239,7 +254,7 @@ export default function Settings() {
{data?.path || 'unknown path'}
</span>
</span>
<span>version {data?.version || 'unknown'}</span>
<span>version {formatNumber(data?.version ?? 0)}</span>
{data?.reload_available === false && (
<span>the daemon cannot reload this file at runtime</span>
)}
@@ -307,7 +322,8 @@ export default function Settings() {
icon={Save}
onClick={() => void onSave()}
loading={save.pending}
disabled={!writable || !dirty}
disabled={!canSave || !dirty}
title={canWrite ? undefined : 'This API key is read-only'}
>
Save
</Button>
@@ -315,13 +331,23 @@ export default function Settings() {
}
>
<CardBody>
{!writable && (
{(!writable || readOnly) && (
<p className="flex items-start gap-2 rounded-lg border border-warn/40 bg-warn-soft px-3 py-2 text-xs text-fg">
<Ban size={14} className="mt-0.5 shrink-0 text-warn" aria-hidden="true" />
<span>
This daemon reports the config file as read-only, so Save is disabled. Edit{' '}
<span className="font-mono">{data?.path || 'the file'}</span> on the host and
use Reload from disk.
{!writable ? (
<>
This daemon reports the config file as read-only, so Save is disabled. Edit{' '}
<span className="font-mono">{data?.path || 'the file'}</span> on the host
and use Reload from disk.
</>
) : (
<>
This API key is read-only, so the document below cannot be saved from here.
Edit <span className="font-mono">{data?.path || 'the file'}</span> on the
host and use Reload from disk.
</>
)}
</span>
</p>
)}
@@ -433,6 +459,8 @@ export default function Settings() {
variant="outline"
onClick={() => void onFlush()}
loading={flush.pending}
disabled={!canWrite}
title={canWrite ? undefined : 'This API key is read-only'}
>
Flush cache
</Button>
@@ -441,6 +469,8 @@ export default function Settings() {
variant="outline"
onClick={() => void onRefreshLists()}
loading={refreshLists.pending}
disabled={!canWrite}
title={canWrite ? undefined : 'This API key is read-only'}
>
Refresh blocklists
</Button>
+31 -20
View File
@@ -21,9 +21,10 @@ import {
} from 'lucide-react'
import { getUpstreams, putUpstreams } from '../lib/api'
import type { UpstreamBootstrap, UpstreamHealth, UpstreamServer } from '../lib/types'
import { useWhoami } from '../lib/session.ts'
import type { UpstreamBootstrap, UpstreamPolicy, UpstreamProto, UpstreamStat } from '../lib/types'
import { useApi, useAsyncAction } from '../hooks/useApi'
import { formatLatency, formatMs, formatNumber, formatRate } from '../lib/format'
import { formatFraction, formatLatency, formatMs, formatNumber } from '../lib/format'
import {
Badge,
Button,
@@ -69,7 +70,11 @@ const PROTOS = [
{ value: 'tls', label: 'TLS (DoT)' },
]
/** "30s", "1m30s", "1h" or a bare number -> seconds. */
/**
* "30s", "1m30s", "24h0m0s" or a bare number -> seconds. Every duration on the
* upstream payload is a string, so this is how they get back into the number
* input the editor keeps them in.
*/
function parseDuration(value: string): number {
const text = value.trim().toLowerCase()
if (text === '') return 30
@@ -115,7 +120,7 @@ type Draft = {
bootstraps: BootstrapDraft[]
}
function toServerDraft(s: UpstreamServer): ServerDraft {
function toServerDraft(s: UpstreamStat): ServerDraft {
return {
addr: s.addr ?? '',
proto: String(s.proto ?? 'udp'),
@@ -168,6 +173,7 @@ function splitList(value: string): string[] {
export default function Upstreams() {
const { toast } = useToast()
const { canWrite } = useWhoami()
const { data, error, loading, refetch } = useApi(() => getUpstreams(), [])
const [draft, setDraft] = useState<Draft | null>(null)
@@ -175,7 +181,7 @@ export default function Upstreams() {
const [editing, setEditing] = useState<ServerDraft | null>(null)
const [pendingRemove, setPendingRemove] = useState<number | null>(null)
const servers: UpstreamServer[] = useMemo(() => data?.servers ?? [], [data])
const servers: UpstreamStat[] = useMemo(() => data?.servers ?? [], [data])
const bootstraps: UpstreamBootstrap[] = useMemo(() => data?.bootstraps ?? [], [data])
const working: Draft = useMemo(() => {
@@ -184,7 +190,7 @@ export default function Upstreams() {
policy: String(data?.policy ?? 'parallel'),
max_attempts: String(data?.max_attempts ?? 2),
breaker_threshold: String(data?.breaker_threshold ?? 5),
healthcheck_s: String(parseDuration(String(data?.healthcheck_interval ?? '30s'))),
healthcheck_s: String(parseDuration(data?.healthcheck_interval ?? '30s')),
servers: servers.map(toServerDraft),
bootstraps: bootstraps.map((b) => ({
name: b.name ?? '',
@@ -196,29 +202,26 @@ export default function Upstreams() {
const dirty = draft !== null
const slowest = working.servers.reduce((max, s) => Math.max(max, s.latency_ms || 0), 0)
// The daemon reports the breaker cooldown as a duration string and keeps the
// value already configured unless a write changes it, so it is shown, not
// edited here.
const cooldown = data?.breaker_cooldown ?? ''
const save = useAsyncAction(async () => {
const payload = {
policy: working.policy,
policy: working.policy as UpstreamPolicy,
max_attempts: toInt(working.max_attempts, 2),
breaker_threshold: toInt(working.breaker_threshold, 5),
healthcheck_interval_s: toInt(working.healthcheck_s, 30),
// Only the editable fields go up: the server owns the health and the
// counters, and sending them back is noise it has to ignore.
servers: working.servers.map((s) => ({
addr: s.addr.trim(),
proto: s.proto,
proto: s.proto as UpstreamProto,
server_name: s.server_name.trim(),
insecure_skip_verify: s.insecure_skip_verify,
weight: s.weight,
comment: s.comment,
health: s.health as UpstreamHealth,
latency_ms: s.latency_ms,
fail_rate: s.fail_rate,
breaker_open: s.breaker_open,
// Runtime counters are not part of a write: the server owns them and
// ignores these fields on PUT /upstreams.
queries: 0,
avg_ms: 0,
p95_ms: 0,
})),
bootstraps: working.bootstraps.map((b) => ({
name: b.name.trim(),
@@ -314,7 +317,9 @@ export default function Upstreams() {
</span>
</span>
),
fail: <span className="font-mono text-xs">{s.fail_rate > 0 ? formatRate(s.fail_rate) : '—'}</span>,
fail: (
<span className="font-mono text-xs">{s.fail_rate > 0 ? formatFraction(s.fail_rate) : '—'}</span>
),
weight: <span className="font-mono text-xs">{s.weight}</span>,
comment: <span className="block max-w-[160px] truncate text-xs text-slate-500">{s.comment}</span>,
order: (
@@ -342,7 +347,13 @@ export default function Upstreams() {
>
Discard
</Button>
<Button icon={Save} onClick={() => void commit()} loading={save.pending} disabled={!dirty}>
<Button
icon={Save}
onClick={() => void commit()}
loading={save.pending}
disabled={!dirty || !canWrite}
title={!canWrite ? 'This API key is read-only' : undefined}
>
Save
</Button>
</div>
@@ -482,7 +493,7 @@ export default function Upstreams() {
<p className="text-xs text-slate-500 dark:text-slate-400">
{working.servers.length} server{working.servers.length === 1 ? '' : 's'} ·{' '}
{formatNumber(working.servers.reduce((sum, s) => sum + s.weight, 0))} total weight ·
slowest {formatMs(slowest)}
slowest {formatMs(slowest)} · breaker cooldown {cooldown === '' ? 'the config default' : cooldown}
{dirty ? ' · unsaved changes' : ''}
</p>