22 Commits
Author SHA1 Message Date
mokhtar c9701fae85 build: bump version to 0.0.13
Gates / frontend (push) Successful in 1m35s
Gates / test (push) Successful in 2m23s
Gates / test-aarch64 (push) Successful in 8m13s
Gates / package (push) Successful in 4m15s
Gates / container (push) Successful in 10s
CI / gates (push) Successful in 23m19s
Release / guard (push) Successful in 34s
Gates / frontend (push) Successful in 1m39s
Gates / test (push) Successful in 2m19s
Gates / test-aarch64 (push) Successful in 7m25s
Gates / package (push) Successful in 48s
Release / publish (push) Successful in 6m36s
Gates / container (push) Successful in 17s
Release / gates (push) Successful in 10m52s
2026-08-27 21:46:08 +02:00
mokhtar a3aa7febb4 upstream: one absolute per-query budget across queueing and failover
Gates / frontend (push) Successful in 1m46s
Gates / test (push) Successful in 2m32s
Gates / package (push) Successful in 4m20s
Gates / test-aarch64 (push) Successful in 8m15s
Gates / container (push) Successful in 15s
CI / gates (push) Successful in 30m33s
waiting for a slot now spends the query budget; truncated attempts that
expire fault the budget, not the upstream, and are never attributed.
admission sweeps in priority order before blocking. forward zones spend
read_timeout_ms once across udp, truncation and tcp. adds
nxdns_upstream_budget_exhausted_total and a 64-upstream validation limit.
2026-08-27 21:10:43 +02:00
mokhtar d2e12ae0e2 build: bump version to 0.0.12
Gates / test (push) Successful in 2m20s
Gates / frontend (push) Successful in 1m33s
Gates / test-aarch64 (push) Successful in 8m13s
Gates / package (push) Successful in 4m33s
Gates / container (push) Successful in 10s
CI / gates (push) Successful in 27m59s
Release / guard (push) Successful in 1m45s
Gates / frontend (push) Successful in 1m59s
Gates / test (push) Successful in 2m24s
Gates / test-aarch64 (push) Successful in 7m33s
Gates / package (push) Successful in 45s
Gates / container (push) Successful in 14s
Release / gates (push) Successful in 25m53s
Release / publish (push) Successful in 8m32s
2026-08-27 17:49:06 +02:00
mokhtar 6a0630c288 overview: one endpoint, live projections and a response cache (m36)
Gates / frontend (push) Successful in 2m6s
Gates / test (push) Successful in 2m57s
Gates / test-aarch64 (push) Successful in 8m31s
Gates / package (push) Successful in 4m19s
Gates / container (push) Failing after 2s
CI / gates (push) Failing after 26m21s
2026-08-27 17:48:20 +02:00
mokhtar a261dc2aa3 build: bump version to 0.0.11
Gates / test (push) Successful in 2m12s
Gates / test-aarch64 (push) Successful in 7m1s
Gates / package (push) Successful in 42s
Release / gates (push) Successful in 10m8s
Gates / container (push) Successful in 10s
Release / publish (push) Successful in 10m22s
Gates / test-aarch64 (push) Successful in 9m19s
Gates / package (push) Successful in 10m49s
Gates / container (push) Successful in 15s
CI / gates (push) Successful in 25m8s
Gates / frontend (push) Successful in 1m42s
Gates / frontend (push) Successful in 3m55s
Gates / test (push) Successful in 4m41s
Release / guard (push) Successful in 1m48s
2026-08-24 18:41:46 +02:00
mokhtar 90b85ef954 changelog: 0.0.11
Gates / test (push) Successful in 2m6s
Gates / test-aarch64 (push) Successful in 7m31s
Gates / frontend (push) Successful in 1m36s
Gates / package (push) Failing after 16m49s
Gates / container (push) Skipped
CI / gates (push) Failing after 35m55s
2026-08-24 18:40:29 +02:00
mokhtar ad26aca198 admin: draw the overview charts with visx
the hand-written scale, tick, stacking and arc math is replaced by visx 4.0.0
primitives; rendering, colours and themes stay the app's own. all four charts
share one hover treatment: the client chart gains the tooltip and dimming the
query timeline had, the donuts gain both, an open tooltip follows a data
refresh instead of going stale, and it retires when the window rolls. the
timeline's third series is named allowed instead of other, and the client
chart's other aggregate disappears from a window where it counted nothing.
licenses gain the isc text for the bundled d3 modules.
2026-08-24 18:40:17 +02:00
mokhtar 08d756cc87 build: bump version to 0.0.10
Gates / frontend (push) Successful in 2m1s
Gates / test (push) Successful in 3m6s
Gates / test-aarch64 (push) Successful in 9m28s
Gates / package (push) Successful in 9m12s
Gates / container (push) Successful in 14s
CI / gates (push) Successful in 22m4s
Release / guard (push) Successful in 1m32s
Gates / frontend (push) Successful in 1m28s
Gates / test (push) Successful in 1m53s
Gates / package (push) Successful in 23s
Gates / container (push) Successful in 17s
Release / gates (push) Successful in 9m33s
Gates / test-aarch64 (push) Successful in 6m58s
Release / publish (push) Successful in 10m46s
2026-08-24 00:05:33 +02:00
mokhtar 44ecc2c4ae changelog: 0.0.10
Gates / frontend (push) Successful in 1m31s
Gates / test (push) Successful in 1m53s
Gates / test-aarch64 (push) Successful in 7m2s
Gates / package (push) Successful in 5m44s
Gates / container (push) Successful in 9s
CI / gates (push) Successful in 48m46s
2026-08-24 00:05:21 +02:00
mokhtar ce143d1d87 db-mode config changes apply live in-process
Gates / frontend (push) Successful in 1m43s
Gates / test (push) Successful in 2m14s
Gates / test-aarch64 (push) Successful in 8m3s
Gates / package (push) Successful in 5m42s
Gates / container (push) Successful in 54s
CI / gates (push) Successful in 50m24s
settings and upstream writes now follow a prepare, commit, publish, retire
contract: candidates are built and validated before the database transaction,
published as infallible pointer swaps, and old generations retire after their
readers drain. per-query policy values snapshot once per query; upstream pool,
cache, rate limiter, sessions, api limiter, log sink, blocklist scheduler and
the query-log queue each gained one named live operation. restart_required
shrinks from every scalar key to the bind keys and web.enabled; the admin ui
drops its restart notices for everything else. file mode is unchanged.
2026-08-24 00:04:28 +02:00
mokhtar f7f4c8be09 admin: only the content region scrolls on wide screens
the shell grid grew past the viewport and scrolled the document,
carrying the sidebar with it. the shell is now viewport-height at the
wide breakpoint with main as the sole scroll container; the nav list
scrolls inside the pinned rail; router scroll restoration targets the
inner scroller so navigation resets it and back/forward restores it.
2026-08-23 15:17:51 +02:00
mokhtar fe71efe335 cut: schema gate — refuse to release an undisclosed querylog schema change
the gate recomputes the previous release tag's ddl fingerprint from the
remote peeled object and compares it against the tree's; a change must
be disclosed by 'resets your query history' in the version's changelog
section. the 0.0.9 reset shipped with an announcement claiming no
schema change; this makes the impact mechanical instead of remembered.
2026-08-23 15:07:27 +02:00
mokhtar a8fd9fee48 ci: drop the one-insn-per-tb workaround, the qemu panic is an 11.1.0-only regression
Gates / frontend (push) Successful in 1m33s
Gates / test-aarch64 (push) Successful in 7m18s
Gates / container (push) Successful in 18s
CI / gates (push) Successful in 13m41s
Gates / test (push) Successful in 1m47s
Gates / package (push) Successful in 4m12s
Gates / package (push) Successful in 38s
Release / guard (push) Successful in 20s
Gates / frontend (push) Successful in 1m27s
Gates / test (push) Successful in 1m43s
Gates / test-aarch64 (push) Successful in 7m1s
Gates / container (push) Successful in 9s
Release / gates (push) Successful in 9m33s
Release / publish (push) Successful in 4m43s
the bisect proved the runner image's qemu 8.2 was never affected; the
hangs this masked were the logger deadlock fixed in f1a85d3. the 10x
slowdown it cost also broke the full-batch flush timing test in run 592.
2026-08-23 13:55:22 +02:00
mokhtar f1a85d3dab logger tests: join every writer future before its database closes, fix the gate-open race
Gates / test (push) Successful in 1m50s
Gates / package (push) Successful in 4m6s
Gates / frontend (push) Successful in 1m49s
Gates / test-aarch64 (push) Failing after 1h13m21s
Gates / container (push) Successful in 10s
CI / gates (push) Failing after 1h23m35s
2026-08-23 12:26:09 +02:00
mokhtar 72dbcbe24f ci: run the aarch64 suite with one qemu insn per tb, tcg optimization falsely trips the ubsan pointer check 2026-08-23 12:26:05 +02:00
mokhtar c5875af8c8 admin: live ring capacity is injectable, eviction test no longer timing-bound
Gates / test-aarch64 (push) Failing after 3h1m47s
Gates / package (push) Successful in 4m17s
Gates / container (push) Successful in 15s
CI / gates (push) Failing after 4h45m14s
Gates / frontend (push) Successful in 1m21s
Gates / test (push) Successful in 1m42s
2026-08-23 09:04:18 +02:00
mokhtar 409384ee9e build: bump version to 0.0.9
Gates / container (push) Successful in 15s
CI / gates (push) Failing after 6h11m8s
Gates / frontend (push) Successful in 1m26s
Gates / test (push) Successful in 1m45s
Gates / package (push) Successful in 34s
Gates / test-aarch64 (push) Failing after 3h6m37s
2026-08-22 23:32:47 +02:00
mokhtar 9eb78f6171 changelog: 0.0.9 releases today
Gates / frontend (push) Successful in 1m29s
Gates / test (push) Successful in 1m53s
Gates / test-aarch64 (push) Successful in 7m38s
Gates / package (push) Successful in 3m49s
Gates / container (push) Successful in 10s
CI / gates (push) Successful in 6h29m21s
2026-08-22 23:32:36 +02:00
mokhtar cc23c97218 milestone 33: contract closure — samples, file-authority enumeration, dead code, bundle ceiling
Gates / frontend (push) Successful in 1m34s
Gates / test (push) Successful in 2m3s
Gates / test-aarch64 (push) Failing after 3h13m33s
Gates / package (push) Successful in 5m20s
Gates / container (push) Successful in 15s
CI / gates (push) Failing after 6h30m45s
2026-08-22 23:31:37 +02:00
mokhtar 5da4652e89 querylog: return to the default checkpoint cadence 2026-08-22 23:10:17 +02:00
mokhtar 7e0df5fd94 milestone 32: task-shaped configuration, file mode as a rendering, config status api
Gates / frontend (push) Successful in 1m22s
Gates / test (push) Successful in 1m54s
Gates / test-aarch64 (push) Successful in 7m57s
Gates / package (push) Successful in 5m29s
Gates / container (push) Successful in 10s
CI / gates (push) Successful in 32m51s
2026-08-22 22:42:50 +02:00
mokhtar 025edbb093 milestone 31: concurrent upstream exchanges, dot session reuse, queue metrics
Gates / frontend (push) Successful in 1m26s
Gates / test (push) Successful in 1m55s
Gates / test-aarch64 (push) Failing after 3h1m8s
Gates / package (push) Successful in 3m55s
Gates / container (push) Successful in 15s
CI / gates (push) Failing after 3h21m29s
2026-08-22 19:54:02 +02:00
216 changed files with 24496 additions and 8158 deletions
+5
View File
@@ -101,6 +101,11 @@ jobs:
sudo apt-get update -qq
sudo apt-get install -qq -y --no-install-recommends qemu-user
# qemu 11.1.0 has a TCG regression: its translation-block optimization
# takes the panic branch of Zig's UBSan pointer-overflow check on a
# valid in-bounds pointer (11.0.3 and earlier are clean; bisected via
# the Arch archive). This image's qemu 8.2 is not affected — do not
# upgrade the emulator past 11.0.x until qemu fixes it.
- name: Run test suite under qemu (plain suite, no -Dintegration)
run: zig build test-aarch64 -fqemu
+17
View File
@@ -32,6 +32,23 @@ Any *other* failure text is real. Trust the summary line: `zig build test` exiti
One trap: running a cached test binary by hand with `--listen=-` aborts with `internal test runner failure: EndOfStream`. That is not a teardown bug; the IPC runner is talking to a closed stdin because no build runner is on the other end. Run the binary with no arguments to get the plain stdio report.
## Debug-mode miscompile: a `bool` live across an atomic read-modify-write
In Debug the x86_64 self-hosted backend is the default, and zig 0.16.0's atomic read-modify-write lowering there does not invalidate a `bool` the register allocator is still tracking in EFLAGS. The `bool` silently becomes the flags the `lock xadd` left behind. Release modes go through LLVM and are unaffected, so this can only ever break `zig build test`, never a shipped binary.
The shape to avoid is a comparison whose result stays live across `fetchAdd`/`fetchSub`/`@atomicRmw` and is then branched on:
```zig
const idle = old.refs == 0; // sete 0x50(%rsp) -- correct
_ = self.published.fetchAdd(1, .monotonic); // lock xadd %rdi,(%rsi)
// sete 0x51(%rsp) -- bogus, reads EFLAGS from the xadd
return if (idle) old else null; // branches on 0x51, not 0x50
```
That function returns `null` for every input. `fetchAdd` is the only trigger: a plain `+= 1`, an atomic `load`, and an atomic `store` in the same slot all compile correctly, and inserting any call (including `std.debug.print`) between the comparison and the branch forces a spill that hides it. Build the same file with `-fllvm` or `-OReleaseSafe` to confirm a suspected instance.
`Owner.published` in `src/upstream/owner.zig` is a plain `u64` under the owner's mutex for this reason. Do not "modernize" it to `std.atomic.Value(u64)`.
## Regenerating the contract samples
`admin/src/lib/contractSamples.gen.ts` is a committed golden of canonicalized API responses, byte-compared against the live server by a `-Dintegration` test and type-checked by `tsc`. After a deliberate API contract change, regenerate it with:
+48 -1
View File
@@ -4,7 +4,49 @@ All notable changes to nxdns are recorded here. The format follows [Keep a Chang
Sections are written by hand. Nothing here is generated from commit messages: the point of the file is to say what changed for an operator, which a commit subject rarely does.
## [Unreleased]
## [0.0.13] - 2026-08-27
The upstream query budget becomes one honest deadline. A busy network no longer blames a healthy standby for running out of time, and a query burst no longer queues invisibly until everything answers SERVFAIL at once.
### Fixed
- **The per-query upstream budget is now one absolute deadline, spent by everything that blocks.** Waiting for a free slot on a saturated upstream now spends the query's `upstream.total_timeout_ms` budget just like the exchange itself, instead of being invisible to it — under a burst, queries used to wait out their whole budget in the queue and then start attempts they could never finish. An attempt near the end of the budget runs truncated, and when a truncated attempt runs out of time that is evidence about the budget, not the upstream: it no longer counts against that upstream's health or success rate, and the query log no longer names an upstream that was given no fair chance. A field incident produced 279 rows blaming a standby whose health counters read zero for zero; those rows now attribute nothing.
- **A query no longer blocks behind a saturated upstream while another has capacity.** Admission sweeps the upstreams in priority order and takes the first free slot; priority now means the order among upstreams that can be admitted right now, and a query blocks only when nothing has capacity — on the highest-priority eligible upstream, bounded by the remaining budget.
- **Conditional forward zones spend `upstream.read_timeout_ms` once per query.** A UDP attempt, a truncated answer and the TCP retry now share the one budget instead of taking a fresh one each, so a slow zone resolver can no longer stretch a single query to several times the configured timeout.
### Added
- **`nxdns_upstream_budget_exhausted_total`.** A pool-wide counter of queries whose budget ran out — in the queue or mid-attempt — before any upstream answered. It carries no per-upstream label on purpose: running out of budget is a fact about the pool.
- **A configuration with more than 64 enabled upstreams is rejected at validation** with a clear message, instead of tripping an internal limit at startup.
## [0.0.12] - 2026-08-27
Overview stops re-reading the whole query log. One endpoint, one snapshot, pre-aggregated buckets — a 30-day view now costs the same on a month of history as on a day of it. Read the upgrade note first: it resets your query history.
### Changed
- **Upgrading resets your query history.** The query-log schema gains the aggregate tables described below, and `querylog.db` is never migrated: the first start after the upgrade sets the old file aside (kept on disk next to the new one, named with the reason) and begins a fresh log. Settings, groups, blocklists and every other configuration are untouched.
- **The Overview is served by one endpoint, `GET /api/overview`.** It replaces `GET /api/stats`, `/api/stats/timeseries`, `/api/stats/types`, `/api/stats/routes` and `/api/stats/clients`, which are gone. The five panels now come from a single database snapshot, so they can no longer disagree with each other, and the page shows one loading and one error state instead of five.
- **Query statistics are pre-aggregated as they are written.** The query log now maintains 30-minute aggregate tables in the same transaction that stores the rows, and the 24-hour, 7-day and 30-day views read those instead of scanning every logged query. The cost of opening the Overview no longer grows with the size of the log: measured at three million rows, the 30-day view went from roughly eight-tenths of a second of scanning to under fifty milliseconds, at the price of about ten percent on each background write batch and ~1.5 MB of disk. The server also keeps the most recent response per period in memory and serves repeat polls from it while nothing has changed — until new queries land, retention prunes, or the period's time window rolls forward — so on a quiet network most of the steady 30-second refreshes do no database work at all.
The Overview charts move to visx and grow up: one hover treatment across all four, honest labels, and maintained d3 math under the app's own rendering.
### Changed
- **The Overview charts are drawn with visx.** The hand-written chart layout code is replaced by visx 4.0.0 primitives — maintained d3 math for the scales, ticks, stacking and arcs — while the rendering, colours and themes stay the app's own. The charts read as before, with four behaviour improvements: all four charts now share the same hover treatment (the per-client chart and both donuts gain the tooltip and dimming the query timeline already had, so pointing at a ring segment names it, its count and its share), an open tooltip follows a data refresh instead of showing stale counts, and it retires cleanly when the time window rolls. The admin bundle grows by about 68 KB and stays under its size budget.
- **The query timeline's third series is called "Allowed".** What the chart called "Other" is every query that was neither blocked nor served from cache — answered upstream, from a local record or a forward zone — so it is now named for what it is rather than for the subtraction that produces it. It stays on the chart even in a window where nothing was allowed, alongside Blocked and Cached: all three name a kind of answer a query can get, and a period where every query was blocked or cached is worth seeing.
- **The client chart drops "Other" in a window where it counted nothing.** That series aggregates the clients outside the top eight, so when it counts nothing there is nothing being aggregated, and a legend entry, a tooltip row and a table column that exist only to say "zero" are noise. The named clients stay even at zero, because a client that went quiet is a fact about the window.
## [0.0.10] - 2026-08-24
Configuration goes live: when the database owns the configuration, saving a setting reconfigures the running process instead of asking for a restart. The restart-required set shrinks to the listen sockets and the admin interface switch.
### Changed
- **Almost every settings change now applies while the server runs.** When the database owns the configuration, saving a setting takes effect immediately — the blocking response, upstream timeouts, cache size, rate limits, session lifetime, log level and destination, blocklist update schedule, privacy flags, disk thresholds and the query-log buffer all reconfigure the running process, exactly as Pi-hole and AdGuard Home do. Nothing is written to the database unless the running server already accepted it, so the API can never report a value the process refused. The restart-required set shrinks from every scalar key to the twelve that genuinely need one: listen addresses and ports, and turning the admin interface itself on or off. The admin pages drop their restart notices for everything else, and an upstream edit — the loudest offender — now applies to the next query. A configuration file still works the way it always has: edit the file, restart the process.
- **The release cut refuses to ship an undisclosed query-log schema change.** `zig build cut` now compares the `querylog.db` schema fingerprint of the previous release tag against this tree's, and when they differ it requires the changelog section for the version being cut to state that the upgrade discards the stored query history. 0.0.9 changed the schema and its announcement did not mention it; the file is never migrated, so that upgrade silently threw every logged query away.
## [0.0.9] - 2026-08-22
Query provenance: every logged query becomes exactly explainable — what the policy decided, what matched, where the answer came from and what the client saw. The handler records all of it as the reply goes out, `query_log` stores it, and a detail page reads one query back in the order the pipeline decided it. Read the upgrade note below first: it resets your query history.
@@ -15,6 +57,7 @@ Query provenance: every logged query becomes exactly explainable — what the po
- **Diagnostics can be scoped to an absolute window.** `/diagnostics?since=…&until=…` now validates and applies both bounds to the active and resolved lists, and the page states the window it is showing with a way to clear it. A query's detail page links here with the five minutes either side of that query, which is where the underlying failure text for a SERVFAIL lives.
- **The query log and the stats endpoints say how far back the history goes.** `GET /api/queries` and all five `/api/stats*` endpoints each carry a `coverage` object: `available_since`, the first second the file can answer for, and `complete`, whether the window you asked for begins inside it. A period that starts before the query log does now says so instead of charting the missing part as zero — which is what a recreate, a retention pass or a fresh install would otherwise look like.
- **Three new period breakdowns: `GET /api/stats/types`, `/api/stats/routes` and `/api/stats/clients`.** They take the same `period` parameter as `/api/stats` and report over the same UTC-aligned window, so every panel of one page describes the same span. `types` counts queries per DNS type, with the queries that recorded no type kept as their own row instead of dropped — the numeric type only, since naming types is the admin's job and a second table in the server would drift out of agreement with it. `routes` counts queries by how they were answered, grouping upstream rows by the answering resolver and forward-zone rows by the zone, with blocked, cache, local and rejected answers carrying no source. `clients` returns one bucketed series per client, aligned exactly like `/api/stats/timeseries` so the two charts share an x-axis: the eight busiest clients in the window are named and everything else sums into an `other` series, which is always present and always the same length as the named ones.
- **`/metrics` says whether an upstream is queueing.** Five new per-upstream series, labelled by index and redacted url like the existing ones: `nxdns_upstream_in_flight` and `nxdns_upstream_slots` are the exchanges in flight against an upstream and the ceiling they cannot cross, `nxdns_upstream_queued_total` and `nxdns_upstream_queued_seconds_total` count the exchanges that had to wait for a slot and the time they spent waiting — including the ones that were cancelled while waiting, which is exactly the query that ends in SERVFAIL — and `nxdns_upstream_reuse_recoveries_total` counts the stale DoT connections that were redialled, so connection churn is a number instead of log noise. The two queue counters are approximate: they are sampled when a query is admitted, not measured as a queue length. `/api/health` is unchanged.
- **Each of those responses is read atomically.** Every window-bounded read — the five stats endpoints and `GET /api/queries` — now takes its rows and its coverage watermark inside one SQLite read transaction. A retention pass that runs mid-response can no longer hand back rows from before the prune tagged with an `available_since` from after it, and the clients breakdown ranks and buckets from one database state rather than two. The transaction is a deferred read, so it never blocks the query logger or retention.
### Removed
@@ -25,6 +68,7 @@ Query provenance: every logged query becomes exactly explainable — what the po
### Changed
- **Configuration is three task-shaped pages, and a file-managed server says so once.** Groups, Blocklists, Rules, Local DNS, Upstreams and Settings — six navigation entries and six routes — become `/configuration/protection`, `/configuration/resolution` and `/configuration/system` under one labelled "Configuration" group. Protection is group-centred: pick a group and read its safe search, its blocklist sources, its rules and how many clients it filters, with the shared blocklist catalogue and "Update now" on a second tab. Resolution holds the upstream pool, local records and forward zones; System holds the settings sections, the restart-required annotations and "Reload certificates". The tab and the selected group are URL state, so the view you are reading is a link, and the six old paths stop resolving — no redirect, no alias. When a configuration file owns the server, these pages are no longer forms with everything greyed out: they render as definition lists and tables with the exact ZON key beside each value, a note saying which file to edit, and no input, checkbox, Add, Edit, Delete or Save anywhere — while runtime actions that do not touch the file (update blocklists now, reload certificates, pause and resume, deleting an observed client) stay ordinary working buttons. A new `GET /api/config/status` is the one place that answers who owns the configuration and whether a restart is pending; the admin never guesses from a 403, and until the endpoint answers nothing is editable. `restart_pending` is now the server's own state rather than a banner one browser tab remembered: it is set by the upstream and settings changes that need a restart, it survives a page reload, another tab sees it within a minute, and only restarting the process clears it. `GET /api/settings` loses its `authority` object, which said the same thing twice. Clients keeps its own top-level page, because naming an unknown device is operations, not configuration: the list is address, name, group and first/last seen, `?group=` filters it to one group, and each row opens `/clients/{id}` — the client's identity and where its name came from, the group whose policy it follows with a link to that group, and a link into Activity for its last 24 hours.
- **The Dashboard is now Overview, and it takes Pi-hole's layout.** `/` redirects to `/overview`, and the page answers one question — what the resolver did over a period you choose — instead of laying out six widgets. The 1h/24h/7d/30d period is URL state (`/overview?period=1h`), so the view you are reading is a link you can send. Top to bottom: four neutral stat tiles — queries, blocked with its share, distinct clients, average response time — each linking into the rows behind its number; the query-volume timeline split blocked, cached and other; a new per-client chart on the same axis, the busiest clients named — by their registered or reverse-DNS name where they have one, exactly as the query tables name them — and the rest summed as "other"; and two donuts, query types and how queries were answered, with each upstream and forward zone named separately. Colours follow the identity of a client, a type or a route rather than its rank, so one client overtaking another between refreshes does not repaint the page. Each donut is drawn as decoration with a visible legend beside it and a table a screen reader reads instead of the graphic. All five panels describe one window — matched on the period, both bounds and the coverage watermark together — so a refresh that straddles a bucket boundary, or a retention pass mid-page, can never put a headline count above a chart of a different span. Panels load, fail and retry on their own: a failing donut leaves the charts standing. A period with nothing in it says "No queries in this period." rather than drawing an empty frame.
- **The five health conditions moved to Diagnostics, and the nav item says when to look.** Protection, Upstreams, Query history, Diagnostics and Storage are now a compact strip at the top of `/diagnostics`, above the episodes that explain them, instead of a status list on the landing page. Each states its state in words and an icon as well as colour. A healthy condition is quiet; a degraded one is highlighted and links to what can fix it: protection to Blocklists, no reachable upstream to Upstreams, and a losing or failed query log or a low or critical disk to this same page filtered to the component that failed, with any time window cleared so the filter cannot hide the episodes it points at. Dropped rows are reported with the time of the newest drop, so a loss stays visible after the box recovers. When a health poll fails, the conditions on screen are labelled as the last reading that arrived rather than passing for the current state, and a Retry sits beside them. The Diagnostics navigation item carries a badge with the number of open episodes; it shows a plain "!" when the rollup is degraded with nothing open, and also when the last health poll failed, because an unknown must not look like good news. The badge is absent only when health answered and there was nothing to report.
- **Pause moved to the sidebar, and the header indicator is gone.** The header carries nothing but the menu button and Log out. Pause and Resume sit at the foot of the navigation sidebar, above the version label, in both the desktop rail and the phone drawer — one global runtime action in the one place that belongs to the resolver rather than to whichever page you are on. The control still appears beside the detail of a query that was blocked, which is the other place the action answers what you are looking at. The control says what it is doing as well as what it offers: Pause while filtering is on, and while it is off, "Paused until 14:05" — or plain "Paused" when the pause has no end — above the Resume button, on every page. "Resume" on its own would name an action without naming the state it ends, and with the header indicator gone no other page could tell you filtering was off. Both controls read the same `protection` condition, so they cannot disagree, and a pause or resume is reflected immediately rather than at the next poll. Nothing offers to pause while protection is unavailable, since pausing a resolver with no filter snapshot changes nothing.
@@ -35,9 +79,12 @@ Query provenance: every logged query becomes exactly explainable — what the po
- **Upgrading resets your query history.** The `query_log` table gains the provenance columns below, and `querylog.db` is never migrated (it holds expendable log rows, so a schema change replaces the file instead of upgrading it). On the first start after the upgrade the old file is set aside as `querylog.db.schema-changed-<unix seconds>` and a fresh one is created. Nothing else is touched: `config.db` keeps your configuration and your diagnostics history. The recreate files a resolved `query_log.recreated` diagnostics entry naming the file that was kept and the timestamp the new history begins at, and a new `querylog_meta` table records that coverage start, so the dashboard can say "history is available from ..." instead of charting an empty range as zero. The set-aside file is a working SQLite database and can be deleted once you have decided you do not want it.
- **`logging.query_log_buffer_max` now accepts 1 to 37449, down from 1 to 1000000.** The queued entry carries every new provenance field by value and is about four times as wide as before — 1792 bytes against 432 — so the meaningful bound is bytes rather than entries. The ceiling is computed at compile time from the width of the entry so that the queue's worst case stays within 64 MiB, and it moves whenever that width does. The default of 10000 is unchanged and costs about 17 MiB. A configuration above the new ceiling is rejected at startup with the ceiling in the message.
- **Group and blocklist source names are now capped at 64 bytes.** Both are copied into every query-log row that mentions them, so an unbounded name was an unbounded cost per row. A longer name is rejected as `GroupNameTooLong` or `SourceNameTooLong`.
- **The query log returns to SQLite's default checkpoint cadence.** 0.0.8 stretched `wal_autocheckpoint` on every read-write `querylog.db` connection from the 1000-page default to 8192 pages, on the expectation that it would cut about 130 MiB a day of checkpoint writeback on the deployed Pi. Field measurement on that Pi showed no measurable effect on daily disk writes, so all it bought was a roughly five-hour power-loss durability window in place of the default's ~40 minutes. No pragma is issued any more: the cadence is SQLite's 1000 pages, about 4 MiB, and the ~40-minute boundary is back.
- **The admin bundle now has a ceiling the build enforces.** `npm run build` fails if `admin/dist/assets` totals more than 800,000 bytes — it is 708,352 today — and prints the largest chunks when it does. The bundle is embedded in the server binary and served to your LAN, so an accidental dependency arriving in it is a regression every other check would have passed. Alongside it the redesign's closure sweep removed the last code the new pages left behind: an unused API client call and type, and the `features/queries` directory renamed to `features/provenance` now that no page lives there. The investigation links that carry a time window out of a query detail are pinned by their own tests, including one that a link's emitted bounds survive the Activity page's validation unchanged. Nothing an operator uses changed.
### Fixed
- **A burst of concurrent queries no longer resolves one at a time, and no longer ends in SERVFAIL.** The pool held an upstream for the whole of an exchange, so every query against one upstream waited for the one before it, and the DoT client dialled a fresh TCP connection and ran a full TLS handshake for each query on top of that. Thirty concurrent names against one DoT upstream resolved as a staircase at about 92 ms per query on a Pi, and the queries at the back of the queue burned the five-second total budget waiting and were answered SERVFAIL — with nothing on any surface saying a queue existed. Two changes fix it: each upstream now runs up to eight exchanges at once, each on its own leaf client behind a semaphore, so a query waits for a free slot rather than for the whole upstream; and a DoT client keeps its TLS session open across exchanges instead of handshaking per query. A reused connection that the resolver closed while it was idle is detected at use — never by a keepalive timer — and redialled once, and that redial is invisible to health and to Diagnostics because an idle close is normal, not a fault. The slot count is compiled, not configured: there is no new knob.
- **A UDP reply that has to be truncated keeps the answer's RCODE.** When an answer does not fit the client's UDP buffer, nxdns replaces it with an empty reply carrying the TC bit, which tells the client to retry over TCP. That replacement was always built as NOERROR, whatever the answer said — so an oversized NXDOMAIN reached the client as a success, and an EDNS extended RCODE above 15 lost the eight upper bits it needs an OPT record to carry. The truncated reply now carries the full twelve-bit code the answer had, split across the header and the reply's OPT record where the code needs it, and the query-log row records the code the client actually saw. The retry over TCP always returned the right RCODE; this was the UDP answer that preceded it.
## [0.0.8] - 2026-08-21
+9 -5
View File
@@ -238,7 +238,7 @@ src/
web/
server.zig router.zig auth.zig sse.zig static.zig metrics.zig openapi.zig
handlers/
auth.zig stats.zig queries.zig clients.zig groups.zig blocklists.zig
auth.zig overview.zig queries.zig clients.zig groups.zig blocklists.zig
rules.zig local.zig lookup.zig pause.zig settings.zig
upstream_health.zig certs.zig health.zig version.zig
@@ -324,7 +324,9 @@ Per-group boolean. Rewrites known engine domains to their safe-search CNAME targ
## 9. Upstream Resolution
- Schemes: `https://…` → DoH, `tls://host:853` → DoT.
- Ordered by priority; sequential attempt; per-upstream failure counters; exponential backoff with jitter; success resets.
- Ordered by priority; one query tries upstreams sequentially; per-upstream failure counters; exponential backoff with jitter; success resets.
- Concurrency is per upstream, not per pool: each entry owns `slots_per_entry = 8` leaf clients behind a semaphore, so at most 8 exchanges are in flight against one upstream at a time and the rest wait for a slot rather than for the whole entry. The slot count is compiled, not configured. A task that finds every slot taken counts itself in `queued_total`/`queued_seconds_total` on both exits — acquisition and cancellation — so a query that burned its total budget waiting is visible on `/metrics` (`nxdns_upstream_queued_total`, `nxdns_upstream_in_flight`, `nxdns_upstream_slots`) instead of being an unexplained SERVFAIL. The counters are admission samples, not an exact queue length.
- DoT keeps its connection: a `DotClient` holds one TLS session open across exchanges rather than dialing and handshaking per query. Staleness is detected at use, never by a keepalive timer — a reused session that fails before the first response byte with a connection-lifecycle error is redialed once and retried, and that recovery counts in `nxdns_upstream_reuse_recoveries_total` without touching health or emitting a diagnostics episode. Every other failure closes the session and classifies as before.
- `UpstreamHealth` per upstream: last_success_at, last_error_at, last_error_message, rolling success rate, consecutive failures, backoff-until. This is routing state: it drives failover and backoff, and is exposed through `/metrics` and `nxdns check`. There is no per-upstream API surface: `/api/health` reports the pool as available-of-enabled, and a failing upstream is a Diagnostics episode (`upstream.exchange`).
- DoH client: `std.http.Client` with `content-type/accept: application/dns-message`; strict status + payload checks.
- `platform/tls_client.zig` enforces per-connection read/write deadlines, classifies TLS errors explicitly, retries with backoff. Integration tests cover timeout/hang scenarios so compiler upgrades can't silently regress them.
@@ -482,6 +484,8 @@ CREATE INDEX idx_query_log_client ON query_log(client_ip);
CREATE INDEX idx_query_log_domain ON query_log(domain_id);
```
The sketch above is the original shape; `src/storage/querylog_schema.zig` is the authority, and the provenance columns milestone 28 added are not repeated here. Beside the raw rows the file carries four projection tables — `bucket_totals`, `bucket_clients`, `bucket_types`, `bucket_routes` — on a 30-minute grain, which is what `GET /api/overview` reads for the 24h, 7d and 30d windows instead of scanning every row. They are maintained by the batch writer and by retention inside the same transaction as the raw rows, so SQLite's transaction is the whole coherence story: no second file, no backfill, no rebuild command. The 1h window is narrower than the grain and takes one raw scan.
### 11.4 Query Logger
- In-memory buffer, mutex guarded, hard cap `query_log_buffer_max` (default 10000).
@@ -491,7 +495,7 @@ CREATE INDEX idx_query_log_domain ON query_log(domain_id);
### 11.5 Retention
Periodic delete of rows older than `retention_days`; scheduled checkpoint/VACUUM on `querylog.db` only.
Periodic delete of rows older than `retention_days`, dropping the projection buckets behind the cutoff and recomputing the straddling one in the same transaction; scheduled checkpoint/VACUUM on `querylog.db` only.
### 11.6 Disk Discipline (cloudflared lesson)
@@ -534,7 +538,7 @@ Scalars in `settings(key, value)`; ordered/structured items in dedicated tables.
### 13.1 Endpoints
- `POST /api/auth/login`, `POST /api/auth/logout`
- `GET /api/stats?period=…`, `GET /api/stats/timeseries?period=…`, `GET /api/stats/types?period=…`, `GET /api/stats/routes?period=…`, `GET /api/stats/clients?period=…`
- `GET /api/overview?period=…` — every Overview panel in one response over one read transaction
- `GET /api/queries` (filter + paginate), `GET /api/queries/live` (SSE, per-IP cap)
- `GET/PUT /api/clients/{id}`
- `GET/POST/PUT/DELETE /api/groups…`, `/api/blocklists…`, `/api/rules…`, `/api/local-records…`, `/api/forward-zones…`
@@ -662,7 +666,7 @@ The project publishes released binaries and container images from its own Gitea
6. Disk-fill degrades gracefully; no silent log-flood failure mode.
7. Web UI + API provide full admin functionality; OpenAPI contract tests green.
8. `nxdns export` round-trips via `nxdns import`.
9. Query logging, stats, SSE live stream work; querylog.db corruption self-heals.
9. Query logging, the overview, SSE live stream work; querylog.db corruption self-heals.
10. Local DoH + DoT endpoints serve LAN clients.
11. Schema upgrade = install + restart (migration test proves it).
12. All suites green in Gitea CI for both targets.
+508 -3
View File
@@ -11,6 +11,12 @@
"@stylexjs/stylex": "0.19.0",
"@tanstack/react-query": "5.101.4",
"@tanstack/react-router": "1.170.18",
"@visx/axis": "4.0.0",
"@visx/grid": "4.0.0",
"@visx/group": "4.0.0",
"@visx/scale": "4.0.0",
"@visx/shape": "4.0.0",
"@visx/tooltip": "4.0.0",
"react": "19.2.8",
"react-aria-components": "1.20.0",
"react-dom": "19.2.8"
@@ -1619,6 +1625,84 @@
"assertion-error": "^2.0.1"
}
},
"node_modules/@types/d3-array": {
"version": "3.0.3",
"resolved": "https://registry.npmjs.org/@types/d3-array/-/d3-array-3.0.3.tgz",
"integrity": "sha512-Reoy+pKnvsksN0lQUlcH6dOGjRZ/3WRwXR//m+/8lt1BXeI4xyaUZoqULNjyXXRuh0Mj4LNpkCvhUpQlY3X5xQ==",
"license": "MIT"
},
"node_modules/@types/d3-color": {
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/@types/d3-color/-/d3-color-3.1.0.tgz",
"integrity": "sha512-HKuicPHJuvPgCD+np6Se9MQvS6OCbJmOjGvylzMJRlDwUXjKTTXs6Pwgk79O09Vj/ho3u1ofXnhFOaEWWPrlwA==",
"license": "MIT"
},
"node_modules/@types/d3-delaunay": {
"version": "6.0.1",
"resolved": "https://registry.npmjs.org/@types/d3-delaunay/-/d3-delaunay-6.0.1.tgz",
"integrity": "sha512-tLxQ2sfT0p6sxdG75c6f/ekqxjyYR0+LwPrsO1mbC9YDBzPJhs2HbJJRrn8Ez1DBoHRo2yx7YEATI+8V1nGMnQ==",
"license": "MIT"
},
"node_modules/@types/d3-format": {
"version": "3.0.1",
"resolved": "https://registry.npmjs.org/@types/d3-format/-/d3-format-3.0.1.tgz",
"integrity": "sha512-5KY70ifCCzorkLuIkDe0Z9YTf9RR2CjBX1iaJG+rgM/cPP+sO+q9YdQ9WdhQcgPj1EQiJ2/0+yUkkziTG6Lubg==",
"license": "MIT"
},
"node_modules/@types/d3-geo": {
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/@types/d3-geo/-/d3-geo-3.1.0.tgz",
"integrity": "sha512-856sckF0oP/diXtS4jNsiQw/UuK5fQG8l/a9VVLeSouf1/PPbBE1i1W852zVwKwYCBkFJJB7nCFTbk6UMEXBOQ==",
"license": "MIT",
"dependencies": {
"@types/geojson": "*"
}
},
"node_modules/@types/d3-interpolate": {
"version": "3.0.1",
"resolved": "https://registry.npmjs.org/@types/d3-interpolate/-/d3-interpolate-3.0.1.tgz",
"integrity": "sha512-jx5leotSeac3jr0RePOH1KdR9rISG91QIE4Q2PYTu4OymLTZfA3SrnURSLzKH48HmXVUru50b8nje4E79oQSQw==",
"license": "MIT",
"dependencies": {
"@types/d3-color": "*"
}
},
"node_modules/@types/d3-path": {
"version": "3.1.1",
"resolved": "https://registry.npmjs.org/@types/d3-path/-/d3-path-3.1.1.tgz",
"integrity": "sha512-VMZBYyQvbGmWyWVea0EHs/BwLgxc+MKi1zLDCONksozI4YJMcTt8ZEuIR4Sb1MMTE8MMW49v0IwI5+b7RmfWlg==",
"license": "MIT"
},
"node_modules/@types/d3-scale": {
"version": "4.0.2",
"resolved": "https://registry.npmjs.org/@types/d3-scale/-/d3-scale-4.0.2.tgz",
"integrity": "sha512-Yk4htunhPAwN0XGlIwArRomOjdoBFXC3+kCxK2Ubg7I9shQlVSJy/pG/Ht5ASN+gdMIalpk8TJ5xV74jFsetLA==",
"license": "MIT",
"dependencies": {
"@types/d3-time": "*"
}
},
"node_modules/@types/d3-shape": {
"version": "3.1.7",
"resolved": "https://registry.npmjs.org/@types/d3-shape/-/d3-shape-3.1.7.tgz",
"integrity": "sha512-VLvUQ33C+3J+8p+Daf+nYSOsjB4GXp19/S/aGo60m9h1v6XaxjiT82lKVWJCfzhtuZ3yD7i/TPeC/fuKLLOSmg==",
"license": "MIT",
"dependencies": {
"@types/d3-path": "*"
}
},
"node_modules/@types/d3-time": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/@types/d3-time/-/d3-time-3.0.0.tgz",
"integrity": "sha512-sZLCdHvBUcNby1cB6Fd3ZBrABbjz3v1Vm90nysCQ6Vt7vd6e/h9Lt7SiJUoEX0l4Dzc7P5llKyhqSi1ycSf1Hg==",
"license": "MIT"
},
"node_modules/@types/d3-time-format": {
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/@types/d3-time-format/-/d3-time-format-2.1.0.tgz",
"integrity": "sha512-/myT3I7EwlukNOX2xVdMzb8FRgNzRMpsZddwst9Ld/VFe6LyJyRp0s32l/V9XoUzk+Gqu56F/oGk6507+8BxrA==",
"license": "MIT"
},
"node_modules/@types/deep-eql": {
"version": "4.0.2",
"resolved": "https://registry.npmjs.org/@types/deep-eql/-/deep-eql-4.0.2.tgz",
@@ -1633,6 +1717,12 @@
"dev": true,
"license": "MIT"
},
"node_modules/@types/geojson": {
"version": "7946.0.16",
"resolved": "https://registry.npmjs.org/@types/geojson/-/geojson-7946.0.16.tgz",
"integrity": "sha512-6C8nqWur3j98U6+lXDfTUWIfgvZU+EumvpHKcYjujKH7woYyLj2sUmff0tRhrqM7BohUw7Pz3ZB1jj2gW9Fvmg==",
"license": "MIT"
},
"node_modules/@types/node": {
"version": "26.1.1",
"resolved": "https://registry.npmjs.org/@types/node/-/node-26.1.1.tgz",
@@ -1647,7 +1737,7 @@
"version": "19.2.17",
"resolved": "https://registry.npmjs.org/@types/react/-/react-19.2.17.tgz",
"integrity": "sha512-MXfmqaVPEVgkBT/aY0aGCkRWWtByiYQXo3xdQ8r5RzuFrPiRn8Gar2tQdXSUQ2GKV3bkXckek89V8wQBY2Q/Aw==",
"dev": true,
"devOptional": true,
"license": "MIT",
"dependencies": {
"csstype": "^3.2.2"
@@ -1657,7 +1747,7 @@
"version": "19.2.3",
"resolved": "https://registry.npmjs.org/@types/react-dom/-/react-dom-19.2.3.tgz",
"integrity": "sha512-jp2L/eY6fn+KgVVQAOqYItbF0VY/YApe5Mz2F0aykSO8gx31bYCZyvSeYxCHKvzHG5eZjc+zyaS5BrBWya2+kQ==",
"dev": true,
"devOptional": true,
"license": "MIT",
"peerDependencies": {
"@types/react": "^19.2.0"
@@ -2003,6 +2093,211 @@
"node": ">=16.20.0"
}
},
"node_modules/@visx/axis": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/@visx/axis/-/axis-4.0.0.tgz",
"integrity": "sha512-cSPNO9Aic2UX49AmIeJJ9TQrrAkvUHpHOGqimUAXhbg07VI3HoHDKcXZdrjvQz+g0LhubrUkjj8Gwju2WZ3dtg==",
"license": "MIT",
"dependencies": {
"@visx/group": "4.0.0",
"@visx/point": "4.0.0",
"@visx/scale": "4.0.0",
"@visx/shape": "4.0.0",
"@visx/text": "4.0.0",
"classnames": "^2.3.1"
},
"peerDependencies": {
"@types/react": "^18.0.0 || ^19.0.0",
"react": "^18.0.0 || ^19.0.0"
},
"peerDependenciesMeta": {
"@types/react": {
"optional": true
}
}
},
"node_modules/@visx/bounds": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/@visx/bounds/-/bounds-4.0.0.tgz",
"integrity": "sha512-3wAfN5fg2bxg/5f3MlKWzGDTKU2hdKkxq8bVWXpPZQV0UiVc0myuU1qa34c7tN3hg5SDe6MJi/bae2eTQDgEiQ==",
"license": "MIT",
"peerDependencies": {
"@types/react": "^18.0.0 || ^19.0.0",
"@types/react-dom": "^18.0.0 || ^19.0.0",
"react": "^18.0.0 || ^19.0.0",
"react-dom": "^18.0.0 || ^19.0.0"
},
"peerDependenciesMeta": {
"@types/react": {
"optional": true
},
"@types/react-dom": {
"optional": true
}
}
},
"node_modules/@visx/curve": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/@visx/curve/-/curve-4.0.0.tgz",
"integrity": "sha512-bXrOSd2BzVCxR7kBE7gPTSU4plxzYN75w7erdHYabwn3vzP+xFk1o0gg3NOHEPJzt5tXqf0Ecm5YqHACOnipTA==",
"license": "MIT",
"dependencies": {
"@visx/vendor": "4.0.0"
}
},
"node_modules/@visx/grid": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/@visx/grid/-/grid-4.0.0.tgz",
"integrity": "sha512-BUnznqYo8jyn3zXRWZiF0zwg1VQl6w5kYqZ+XMY+cPXtAHZZbwGXBChMpPefH5Lj1+P1b4Pf3QihKG8zjL9PCw==",
"license": "MIT",
"dependencies": {
"@visx/curve": "4.0.0",
"@visx/group": "4.0.0",
"@visx/point": "4.0.0",
"@visx/scale": "4.0.0",
"@visx/shape": "4.0.0",
"classnames": "^2.3.1"
},
"peerDependencies": {
"@types/react": "^18.0.0 || ^19.0.0",
"react": "^18.0.0 || ^19.0.0"
},
"peerDependenciesMeta": {
"@types/react": {
"optional": true
}
}
},
"node_modules/@visx/group": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/@visx/group/-/group-4.0.0.tgz",
"integrity": "sha512-HGAq8BCqn5x0t94CJOLJeKtWss9LFpF3HY69HbuO1PlR+B9c4aVT9xbjfudmU8wGQZLT6JNt+PJvxbO2aJ+1aA==",
"license": "MIT",
"dependencies": {
"classnames": "^2.3.1"
},
"peerDependencies": {
"@types/react": "^18.0.0 || ^19.0.0",
"react": "^18.0.0 || ^19.0.0"
},
"peerDependenciesMeta": {
"@types/react": {
"optional": true
}
}
},
"node_modules/@visx/point": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/@visx/point/-/point-4.0.0.tgz",
"integrity": "sha512-hwJ9UlIjg3iV4iiJ3RN5SNTXama+zGaNe57sXSrSvPiqhkDXypsYBdDSlAnHmKbMzHP0zFmgB1UJciB/QUyigw==",
"license": "MIT"
},
"node_modules/@visx/scale": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/@visx/scale/-/scale-4.0.0.tgz",
"integrity": "sha512-Q3VaSLKlsrxxSl9CwS2D3Mvz4/4kIp/6NMKRY8Im0Au1hrQh2egU806p0+JwN0ccuGGDe03jyAxX4BSRAH8Plg==",
"license": "MIT",
"dependencies": {
"@visx/vendor": "4.0.0"
}
},
"node_modules/@visx/shape": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/@visx/shape/-/shape-4.0.0.tgz",
"integrity": "sha512-X0FP3OFjQhc5/6Vj2aY7cK2JwKYI0H0hQM7cdNRWy/ZMMlrh5KpEdqx0HVo0KoTeTlkUvO+kydMLnAuuCRFIFw==",
"license": "MIT",
"dependencies": {
"@visx/curve": "4.0.0",
"@visx/group": "4.0.0",
"@visx/scale": "4.0.0",
"@visx/vendor": "4.0.0",
"classnames": "^2.3.1"
},
"peerDependencies": {
"@types/react": "^18.0.0 || ^19.0.0",
"react": "^18.0.0 || ^19.0.0"
},
"peerDependenciesMeta": {
"@types/react": {
"optional": true
}
}
},
"node_modules/@visx/text": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/@visx/text/-/text-4.0.0.tgz",
"integrity": "sha512-39f2goSaKy5Mqn89lRDGSJ1IMr49wplkbIFHsFI8cPnAPbguiJxYZ+ulizd7Vcsq2z/hytuGv3Lmk165zUiUYQ==",
"license": "MIT",
"dependencies": {
"classnames": "^2.3.1",
"reduce-css-calc": "^1.3.0"
},
"peerDependencies": {
"@types/react": "^18.0.0 || ^19.0.0",
"react": "^18.0.0 || ^19.0.0"
},
"peerDependenciesMeta": {
"@types/react": {
"optional": true
}
}
},
"node_modules/@visx/tooltip": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/@visx/tooltip/-/tooltip-4.0.0.tgz",
"integrity": "sha512-+6J2h5qPvniT0pQtxQrLYGErPRVHr3pRfcMkNqTxD/HgofDGsL6vEBkjMR535MF1hkWYQ9XzOiWP6ERN4TF+mg==",
"license": "MIT",
"dependencies": {
"@visx/bounds": "4.0.0",
"classnames": "^2.3.1",
"react-use-measure": "^2.0.4"
},
"peerDependencies": {
"@types/react": "^18.0.0 || ^19.0.0",
"@types/react-dom": "^18.0.0 || ^19.0.0",
"react": "^18.0.0 || ^19.0.0",
"react-dom": "^18.0.0 || ^19.0.0"
},
"peerDependenciesMeta": {
"@types/react": {
"optional": true
},
"@types/react-dom": {
"optional": true
}
}
},
"node_modules/@visx/vendor": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/@visx/vendor/-/vendor-4.0.0.tgz",
"integrity": "sha512-LoBNzWjTXzBfu095BQxB14IwZQHHOLs8ZMzM6t2FL4ZGORaACgLcmXRRLhFo0VmRR8L7iNTM4HHc1j6yFvzsAA==",
"license": "MIT and ISC",
"dependencies": {
"@types/d3-array": "3.0.3",
"@types/d3-color": "3.1.0",
"@types/d3-delaunay": "6.0.1",
"@types/d3-format": "3.0.1",
"@types/d3-geo": "3.1.0",
"@types/d3-interpolate": "3.0.1",
"@types/d3-path": "3.1.1",
"@types/d3-scale": "4.0.2",
"@types/d3-shape": "3.1.7",
"@types/d3-time": "3.0.0",
"@types/d3-time-format": "2.1.0",
"d3-array": "3.2.1",
"d3-color": "3.1.0",
"d3-delaunay": "6.0.2",
"d3-format": "3.1.0",
"d3-geo": "3.1.0",
"d3-interpolate": "3.0.1",
"d3-path": "3.1.0",
"d3-scale": "4.0.2",
"d3-shape": "3.2.0",
"d3-time": "3.1.0",
"d3-time-format": "4.1.0",
"internmap": "2.0.3"
}
},
"node_modules/@vitejs/plugin-react": {
"version": "6.0.4",
"resolved": "https://registry.npmjs.org/@vitejs/plugin-react/-/plugin-react-6.0.4.tgz",
@@ -2211,6 +2506,12 @@
"node": ">=12"
}
},
"node_modules/balanced-match": {
"version": "0.4.2",
"resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-0.4.2.tgz",
"integrity": "sha512-STw03mQKnGUYtoNjmowo4F2cRmIIxYEGiMsjjwla/u5P1lxadj/05WkNaFjNiKTgJkj8KiXbgAiRTmcQRwQNtg==",
"license": "MIT"
},
"node_modules/baseline-browser-mapping": {
"version": "2.11.12",
"resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.11.12.tgz",
@@ -2299,6 +2600,12 @@
"node": ">=18"
}
},
"node_modules/classnames": {
"version": "2.5.1",
"resolved": "https://registry.npmjs.org/classnames/-/classnames-2.5.1.tgz",
"integrity": "sha512-saHYOzhIQs6wy2sVxTM6bUDsQO4F50V9RQ22qBpEdCW+I+/Wmke2HOl6lS6dTpdxVhb88/I6+Hs+438c3lfUow==",
"license": "MIT"
},
"node_modules/client-only": {
"version": "0.0.1",
"resolved": "https://registry.npmjs.org/client-only/-/client-only-0.0.1.tgz",
@@ -2351,9 +2658,136 @@
"version": "3.2.3",
"resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz",
"integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==",
"dev": true,
"devOptional": true,
"license": "MIT"
},
"node_modules/d3-array": {
"version": "3.2.1",
"resolved": "https://registry.npmjs.org/d3-array/-/d3-array-3.2.1.tgz",
"integrity": "sha512-gUY/qeHq/yNqqoCKNq4vtpFLdoCdvyNpWoC/KNjhGbhDuQpAM9sIQQKkXSNpXa9h5KySs/gzm7R88WkUutgwWQ==",
"license": "ISC",
"dependencies": {
"internmap": "1 - 2"
},
"engines": {
"node": ">=12"
}
},
"node_modules/d3-color": {
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/d3-color/-/d3-color-3.1.0.tgz",
"integrity": "sha512-zg/chbXyeBtMQ1LbD/WSoW2DpC3I0mpmPdW+ynRTj/x2DAWYrIY7qeZIHidozwV24m4iavr15lNwIwLxRmOxhA==",
"license": "ISC",
"engines": {
"node": ">=12"
}
},
"node_modules/d3-delaunay": {
"version": "6.0.2",
"resolved": "https://registry.npmjs.org/d3-delaunay/-/d3-delaunay-6.0.2.tgz",
"integrity": "sha512-IMLNldruDQScrcfT+MWnazhHbDJhcRJyOEBAJfwQnHle1RPh6WDuLvxNArUju2VSMSUuKlY5BGHRJ2cYyoFLQQ==",
"license": "ISC",
"dependencies": {
"delaunator": "5"
},
"engines": {
"node": ">=12"
}
},
"node_modules/d3-format": {
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/d3-format/-/d3-format-3.1.0.tgz",
"integrity": "sha512-YyUI6AEuY/Wpt8KWLgZHsIU86atmikuoOmCfommt0LYHiQSPjvX2AcFc38PX0CBpr2RCyZhjex+NS/LPOv6YqA==",
"license": "ISC",
"engines": {
"node": ">=12"
}
},
"node_modules/d3-geo": {
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/d3-geo/-/d3-geo-3.1.0.tgz",
"integrity": "sha512-JEo5HxXDdDYXCaWdwLRt79y7giK8SbhZJbFWXqbRTolCHFI5jRqteLzCsq51NKbUoX0PjBVSohxrx+NoOUujYA==",
"license": "ISC",
"dependencies": {
"d3-array": "2.5.0 - 3"
},
"engines": {
"node": ">=12"
}
},
"node_modules/d3-interpolate": {
"version": "3.0.1",
"resolved": "https://registry.npmjs.org/d3-interpolate/-/d3-interpolate-3.0.1.tgz",
"integrity": "sha512-3bYs1rOD33uo8aqJfKP3JWPAibgw8Zm2+L9vBKEHJ2Rg+viTR7o5Mmv5mZcieN+FRYaAOWX5SJATX6k1PWz72g==",
"license": "ISC",
"dependencies": {
"d3-color": "1 - 3"
},
"engines": {
"node": ">=12"
}
},
"node_modules/d3-path": {
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/d3-path/-/d3-path-3.1.0.tgz",
"integrity": "sha512-p3KP5HCf/bvjBSSKuXid6Zqijx7wIfNW+J/maPs+iwR35at5JCbLUT0LzF1cnjbCHWhqzQTIN2Jpe8pRebIEFQ==",
"license": "ISC",
"engines": {
"node": ">=12"
}
},
"node_modules/d3-scale": {
"version": "4.0.2",
"resolved": "https://registry.npmjs.org/d3-scale/-/d3-scale-4.0.2.tgz",
"integrity": "sha512-GZW464g1SH7ag3Y7hXjf8RoUuAFIqklOAq3MRl4OaWabTFJY9PN/E1YklhXLh+OQ3fM9yS2nOkCoS+WLZ6kvxQ==",
"license": "ISC",
"dependencies": {
"d3-array": "2.10.0 - 3",
"d3-format": "1 - 3",
"d3-interpolate": "1.2.0 - 3",
"d3-time": "2.1.1 - 3",
"d3-time-format": "2 - 4"
},
"engines": {
"node": ">=12"
}
},
"node_modules/d3-shape": {
"version": "3.2.0",
"resolved": "https://registry.npmjs.org/d3-shape/-/d3-shape-3.2.0.tgz",
"integrity": "sha512-SaLBuwGm3MOViRq2ABk3eLoxwZELpH6zhl3FbAoJ7Vm1gofKx6El1Ib5z23NUEhF9AsGl7y+dzLe5Cw2AArGTA==",
"license": "ISC",
"dependencies": {
"d3-path": "^3.1.0"
},
"engines": {
"node": ">=12"
}
},
"node_modules/d3-time": {
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/d3-time/-/d3-time-3.1.0.tgz",
"integrity": "sha512-VqKjzBLejbSMT4IgbmVgDjpkYrNWUYJnbCGo874u7MMKIWsILRX+OpX/gTk8MqjpT1A/c6HY2dCA77ZN0lkQ2Q==",
"license": "ISC",
"dependencies": {
"d3-array": "2 - 3"
},
"engines": {
"node": ">=12"
}
},
"node_modules/d3-time-format": {
"version": "4.1.0",
"resolved": "https://registry.npmjs.org/d3-time-format/-/d3-time-format-4.1.0.tgz",
"integrity": "sha512-dJxPBlzC7NugB2PDLwo9Q8JiTR3M3e4/XANkreKSUxF8vvXKqm1Yfq4Q5dl8budlunRVlUUaDUgFt7eA8D6NLg==",
"license": "ISC",
"dependencies": {
"d3-time": "1 - 3"
},
"engines": {
"node": ">=12"
}
},
"node_modules/data-urls": {
"version": "7.0.0",
"resolved": "https://registry.npmjs.org/data-urls/-/data-urls-7.0.0.tgz",
@@ -2393,6 +2827,15 @@
"dev": true,
"license": "MIT"
},
"node_modules/delaunator": {
"version": "5.1.0",
"resolved": "https://registry.npmjs.org/delaunator/-/delaunator-5.1.0.tgz",
"integrity": "sha512-AGrQ4QSgssa1NGmWmLPqN5NY2KajF5MqxetNEO+o0n3ZwZZeTmt7bBnvzHWrmkZFxGgr4HdyFgelzgi06otLuQ==",
"license": "ISC",
"dependencies": {
"robust-predicates": "^3.0.2"
}
},
"node_modules/dequal": {
"version": "2.0.3",
"resolved": "https://registry.npmjs.org/dequal/-/dequal-2.0.3.tgz",
@@ -2533,6 +2976,15 @@
"node": "^20.19.0 || ^22.12.0 || >=24.0.0"
}
},
"node_modules/internmap": {
"version": "2.0.3",
"resolved": "https://registry.npmjs.org/internmap/-/internmap-2.0.3.tgz",
"integrity": "sha512-5Hh7Y1wQbvY5ooGgPbDaL5iYLAPzMTUrjMulskHLH6wnv/A+1q5rgEaiuqEjB+oxGXIVZs1FF+R/KPN3ZSQYYg==",
"license": "ISC",
"engines": {
"node": ">=12"
}
},
"node_modules/invariant": {
"version": "2.2.4",
"resolved": "https://registry.npmjs.org/invariant/-/invariant-2.2.4.tgz",
@@ -2946,6 +3398,12 @@
"@jridgewell/sourcemap-codec": "^1.5.5"
}
},
"node_modules/math-expression-evaluator": {
"version": "1.4.0",
"resolved": "https://registry.npmjs.org/math-expression-evaluator/-/math-expression-evaluator-1.4.0.tgz",
"integrity": "sha512-4vRUvPyxdO8cWULGTh9dZWL2tZK6LDBvj+OGHBER7poH9Qdt7kXEoj20wiz4lQUbUXQZFjPbe5mVDo9nutizCw==",
"license": "MIT"
},
"node_modules/mdn-data": {
"version": "2.27.1",
"resolved": "https://registry.npmjs.org/mdn-data/-/mdn-data-2.27.1.tgz",
@@ -3254,6 +3712,47 @@
"react": "^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1"
}
},
"node_modules/react-use-measure": {
"version": "2.1.7",
"resolved": "https://registry.npmjs.org/react-use-measure/-/react-use-measure-2.1.7.tgz",
"integrity": "sha512-KrvcAo13I/60HpwGO5jpW7E9DfusKyLPLvuHlUyP5zqnmAPhNc6qTRjUQrdTADl0lpPpDVU2/Gg51UlOGHXbdg==",
"license": "MIT",
"peerDependencies": {
"react": ">=16.13",
"react-dom": ">=16.13"
},
"peerDependenciesMeta": {
"react-dom": {
"optional": true
}
}
},
"node_modules/reduce-css-calc": {
"version": "1.3.0",
"resolved": "https://registry.npmjs.org/reduce-css-calc/-/reduce-css-calc-1.3.0.tgz",
"integrity": "sha512-0dVfwYVOlf/LBA2ec4OwQ6p3X9mYxn/wOl2xTcLwjnPYrkgEfPx3VI4eGCH3rQLlPISG5v9I9bkZosKsNRTRKA==",
"license": "MIT",
"dependencies": {
"balanced-match": "^0.4.2",
"math-expression-evaluator": "^1.2.14",
"reduce-function-call": "^1.0.1"
}
},
"node_modules/reduce-function-call": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/reduce-function-call/-/reduce-function-call-1.0.3.tgz",
"integrity": "sha512-Hl/tuV2VDgWgCSEeWMLwxLZqX7OK59eU1guxXsRKTAyeYimivsKdtcV4fu3r710tpG5GmDKDhQ0HSZLExnNmyQ==",
"license": "MIT",
"dependencies": {
"balanced-match": "^1.0.0"
}
},
"node_modules/reduce-function-call/node_modules/balanced-match": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz",
"integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==",
"license": "MIT"
},
"node_modules/require-from-string": {
"version": "2.0.2",
"resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz",
@@ -3264,6 +3763,12 @@
"node": ">=0.10.0"
}
},
"node_modules/robust-predicates": {
"version": "3.0.3",
"resolved": "https://registry.npmjs.org/robust-predicates/-/robust-predicates-3.0.3.tgz",
"integrity": "sha512-NS3levdsRIUOmiJ8FZWCP7LG3QpJyrs/TE0Zpf1yvZu8cAJJ6QMW92H1c7kWpdIHo8RvmLxN/o2JXTKHp74lUA==",
"license": "Unlicense"
},
"node_modules/rolldown": {
"version": "1.1.5",
"resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.1.5.tgz",
+7 -1
View File
@@ -8,7 +8,7 @@
},
"scripts": {
"dev": "vite",
"build": "vite build && node scripts/assert-css-layers.mjs && node scripts/stamp-dist.mjs",
"build": "vite build && node scripts/assert-css-layers.mjs && node scripts/assert-bundle-size.mjs && node scripts/stamp-dist.mjs",
"typecheck": "tsc -b",
"lint": "oxlint src vite.config.ts",
"format": "prettier --write .",
@@ -28,6 +28,12 @@
"@stylexjs/stylex": "0.19.0",
"@tanstack/react-query": "5.101.4",
"@tanstack/react-router": "1.170.18",
"@visx/axis": "4.0.0",
"@visx/grid": "4.0.0",
"@visx/group": "4.0.0",
"@visx/scale": "4.0.0",
"@visx/shape": "4.0.0",
"@visx/tooltip": "4.0.0",
"react": "19.2.8",
"react-aria-components": "1.20.0",
"react-dom": "19.2.8"
+55
View File
@@ -0,0 +1,55 @@
#!/usr/bin/env node
// The admin bundle is embedded in the server binary and served to a household
// LAN, so an accidental dependency or a stray asset landing in dist is a
// regression nobody would otherwise notice: every other gate passes with a
// bundle twice this size. One number, total bytes of dist/assets — not per
// chunk, not gzipped — because the failure being caught is "something big
// arrived", not chunk shape.
//
// This runs from admin/ as part of `npm run build`, before stamp-dist: a failed
// size check must not leave a fresh .src-hash beside an oversized bundle that a
// later Zig build would accept as current.
import { readdirSync, statSync } from "node:fs";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
const BUDGET_BYTES = 800_000;
const distDir = join(dirname(dirname(fileURLToPath(import.meta.url))), "dist", "assets");
let entries;
try {
entries = readdirSync(distDir, { withFileTypes: true });
} catch (err) {
console.error(`assert-bundle-size: cannot read admin/dist/assets: ${err.message}`);
process.exit(1);
}
const files = entries
.filter((entry) => entry.isFile())
.map((entry) => ({ name: entry.name, bytes: statSync(join(distDir, entry.name)).size }))
.sort((a, b) => b.bytes - a.bytes);
if (files.length === 0) {
console.error("assert-bundle-size: no files in admin/dist/assets — did the build emit anything?");
process.exit(1);
}
const total = files.reduce((sum, file) => sum + file.bytes, 0);
const format = (bytes) => bytes.toLocaleString("en-US");
if (total > BUDGET_BYTES) {
console.error(
`assert-bundle-size: admin/dist/assets is ${format(total)} bytes, over the ${format(BUDGET_BYTES)} byte budget.`,
);
console.error("Largest chunks:");
for (const file of files.slice(0, 5)) console.error(` ${format(file.bytes).padStart(9)} ${file.name}`);
console.error("Drop what arrived, or raise the budget in this script with the reason in the changelog.");
process.exit(1);
}
console.log(
`admin/dist/assets is ${format(total)} bytes across ${files.length} files, ` +
`${format(BUDGET_BYTES - total)} under the ${format(BUDGET_BYTES)} byte budget`,
);
@@ -5,7 +5,7 @@ import { AuthProvider } from "@/auth/store";
import { createQueryClient } from "@/lib/queryClient";
import { createAppRouter } from "@/routes";
import type { QueryDetail } from "@/lib/types";
import { provenance } from "@/features/queries/provenanceFixture";
import { provenance } from "@/features/provenance/provenanceFixture";
import { health } from "@/lib/healthFixture";
function detail(id: number, sections: Parameters<typeof provenance>[0] = {}): QueryDetail {
@@ -11,7 +11,7 @@ import { createQueryClient } from "@/lib/queryClient";
import { createAppRouter } from "@/routes";
import { health } from "@/lib/healthFixture";
import type { Client, Coverage, QueriesPage, QueryRow } from "@/lib/types";
import { queryRow } from "@/features/queries/provenanceFixture";
import { queryRow } from "@/features/provenance/provenanceFixture";
function client(id: number, ip: string, name: string, learnedName: string): Client {
return {
@@ -15,7 +15,7 @@ import InlineError from "@/lib/InlineError";
import { queriesInfiniteQuery } from "@/lib/queries";
import type { QueryRow } from "@/lib/types";
import { useClientNames } from "@/features/clients/clientNames";
import { summarizeRow } from "@/features/queries/querySummary";
import { summarizeRow } from "@/features/provenance/querySummary";
import { styles as shared } from "@/ui/styles";
import { colors } from "@/ui/tokens.stylex";
import { ActivityCells, ActivityTableHead, activityDomainLink } from "./cells";
@@ -8,14 +8,25 @@
import { act, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
import { QueryClientProvider } from "@tanstack/react-query";
import { RouterProvider, createMemoryHistory } from "@tanstack/react-router";
import { RouterContextProvider, RouterProvider, createMemoryHistory } from "@tanstack/react-router";
import { AuthProvider } from "@/auth/store";
import { createQueryClient } from "@/lib/queryClient";
import { createAppRouter } from "@/routes";
import type { Client } from "@/lib/types";
import { provenance, queryRow } from "@/features/queries/provenanceFixture";
import { provenance, queryRow } from "@/features/provenance/provenanceFixture";
import { health } from "@/lib/healthFixture";
import { FakeEventSource } from "./fakeEventSource";
import LiveActivity from "./LiveActivity";
import type { ActivitySearch } from "./search";
const LIVE_ORIGIN: ActivitySearch = {
mode: "live",
since: undefined,
until: undefined,
domain: undefined,
client: undefined,
blocked: undefined,
};
function client(ip: string, name: string, learnedName: string): Client {
return {
@@ -327,23 +338,55 @@ test("opening a second row moves the expanded state and the focus with it", asyn
expect(document.activeElement).toBe(second);
});
test("an open streamed detail survives the row being evicted from the ring buffer", async () => {
await openLive();
/**
* The one render that bypasses the route, because the ring capacity is a
* parameter of the component and the route deliberately never passes it:
* evicting a row at the real 500 means pushing 500 frames through React state,
* which proves nothing the fifth frame does not. The real route tree still
* backs the links inside the detail.
*/
function renderLiveWithCapacity(capacity: number) {
const queryClient = createQueryClient();
const router = createAppRouter(createMemoryHistory({ initialEntries: ["/activity?mode=live"] }), queryClient);
render(
<AuthProvider>
<QueryClientProvider client={queryClient}>
<RouterContextProvider router={router}>
<LiveActivity origin={LIVE_ORIGIN} capacity={capacity} />
</RouterContextProvider>
</QueryClientProvider>
</AuthProvider>,
);
}
test("an open streamed detail survives the row being evicted from the ring buffer", () => {
renderLiveWithCapacity(5);
act(() => sources[0]!.emit("open"));
act(() => sources[0]!.emit("query", frame(1000, "evicted.example")));
fireEvent.click(screen.getByRole("button", { name: "evicted.example" }));
expect(screen.getByRole("heading", { level: 1, name: "evicted.example" })).toBeTruthy();
// 500 more queries: the ring keeps the newest 500, so the selected row is
// gone from the table. The detail is a snapshot, not a lookup into the ring.
// One ringful more: the ring keeps the newest 5, so the selected row is gone
// from the table. The detail is a snapshot, not a lookup into the ring.
act(() => {
for (let index = 0; index < 500; index += 1) {
for (let index = 0; index < 5; index += 1) {
sources[0]!.emit("query", frame(2000 + index, `filler${index}.example`));
}
});
expect(screen.getAllByRole("row")).toHaveLength(6);
expect(screen.queryByRole("button", { name: "evicted.example" })).toBeNull();
expect(screen.getByRole("heading", { level: 1, name: "evicted.example" })).toBeTruthy();
});
test("the route renders the live ring at its production capacity", async () => {
await openLive();
act(() => sources[0]!.emit("query", frame(1000, "pinned.example")));
expect(screen.getByText(/last 500 kept/)).toBeTruthy();
fireEvent.click(screen.getByRole("button", { name: "Freeze" }));
expect(screen.getByText(/newest 500 kept/)).toBeTruthy();
});
test("an open streamed detail survives Freeze and Resume", async () => {
await openLive();
act(() => sources[0]!.emit("query", frame(1000, "held.example")));
+16 -6
View File
@@ -16,7 +16,7 @@ import { useEffect, useRef, useState } from "react";
import { Link } from "@tanstack/react-router";
import * as stylex from "@stylexjs/stylex";
import { useClientNames } from "@/features/clients/clientNames";
import { summarizeEvent } from "@/features/queries/querySummary";
import { summarizeEvent } from "@/features/provenance/querySummary";
import { styles as shared } from "@/ui/styles";
import { colors } from "@/ui/tokens.stylex";
import { ActivityCells, ActivityTableHead, activityDomainLink } from "./cells";
@@ -276,8 +276,19 @@ function LiveDetail({ row, origin, onClose }: { row: StreamedRow; origin: Activi
);
}
export default function LiveActivity({ origin }: { origin: ActivitySearch }) {
const live = useLiveQueries();
/**
* `capacity` is the ring size, a parameter only so a test can provoke an
* eviction with a handful of rows rather than 500 frames through React state.
* The route renders this without it, so the app is always the 500-row ring.
*/
export default function LiveActivity({
origin,
capacity = RING_CAPACITY,
}: {
origin: ActivitySearch;
capacity?: number;
}) {
const live = useLiveQueries({ capacity });
const clientNames = useClientNames();
const [selected, setSelected] = useState<StreamedRow | null>(null);
const trigger = useRef<HTMLButtonElement | null>(null);
@@ -312,8 +323,7 @@ export default function LiveActivity({ origin }: { origin: ActivitySearch }) {
{live.frozen && (
<p {...stylex.props(styles.note)} role="status">
Display frozen new queries keep buffering ({live.liveCount} in buffer, newest {RING_CAPACITY}{" "}
kept).
Display frozen new queries keep buffering ({live.liveCount} in buffer, newest {capacity} kept).
</p>
)}
@@ -413,7 +423,7 @@ export default function LiveActivity({ origin }: { origin: ActivitySearch }) {
</div>
<p {...stylex.props(styles.footnote)}>
Showing {live.rows.length} {live.rows.length === 1 ? "query" : "queries"} (newest first, last{" "}
{RING_CAPACITY} kept).
{capacity} kept).
</p>
</>
)}
@@ -19,8 +19,8 @@ import {
qclassName,
rcodeName,
routeKindLabel,
} from "@/features/queries/provenanceCopy";
import { qtypeName } from "@/features/queries/qtype";
} from "@/features/provenance/provenanceCopy";
import { qtypeName } from "@/features/provenance/qtype";
import { styles as shared } from "@/ui/styles";
import { colors } from "@/ui/tokens.stylex";
+2 -2
View File
@@ -1,8 +1,8 @@
import { render, screen } from "@testing-library/react";
import type { QueryRow } from "@/lib/types";
import type { ClientNames } from "@/features/clients/clientNames";
import { queryRow } from "@/features/queries/provenanceFixture";
import { summarizeRow, type QuerySummary } from "@/features/queries/querySummary";
import { queryRow } from "@/features/provenance/provenanceFixture";
import { summarizeRow, type QuerySummary } from "@/features/provenance/querySummary";
import { ACTIVITY_COLUMNS, ActivityCells, ActivityTableHead, resultLabel, routeLabel } from "./cells";
const noNames: ClientNames = new Map();
+3 -3
View File
@@ -17,9 +17,9 @@ import * as stylex from "@stylexjs/stylex";
import { formatMicros, formatTime } from "@/lib/format";
import type { RouteKind } from "@/lib/types";
import { ClientName, type ClientNames } from "@/features/clients/clientNames";
import { rcodeShortName } from "@/features/queries/provenanceCopy";
import { qtypeName } from "@/features/queries/qtype";
import type { QuerySummary } from "@/features/queries/querySummary";
import { rcodeShortName } from "@/features/provenance/provenanceCopy";
import { qtypeName } from "@/features/provenance/qtype";
import type { QuerySummary } from "@/features/provenance/querySummary";
import { styles as shared } from "@/ui/styles";
import { colors } from "@/ui/tokens.stylex";
@@ -0,0 +1,58 @@
import { diagnosticsBounds, relatedBounds, RELATED_WINDOW_SECONDS } from "./relatedLinks";
import { queriesFilterOf, validateActivitySearch } from "./search";
const TS = 1_700_000_000;
test("an unbounded origin falls back to the window either side of the query", () => {
expect(relatedBounds(TS, { since: undefined, until: undefined })).toEqual({
since: TS - RELATED_WINDOW_SECONDS,
until: TS + RELATED_WINDOW_SECONDS,
});
});
test("a bounded origin carries both of its bounds through unchanged", () => {
expect(relatedBounds(TS, { since: 1, until: 2 })).toEqual({ since: 1, until: 2 });
});
test("a half-bounded origin keeps its half and falls back on the other", () => {
expect(relatedBounds(TS, { since: 1, until: undefined })).toEqual({
since: 1,
until: TS + RELATED_WINDOW_SECONDS,
});
expect(relatedBounds(TS, { since: undefined, until: 2 })).toEqual({
since: TS - RELATED_WINDOW_SECONDS,
until: 2,
});
});
test("an origin bound of zero is a bound, not a missing one", () => {
expect(relatedBounds(TS, { since: 0, until: 0 })).toEqual({ since: 0, until: 0 });
});
test("the diagnostics window is the fixed window either side of the query, never inherited", () => {
expect(diagnosticsBounds(TS)).toEqual({ since: TS - RELATED_WINDOW_SECONDS, until: TS + RELATED_WINDOW_SECONDS });
expect(diagnosticsBounds(0)).toEqual({ since: -RELATED_WINDOW_SECONDS, until: RELATED_WINDOW_SECONDS });
});
/**
* The admin half of the server's `since <= ts < until` window contract
* (queries_repo.zig): what a related link emits has to survive the validation
* the Activity route puts every search through, or the link would silently open
* a wider window than it named. Inclusion at the edges is the server's property
* and is tested there; this pins that the bounds arrive intact.
*/
test("bounds emitted by a related link round-trip through the Activity search to the same filter", () => {
const origin = { since: undefined, until: TS + 3_600 };
const emitted = { mode: "history", domain: "ads.example.com", ...relatedBounds(TS, origin) };
const applied = validateActivitySearch(emitted);
expect(applied.mode).toBe("history");
expect(applied.since).toBe(emitted.since);
expect(applied.until).toBe(emitted.until);
expect(queriesFilterOf(applied)).toEqual({
domain: "ads.example.com",
since: TS - RELATED_WINDOW_SECONDS,
until: TS + 3_600,
});
});
@@ -1,5 +1,5 @@
import type { Provenance, QueryRow } from "@/lib/types";
import { provenance, queryRow } from "@/features/queries/provenanceFixture";
import { provenance, queryRow } from "@/features/provenance/provenanceFixture";
import { RING_CAPACITY, mergeGap, pushRow, summaryOf, type LiveRow } from "./ringBuffer";
function streamed(key: number, ts: number, domain: string, sections: Parameters<typeof provenance>[0] = {}): LiveRow {
+1 -1
View File
@@ -1,5 +1,5 @@
import type { LiveQueryEvent, QueryRow } from "@/lib/types";
import { summarizeEvent, summarizeRow, type QuerySummary } from "@/features/queries/querySummary";
import { summarizeEvent, summarizeRow, type QuerySummary } from "@/features/provenance/querySummary";
/**
* A row in the live buffer. `key` is a client-side monotonic counter, because
@@ -1,7 +1,7 @@
import { act, renderHook, waitFor } from "@testing-library/react";
import { ApiError } from "@/lib/api";
import type { QueriesPage, QueryRow } from "@/lib/types";
import { provenance, queryRow } from "@/features/queries/provenanceFixture";
import { provenance, queryRow } from "@/features/provenance/provenanceFixture";
import { summaryOf, type LiveRow } from "./ringBuffer";
import { FakeEventSource } from "./fakeEventSource";
import { CAP_ERROR_THRESHOLD, useLiveQueries } from "./useLiveQueries";
+18 -8
View File
@@ -24,6 +24,12 @@ export interface LiveQueriesOptions {
fetchSince?: (since: number) => Promise<QueriesPage>;
/** Cheap session-gated GET fired once on entering capped, to distinguish an expired session from a real cap. */
probeSession?: () => Promise<unknown>;
/**
* Ring size. Injectable so a test can provoke an eviction with a handful of
* rows instead of pushing 500 frames through React state; the app never
* passes it, and the operator never sees it.
*/
capacity?: number;
}
// A transient drop is invisible to EventSource beyond a bare `error` event;
@@ -34,7 +40,10 @@ export interface LiveQueriesOptions {
export const CAP_ERROR_THRESHOLD = 3;
const defaultEventSource: EventSourceFactory = (url) => new EventSource(url);
const defaultFetchSince = (since: number): Promise<QueriesPage> => api.getQueries({ since, limit: RING_CAPACITY });
const defaultFetchSince =
(capacity: number) =>
(since: number): Promise<QueriesPage> =>
api.getQueries({ since, limit: capacity });
const defaultProbeSession = (): Promise<unknown> => api.getPause();
function isUnauthorized(error: unknown): boolean {
@@ -79,7 +88,8 @@ export function useLiveQueries(options?: LiveQueriesOptions): LiveQueries {
errorsRef.current = 0;
setStatus("connecting");
const opts = optionsRef.current;
const fetchSince = opts?.fetchSince ?? defaultFetchSince;
const capacity = opts?.capacity ?? RING_CAPACITY;
const fetchSince = opts?.fetchSince ?? defaultFetchSince(capacity);
const probeSession = opts?.probeSession ?? defaultProbeSession;
const es = (opts?.createEventSource ?? defaultEventSource)(opts?.url ?? api.liveQueriesUrl);
esRef.current = es;
@@ -94,7 +104,7 @@ export function useLiveQueries(options?: LiveQueriesOptions): LiveQueries {
fetchSince(since).then(
(page) => {
if (esRef.current !== es) return;
const merged = mergeGap(bufferRef.current, page.queries, () => ++keyRef.current);
const merged = mergeGap(bufferRef.current, page.queries, () => ++keyRef.current, capacity);
bufferRef.current = merged.rows;
setRows(merged.rows);
setMissed(merged.missed);
@@ -122,11 +132,11 @@ export function useLiveQueries(options?: LiveQueriesOptions): LiveQueries {
return;
}
lastSeenTsRef.current = payload.request.time;
bufferRef.current = pushRow(bufferRef.current, {
kind: "streamed",
event: payload,
key: ++keyRef.current,
});
bufferRef.current = pushRow(
bufferRef.current,
{ kind: "streamed", event: payload, key: ++keyRef.current },
capacity,
);
setRows(bufferRef.current);
});
@@ -1,279 +0,0 @@
import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";
import { QueryClientProvider } from "@tanstack/react-query";
import { RouterProvider, createMemoryHistory } from "@tanstack/react-router";
import { AuthProvider } from "@/auth/store";
import { createQueryClient } from "@/lib/queryClient";
import { createAppRouter } from "@/routes";
import { clearRefreshStatus } from "@/features/blocklists/refreshStore";
const BLOCKLISTS = {
blocklists: [
{
id: 1,
url: "https://example.com/hosts.txt",
name: "StevenBlack",
enabled: true,
is_suggested: true,
last_updated: 1700000000,
domain_count: 1000,
wildcard_count: 10,
exception_count: 7,
skipped_regex_count: 3,
skipped_unsupported_count: 21,
checksum: "abc",
},
{
id: 2,
url: "https://example.org/list.txt",
name: "Custom",
enabled: false,
is_suggested: false,
last_updated: null,
domain_count: 0,
wildcard_count: 0,
exception_count: 0,
skipped_regex_count: 0,
skipped_unsupported_count: 0,
checksum: null,
},
],
};
const RESPONSES: Record<string, unknown> = {
"/api/blocklists": BLOCKLISTS,
"/api/version": { version: "0.0.0-test", git_commit: "0000000", zig_version: "0.16.0", uptime_seconds: 1 },
};
let resolveUpdate: ((response: Response) => void) | null;
let deleted: string[];
beforeEach(() => {
clearRefreshStatus();
resolveUpdate = null;
deleted = [];
vi.stubGlobal(
"fetch",
vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
const url = String(input);
if (init?.method === "DELETE") {
deleted.push(url);
return new Response(null, { status: 204 });
}
if (url === "/api/blocklists/update" && init?.method === "POST") {
return new Promise<Response>((resolve) => {
resolveUpdate = resolve;
});
}
const payload = RESPONSES[url];
if (payload === undefined) return new Response(JSON.stringify({ error: "not stubbed" }), { status: 404 });
return new Response(JSON.stringify(payload), {
status: 200,
headers: { "content-type": "application/json" },
});
}),
);
});
afterEach(() => {
vi.unstubAllGlobals();
});
function renderBlocklistsRoute(queryClient = createQueryClient()) {
const router = createAppRouter(createMemoryHistory({ initialEntries: ["/blocklists"] }), queryClient);
const view = render(
<AuthProvider>
<QueryClientProvider client={queryClient}>
<RouterProvider router={router} />
</QueryClientProvider>
</AuthProvider>,
);
return { queryClient, unmount: view.unmount };
}
const SNAPSHOT = {
sources: [
{
id: 1,
state: "loaded",
loaded: true,
last_attempt: 1700000100,
last_success: 1700000100,
url: "https://example.com/hosts.txt",
last_error: "",
domains: 1200,
wildcards: 12,
exceptions: 9,
skipped_regex: 4,
skipped_unsupported: 17,
},
],
};
test("renders the source table and the status empty state", async () => {
renderBlocklistsRoute();
await screen.findByRole("heading", { name: "Blocklists" });
expect(screen.getByText("StevenBlack")).toBeTruthy();
expect(screen.getByText("https://example.com/hosts.txt")).toBeTruthy();
expect(screen.getByText("Suggested")).toBeTruthy();
expect(screen.getByText("1000")).toBeTruthy();
expect(screen.getByText("10")).toBeTruthy();
expect(screen.getByText("7")).toBeTruthy();
expect(screen.getByText("3")).toBeTruthy();
expect(screen.getByText("21")).toBeTruthy();
expect(screen.getByText("never")).toBeTruthy();
expect(screen.getByRole("columnheader", { name: "Skipped regex" })).toBeTruthy();
expect(screen.getByRole("columnheader", { name: "Skipped unsupported" })).toBeTruthy();
expect(
screen.getByText(/Skipped unsupported lines are syntax nxdns cannot translate into a DNS decision/),
).toBeTruthy();
const enabledToggle = screen.getByLabelText("StevenBlack enabled") as HTMLInputElement;
expect(enabledToggle.checked).toBe(true);
const disabledToggle = screen.getByLabelText("Custom enabled") as HTMLInputElement;
expect(disabledToggle.checked).toBe(false);
expect(screen.getByText(/run .Update now. to fetch status/)).toBeTruthy();
expect(screen.getByRole("heading", { name: "Add source" })).toBeTruthy();
});
test("update now disables the button, then replaces the status section from the 202 snapshot", async () => {
renderBlocklistsRoute();
await screen.findByRole("heading", { name: "Blocklists" });
const button = screen.getByRole("button", { name: "Update now" }) as HTMLButtonElement;
fireEvent.click(button);
const pending = (await screen.findByRole("button", { name: "Updating…" })) as HTMLButtonElement;
expect(pending.disabled).toBe(true);
expect(resolveUpdate).not.toBeNull();
const snapshot = {
sources: [
{
id: 1,
state: "loaded",
loaded: true,
last_attempt: 1700000100,
last_success: 1700000100,
url: "https://example.com/hosts.txt",
last_error: "",
domains: 1200,
wildcards: 12,
exceptions: 9,
skipped_regex: 4,
skipped_unsupported: 17,
},
{
id: 2,
state: "fetch_failed",
loaded: false,
last_attempt: 1700000100,
last_success: 0,
url: "https://example.org/list.txt",
last_error: "connect timed out",
domains: 0,
wildcards: 0,
exceptions: 0,
skipped_regex: 0,
skipped_unsupported: 0,
},
],
};
resolveUpdate!(
new Response(JSON.stringify(snapshot), { status: 202, headers: { "content-type": "application/json" } }),
);
await screen.findByText("loaded");
expect(screen.getByText("fetch_failed")).toBeTruthy();
expect(screen.getByText("connect timed out")).toBeTruthy();
expect(screen.getByText("1200")).toBeTruthy();
expect(screen.getByText("12")).toBeTruthy();
expect(screen.getByText("9")).toBeTruthy();
expect(screen.getByText("4")).toBeTruthy();
expect(screen.getByText("17")).toBeTruthy();
expect(screen.getAllByRole("columnheader", { name: "Skipped unsupported" })).toHaveLength(2);
expect(screen.queryByText(/run .Update now. to fetch status/)).toBeNull();
// The store notifies one flush before the mutation's success state lands.
await screen.findByText(/Update completed/);
await waitFor(() => {
const idle = screen.getByRole("button", { name: "Update now" }) as HTMLButtonElement;
expect(idle.disabled).toBe(false);
});
});
test("update now shows a countdown when rate limited with Retry-After", async () => {
renderBlocklistsRoute();
await screen.findByRole("heading", { name: "Blocklists" });
fireEvent.click(screen.getByRole("button", { name: "Update now" }));
await screen.findByRole("button", { name: "Updating…" });
expect(resolveUpdate).not.toBeNull();
resolveUpdate!(
new Response(JSON.stringify({ error: "rate limited" }), {
status: 429,
headers: { "content-type": "application/json", "Retry-After": "7" },
}),
);
const alert = await screen.findByRole("alert");
expect(alert.textContent).toBe("Rate limited. Try again in 7s.");
});
test("the refresh snapshot outlives the query cache's gcTime", async () => {
vi.useFakeTimers({ shouldAdvanceTime: true });
try {
const { queryClient, unmount } = renderBlocklistsRoute();
await screen.findByRole("heading", { name: "Blocklists" });
fireEvent.click(screen.getByRole("button", { name: "Update now" }));
await screen.findByRole("button", { name: "Updating…" });
resolveUpdate!(
new Response(JSON.stringify(SNAPSHOT), {
status: 202,
headers: { "content-type": "application/json" },
}),
);
await screen.findByText("loaded");
unmount();
// Well past the default 5-minute gcTime: an unsubscribed cache entry is
// collected by now, which is what used to erase the snapshot.
await act(async () => {
await vi.advanceTimersByTimeAsync(6 * 60_000);
});
renderBlocklistsRoute(queryClient);
await screen.findByRole("heading", { name: "Blocklists" });
expect(await screen.findByText("loaded")).toBeTruthy();
expect(screen.queryByText(/run .Update now. to fetch status/)).toBeNull();
} finally {
vi.useRealTimers();
}
});
test("delete asks for confirmation, and cancelling sends no request", async () => {
renderBlocklistsRoute();
await screen.findByRole("heading", { name: "Blocklists" });
fireEvent.click(screen.getAllByRole("button", { name: "Delete" })[0]!);
const dialog = await screen.findByRole("alertdialog");
expect(dialog.textContent).toContain('Delete blocklist "StevenBlack"? Its domains stop being blocked.');
fireEvent.click(screen.getByRole("button", { name: "Cancel" }));
await waitFor(() => expect(screen.queryByRole("alertdialog")).toBeNull());
expect(deleted).toEqual([]);
});
test("confirming the delete dialog issues the DELETE for that source", async () => {
renderBlocklistsRoute();
await screen.findByRole("heading", { name: "Blocklists" });
fireEvent.click(screen.getAllByRole("button", { name: "Delete" })[1]!);
await screen.findByRole("alertdialog");
fireEvent.click(screen.getByRole("button", { name: "Delete" }));
await waitFor(() => expect(deleted).toEqual(["/api/blocklists/2"]));
});
@@ -1,134 +0,0 @@
import * as stylex from "@stylexjs/stylex";
import { formatTime } from "@/lib/format";
import type { SourceStatus } from "@/lib/types";
import { styles as shared } from "@/ui/styles";
import { colors } from "@/ui/tokens.stylex";
function formatAttempt(unixSeconds: number): string {
return unixSeconds === 0 ? "never" : formatTime(unixSeconds);
}
interface SourceStatusSectionProps {
sources: SourceStatus[] | null;
namesById: ReadonlyMap<number, string>;
}
const styles = stylex.create({
section: {
marginTop: "2rem",
},
heading: {
fontSize: "1.125rem",
lineHeight: "1.75rem",
fontWeight: 500,
},
note: {
marginTop: "0.5rem",
color: colors.textMuted,
},
tableWrap: {
marginTop: "0.5rem",
overflowX: "auto",
},
table: {
width: "100%",
minWidth: "max-content",
borderCollapse: "collapse",
fontSize: "0.875rem",
lineHeight: "1.25rem",
},
name: {
fontWeight: 500,
},
url: {
marginTop: "0.125rem",
display: "block",
maxWidth: "16rem",
overflow: "hidden",
textOverflow: "ellipsis",
whiteSpace: "nowrap",
fontSize: "0.75rem",
lineHeight: "1rem",
color: colors.textMuted,
},
/** Green has no token: a loaded source is the only success state in the app. */
loaded: {
color: {
default: "oklch(52.7% 0.154 150.069)",
"@media (prefers-color-scheme: dark)": "oklch(79.2% 0.209 151.711)",
},
},
failed: {
color: colors.danger,
},
absent: {
color: colors.textMuted,
},
});
export default function SourceStatusSection({ sources, namesById }: SourceStatusSectionProps) {
return (
<section {...stylex.props(styles.section)}>
<h2 {...stylex.props(styles.heading)}>Source status</h2>
{sources === null ? (
<p {...stylex.props(styles.note)}>
No status snapshot yet run Update now to fetch status for every enabled source.
</p>
) : sources.length === 0 ? (
<p {...stylex.props(styles.note)}>The last update ran against no enabled sources.</p>
) : (
<div {...stylex.props(styles.tableWrap)}>
<table {...stylex.props(styles.table)}>
<thead>
<tr>
<th {...stylex.props(shared.th)}>Source</th>
<th {...stylex.props(shared.th)}>State</th>
<th {...stylex.props(shared.th)}>Last attempt</th>
<th {...stylex.props(shared.th)}>Last success</th>
<th {...stylex.props(shared.th)}>Domains</th>
<th {...stylex.props(shared.th)}>Wildcards</th>
<th {...stylex.props(shared.th)}>Exceptions</th>
<th {...stylex.props(shared.th)}>Skipped regex</th>
<th {...stylex.props(shared.th)}>Skipped unsupported</th>
<th {...stylex.props(shared.th)}>Last error</th>
</tr>
</thead>
<tbody>
{sources.map((source) => (
<tr key={source.id}>
<td {...stylex.props(shared.td)}>
<span {...stylex.props(styles.name)}>
{namesById.get(source.id) ?? source.url}
</span>
<span {...stylex.props(styles.url)}>{source.url}</span>
</td>
<td {...stylex.props(shared.td)}>
<span {...stylex.props(source.loaded ? styles.loaded : styles.failed)}>
{source.state}
</span>
</td>
<td {...stylex.props(shared.td)}>{formatAttempt(source.last_attempt)}</td>
<td {...stylex.props(shared.td)}>{formatAttempt(source.last_success)}</td>
<td {...stylex.props(shared.td, shared.tabularNums)}>{source.domains}</td>
<td {...stylex.props(shared.td, shared.tabularNums)}>{source.wildcards}</td>
<td {...stylex.props(shared.td, shared.tabularNums)}>{source.exceptions}</td>
<td {...stylex.props(shared.td, shared.tabularNums)}>{source.skipped_regex}</td>
<td {...stylex.props(shared.td, shared.tabularNums)}>
{source.skipped_unsupported}
</td>
<td {...stylex.props(shared.td)}>
{source.last_error === "" ? (
<span {...stylex.props(styles.absent)}></span>
) : (
<span {...stylex.props(styles.failed)}>{source.last_error}</span>
)}
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</section>
);
}
@@ -1,31 +0,0 @@
import { useSyncExternalStore } from "react";
import type { SourceStatus } from "@/lib/types";
// Client UI state, not server state: the snapshot exists only as the 202 body of
// POST /api/blocklists/update and no GET can refetch it. Held here so it outlives
// the query cache's gcTime instead of vanishing from an unsubscribed cache entry.
let snapshot: SourceStatus[] | null = null;
const listeners = new Set<() => void>();
function subscribe(listener: () => void): () => void {
listeners.add(listener);
return () => listeners.delete(listener);
}
function getSnapshot(): SourceStatus[] | null {
return snapshot;
}
export function setRefreshStatus(sources: SourceStatus[]): void {
snapshot = sources;
for (const listener of listeners) listener();
}
export function clearRefreshStatus(): void {
snapshot = null;
for (const listener of listeners) listener();
}
export function useRefreshStatus(): SourceStatus[] | null {
return useSyncExternalStore(subscribe, getSnapshot);
}
@@ -0,0 +1,107 @@
import { fireEvent, screen, waitFor, within } from "@testing-library/react";
import { BASE, MANAGED_FILE, NEVER, renderAt } from "./testFixtures";
afterEach(() => {
vi.unstubAllGlobals();
});
test("a cold deep link fetches the list once and renders the client (D9)", async () => {
const { fetchMock } = renderAt("/clients/1", BASE);
await screen.findByRole("heading", { name: "laptop" });
expect(screen.getByText("192.168.1.10")).toBeTruthy();
const listCalls = fetchMock.mock.calls.filter(([input]) => String(input) === "/api/clients");
expect(listCalls).toHaveLength(1);
});
test("identity carries the name, its provenance and both timestamps", async () => {
renderAt("/clients/2", BASE);
// The unnamed row is the learned one, and Clients is where the marker shows.
const heading = await screen.findByRole("heading", { name: /kids-tablet\.lan/ });
expect(within(heading).getByText("learned")).toBeTruthy();
expect(screen.getByText(/This client appeared from DNS traffic/)).toBeTruthy();
expect(screen.getByText("First seen")).toBeTruthy();
expect(screen.getByText("Last seen")).toBeTruthy();
});
test("a hand-set row reads as edited under database authority", async () => {
renderAt("/clients/1", BASE);
await waitFor(() => expect(screen.getByText(/The name and group were set here/)).toBeTruthy());
});
test("the same row reads as declared under file authority", async () => {
renderAt("/clients/1", { ...BASE, "GET /api/config/status": MANAGED_FILE });
await screen.findByText(/Declared in \/etc\/nxdns\/config\.zon/);
});
test("an unresolved authority names the doubt instead of picking a provenance", async () => {
renderAt("/clients/1", { ...BASE, "GET /api/config/status": NEVER });
await screen.findByText(/Either declared in the configuration file or edited here/);
});
test("an id the list does not contain renders the missing-client state (D9)", async () => {
renderAt("/clients/99", BASE);
await screen.findByRole("heading", { name: "No such client" });
expect(screen.getByText(/no client with id 99/i)).toBeTruthy();
expect(screen.getByRole("link", { name: "← All clients" })).toBeTruthy();
});
test("policy links to the group that filters this client", async () => {
renderAt("/clients/2", BASE);
const link = await screen.findByRole("link", { name: "Group settings" });
expect(link.getAttribute("href")).toBe("/configuration/protection?tab=groups&group=2");
});
test("the Activity affordance is a real link, with bounds minted at interaction time", async () => {
const { router } = renderAt("/clients/1", BASE);
const link = await screen.findByRole("link", { name: /last 24 hours/i });
// A real <a href> is what makes middle-click, copy-link and open-in-new-tab
// work; the bounds must be in that href before the click, not minted by a
// handler the browser never runs on those gestures.
expect(link.tagName).toBe("A");
expect(link.getAttribute("href")).toMatch(/^\/activity\?/);
const before = Math.floor(Date.now() / 1000);
fireEvent.pointerDown(link);
fireEvent.click(link);
const after = Math.floor(Date.now() / 1000);
await waitFor(() => expect(router.state.location.pathname).toBe("/activity"));
const search = router.state.location.search as { mode: string; client: string; since: number; until: number };
expect(search.mode).toBe("history");
expect(search.client).toBe("192.168.1.10");
expect(search.until).toBeGreaterThanOrEqual(before - 1);
expect(search.until).toBeLessThanOrEqual(after + 1);
expect(search.until - search.since).toBe(24 * 60 * 60);
});
test("keyboard activation re-mints the bounds, not the focus that preceded it by hours", async () => {
const { router } = renderAt("/clients/1", BASE);
const link = await screen.findByRole("link", { name: /last 24 hours/i });
// Focus can be hours old by the time Enter lands, so the window it minted is
// stale; the keypress itself is what must be bracketed.
fireEvent.focus(link);
const pressedAt = Date.now() + 3 * 60 * 60 * 1000;
const clock = vi.spyOn(Date, "now").mockReturnValue(pressedAt);
try {
fireEvent.keyDown(link, { key: "Enter" });
// jsdom does not synthesize the click Enter produces on a real anchor.
fireEvent.click(link);
} finally {
clock.mockRestore();
}
await waitFor(() => expect(router.state.location.pathname).toBe("/activity"));
const search = router.state.location.search as { client: string; since: number; until: number };
expect(search.client).toBe("192.168.1.10");
expect(search.until).toBe(Math.floor(pressedAt / 1000));
expect(search.until - search.since).toBe(24 * 60 * 60);
});
@@ -0,0 +1,225 @@
import { useState } from "react";
import { useQuery } from "@tanstack/react-query";
import { Link, useParams } from "@tanstack/react-router";
import * as stylex from "@stylexjs/stylex";
import InlineError from "@/lib/InlineError";
import { formatTime } from "@/lib/format";
import { clientsQuery } from "@/lib/queries";
import { useAuthority } from "@/features/configuration/authority";
import { styles as shared } from "@/ui/styles";
import { colors } from "@/ui/tokens.stylex";
import { ClientDisplayName, provenanceOf } from "./clientIdentity";
/** The Activity window this page offers: the last day, in seconds. */
const ACTIVITY_WINDOW_SECONDS = 24 * 60 * 60;
const nowInSeconds = () => Math.floor(Date.now() / 1000);
const styles = stylex.create({
back: {
fontSize: "0.875rem",
lineHeight: "1.25rem",
color: colors.primaryOnSurface,
textDecorationLine: "none",
},
heading: {
marginTop: "0.5rem",
fontSize: "1.5rem",
lineHeight: "2rem",
fontWeight: 600,
},
address: {
marginTop: "0.25rem",
color: colors.textSecondary,
},
panel: {
marginTop: "1rem",
maxWidth: "48rem",
borderRadius: "0.25rem",
borderWidth: 1,
borderStyle: "solid",
borderColor: colors.border,
backgroundColor: colors.surfaceRaised,
padding: "1rem",
},
facts: {
display: "grid",
gap: "0.5rem 1rem",
gridTemplateColumns: {
default: "auto",
"@media (min-width: 640px)": "max-content 1fr",
},
margin: 0,
fontSize: "0.875rem",
lineHeight: "1.25rem",
},
term: {
color: colors.textMuted,
},
value: {
margin: 0,
},
provenanceDetail: {
marginTop: "0.125rem",
color: colors.textMuted,
},
sectionHeading: {
marginTop: "1.5rem",
fontSize: "1.125rem",
lineHeight: "1.75rem",
fontWeight: 600,
},
prose: {
marginTop: "0.5rem",
maxWidth: "48rem",
fontSize: "0.875rem",
lineHeight: "1.5rem",
},
links: {
marginTop: "0.75rem",
display: "flex",
flexWrap: "wrap",
gap: "1rem",
fontSize: "0.875rem",
lineHeight: "1.25rem",
},
link: {
color: colors.primaryOnSurface,
},
loading: {
marginTop: "1rem",
color: colors.textMuted,
},
});
function BackLink() {
return (
<Link to="/clients" search={{}} {...stylex.props(styles.back, shared.focusRing)}>
All clients
</Link>
);
}
/**
* One client, addressed by the row id `PUT /api/clients/{id}` already uses.
*
* No endpoint answers for a single client, so the list is the source: the route
* loader ensures it, which makes a cold deep link one fetch rather than a
* miss. An id the loaded list does not contain is a row that was deleted or
* never existed — a state this page explains once, with no refetch behind it.
*/
export default function ClientDetailPage() {
const { id } = useParams({ from: "/shell/clients/$id" });
const clientId = Number(id);
const { data, error, isPending, refetch } = useQuery(clientsQuery());
const authority = useAuthority();
// The Activity window is relative to now, and a real link must carry its
// bounds in the href before the click — that is what makes middle-click,
// copy-link and open-in-new-tab work. A page left open would otherwise link
// to yesterday's day, so the window is re-minted when the link is about to be
// used: pointerdown precedes the click, and keydown precedes the click Enter
// synthesizes. Focus re-mints too, but it cannot be the last word — a link can
// hold focus for hours before the keypress. All three are discrete events, so
// the href is fresh by the time navigation reads it.
const [activityUntil, setActivityUntil] = useState(nowInSeconds);
const freshenActivityWindow = () => setActivityUntil(nowInSeconds());
if (isPending) {
return (
<p {...stylex.props(styles.loading, shared.pulse)} role="status">
Loading client
</p>
);
}
if (data === undefined) {
return (
<section>
<BackLink />
<InlineError error={error} onRetry={() => void refetch()} />
</section>
);
}
const client = data.find((row) => row.id === clientId);
if (client === undefined) {
return (
<section>
<BackLink />
<h1 {...stylex.props(styles.heading)}>No such client</h1>
<p {...stylex.props(styles.prose)}>
nxdns has no client with id {id}. It was deleted, or the link was to a row that never existed. A
device that is still on the network reappears in the list on its next DNS query.
</p>
</section>
);
}
const provenance = provenanceOf(client, authority);
return (
<section>
<BackLink />
<h1 {...stylex.props(styles.heading)}>
<ClientDisplayName client={client} />
</h1>
<p {...stylex.props(styles.address, shared.mono)}>{client.ip}</p>
<div {...stylex.props(styles.panel)}>
<dl {...stylex.props(styles.facts)}>
<dt {...stylex.props(styles.term)}>Name</dt>
<dd {...stylex.props(styles.value)}>
<ClientDisplayName client={client} />
</dd>
<dt {...stylex.props(styles.term)}>Provenance</dt>
<dd {...stylex.props(styles.value)}>
{provenance.label}
<span {...stylex.props(styles.provenanceDetail)}> {provenance.detail}</span>
</dd>
<dt {...stylex.props(styles.term)}>First seen</dt>
<dd {...stylex.props(styles.value)}>{formatTime(client.first_seen)}</dd>
<dt {...stylex.props(styles.term)}>Last seen</dt>
<dd {...stylex.props(styles.value)}>{formatTime(client.last_seen)}</dd>
</dl>
</div>
<h2 {...stylex.props(styles.sectionHeading)}>Policy</h2>
<p {...stylex.props(styles.prose)}>
Filtering for this client follows the <strong>{client.group}</strong> group: its safe search setting,
its blocklist sources and its rules.
</p>
<p {...stylex.props(styles.links)}>
<Link
to="/configuration/protection"
search={{ tab: "groups", group: client.group_id }}
{...stylex.props(styles.link, shared.focusRing)}
>
Group settings
</Link>
</p>
<h2 {...stylex.props(styles.sectionHeading)}>Activity</h2>
<p {...stylex.props(styles.links)}>
<Link
to="/activity"
search={{
mode: "history",
client: client.ip,
since: activityUntil - ACTIVITY_WINDOW_SECONDS,
until: activityUntil,
domain: undefined,
blocked: undefined,
}}
onPointerDown={freshenActivityWindow}
onFocus={freshenActivityWindow}
onKeyDown={(event) => {
if (event.key === "Enter") freshenActivityWindow();
}}
{...stylex.props(styles.link, shared.focusRing)}
>
Queries from this client, last 24 hours
</Link>
</p>
</section>
);
}
+36 -14
View File
@@ -4,10 +4,12 @@ import * as stylex from "@stylexjs/stylex";
import { clientUpdateMutation } from "@/lib/queries";
import type { Client, Group } from "@/lib/types";
import InlineError from "@/lib/InlineError";
import ConfigLockIndicator from "@/features/configuration/ConfigLockIndicator";
import { useReadOnlyConfig } from "@/features/configuration/authority";
import Dialog from "@/ui/Dialog";
import Select from "@/ui/Select";
import { styles as shared } from "@/ui/styles";
import { READ_ONLY_HINT, useReadOnlyConfig } from "@/features/settings/authority";
import { colors } from "@/ui/tokens.stylex";
interface Props {
client: Client;
@@ -39,20 +41,30 @@ const styles = stylex.create({
},
actions: {
display: "flex",
flexWrap: "wrap",
alignItems: "center",
justifyContent: "flex-end",
gap: "0.5rem",
},
lockNote: {
marginRight: "auto",
fontSize: "0.75rem",
lineHeight: "1rem",
color: colors.textMuted,
},
});
export default function ClientEditDialog({ client, groups, onClose }: Props) {
const queryClient = useQueryClient();
const mutation = useMutation(clientUpdateMutation(queryClient));
const readOnly = useReadOnlyConfig();
// Adopting the learned name as a typed one is the natural gesture, but only
// where the save can land: under file authority the PUT answers 403, and the
// file's declared name is the one that wins.
const [name, setName] = useState(client.name === "" && !readOnly ? client.learned_name : client.name);
// Adopting the learned name as a typed one is the natural gesture.
const [name, setName] = useState(client.name === "" ? client.learned_name : client.name);
const [groupId, setGroupId] = useState(client.group_id);
// The dialog opens only where the save can land, but authority is polled and
// can turn under an open dialog. So the save path consults it on every render
// rather than trusting the state that was true when the dialog opened; the
// draft stays on screen, locked, instead of vanishing mid-edit.
const readOnly = useReadOnlyConfig();
return (
<Dialog label={`Edit client ${client.ip}`} isOpen onClose={onClose}>
@@ -61,6 +73,9 @@ export default function ClientEditDialog({ client, groups, onClose }: Props) {
{...stylex.props(styles.form)}
onSubmit={(event) => {
event.preventDefault();
// Enter in the name field submits without the Save button, so
// the lock lives here too, not only in what is rendered.
if (readOnly) return;
mutation.mutate(
{ id: client.id, edit: { name: name.trim(), group_id: groupId } },
{ onSuccess: onClose },
@@ -86,17 +101,24 @@ export default function ClientEditDialog({ client, groups, onClose }: Props) {
/>
<InlineError error={mutation.error} />
<div {...stylex.props(styles.actions)}>
{readOnly && (
<span {...stylex.props(styles.lockNote)}>
This edit can no longer be saved.
<ConfigLockIndicator />
</span>
)}
<button type="button" onClick={onClose} {...stylex.props(shared.button, shared.focusRing)}>
Cancel
</button>
<button
type="submit"
disabled={mutation.isPending || readOnly}
title={readOnly ? READ_ONLY_HINT : undefined}
{...stylex.props(shared.primaryButton, shared.focusRing)}
>
Save
</button>
{!readOnly && (
<button
type="submit"
disabled={mutation.isPending}
{...stylex.props(shared.primaryButton, shared.focusRing)}
>
Save
</button>
)}
</div>
</form>
</Dialog>
+218 -97
View File
@@ -1,121 +1,78 @@
import { fireEvent, render, screen, within } from "@testing-library/react";
import { QueryClientProvider } from "@tanstack/react-query";
import { RouterProvider, createMemoryHistory } from "@tanstack/react-router";
import { AuthProvider } from "@/auth/store";
import { createQueryClient } from "@/lib/queryClient";
import { createAppRouter } from "@/routes";
import { fireEvent, render, screen, waitFor, within } from "@testing-library/react";
import { ClientName, type ClientNames } from "./clientNames";
import { BASE, MANAGED_FILE, NEVER, renderClientsPage, setConfigStatus } from "./testFixtures";
const GROUPS = {
groups: [
{ id: 1, name: "default", safe_search: false },
{ id: 2, name: "kids", safe_search: true },
],
};
const CLIENTS = {
clients: [
{
id: 1,
ip: "192.168.1.10",
name: "laptop",
learned_name: "laptop-1.lan",
group_id: 1,
group: "default",
hand_edited: true,
first_seen: 1700000000,
last_seen: 1700003600,
},
{
id: 2,
ip: "192.168.1.11",
name: "",
learned_name: "kids-tablet.lan",
group_id: 2,
group: "kids",
hand_edited: false,
first_seen: 1700000000,
last_seen: 1700007200,
},
],
};
const PREFIXES = {
client_prefixes: [{ id: 1, prefix: "192.168.1.0/24", group_id: 2, group: "kids", priority: 100 }],
};
const VERSION = { version: "0.0.0-test", git_commit: "0000000", zig_version: "0.16.0", uptime_seconds: 1 };
function stubFetch(map: Record<string, unknown>) {
vi.stubGlobal(
"fetch",
vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
const key = `${init?.method ?? "GET"} ${String(input)}`;
const payload = map[key];
if (payload === undefined) {
return new Response(JSON.stringify({ error: `not stubbed: ${key}` }), { status: 404 });
}
return new Response(JSON.stringify(payload), {
status: 200,
headers: { "content-type": "application/json" },
});
}),
);
function clientRow(ip: string): HTMLElement {
const row = screen.getByText(ip).closest("tr");
if (row === null) throw new Error(`no client row for ${ip}`);
return row;
}
async function renderClientsPage(map: Record<string, unknown>) {
stubFetch(map);
const queryClient = createQueryClient();
const router = createAppRouter(createMemoryHistory({ initialEntries: ["/clients"] }), queryClient);
render(
<AuthProvider>
<QueryClientProvider client={queryClient}>
<RouterProvider router={router} />
</QueryClientProvider>
</AuthProvider>,
);
await screen.findByRole("heading", { name: "Clients" });
function assignmentsSection(): HTMLElement {
const heading = screen.getByRole("heading", { name: /Network assignments/ });
const section = heading.closest("section");
if (section === null) throw new Error("no network assignments section");
return section;
}
const BASE = {
"GET /api/clients": CLIENTS,
"GET /api/client-prefixes": PREFIXES,
"GET /api/groups": GROUPS,
"GET /api/version": VERSION,
};
/**
* Editing a client writes configuration, so the affordance is absent until the
* status query says the database owns it — never disabled, never assumed.
*/
async function unlockedEdit(index: number): Promise<HTMLButtonElement> {
const buttons = await screen.findAllByRole("button", { name: "Edit" });
return buttons[index] as HTMLButtonElement;
}
afterEach(() => {
vi.unstubAllGlobals();
});
test("renders the client table with group names and one hand-edited badge", async () => {
await renderClientsPage(BASE);
test("renders the identity-first table: address, name, group, first and last seen", async () => {
await renderClientsPage();
const headers = screen.getAllByRole("columnheader").map((cell) => cell.textContent);
expect(headers).toEqual(["Address", "Name", "Group", "First seen", "Last seen", "Actions"]);
expect(screen.getByText("192.168.1.10")).toBeTruthy();
expect(screen.getByText("192.168.1.11")).toBeTruthy();
expect(screen.getByText("laptop")).toBeTruthy();
expect(screen.getAllByText("edited")).toHaveLength(1);
expect(screen.getAllByRole("cell", { name: "kids" })).toHaveLength(1);
});
test("a named row shows the typed name and hides the learned one", async () => {
await renderClientsPage(BASE);
await renderClientsPage();
expect(screen.getByText("laptop")).toBeTruthy();
expect(screen.queryByText("laptop-1.lan")).toBeNull();
});
test("an unnamed row shows the learned name with the learned affordance", async () => {
await renderClientsPage(BASE);
test("an unnamed row shows the learned name with the learned marker", async () => {
await renderClientsPage();
// The cell holds the learned name followed by the tag, so the match is on
// The cell holds the learned name followed by the marker, so the match is on
// the containing span rather than on a bare text node.
const learned = screen.getByText(
(content, element) => element?.tagName === "SPAN" && content.startsWith("kids-tablet.lan"),
);
// The affordance is text, not colour, so a screen reader announces it too.
// The marker is text, not colour, so a screen reader announces it too.
expect(within(learned).getByText("learned")).toBeTruthy();
});
test("the learned marker is a Clients-page affordance: query tables render the same name without it", () => {
const names: ClientNames = new Map([["192.168.1.11", { name: "", learned_name: "kids-tablet.lan" }]]);
render(<ClientName ip="192.168.1.11" names={names} />);
expect(screen.getByText("kids-tablet.lan")).toBeTruthy();
expect(screen.queryByText("learned")).toBeNull();
});
test("the address links to the client's detail page", async () => {
await renderClientsPage();
const link = within(clientRow("192.168.1.10")).getByRole("link", { name: "192.168.1.10" });
expect(link.getAttribute("href")).toBe("/clients/1");
});
test("shows the DNS-activity empty state when there are no clients", async () => {
await renderClientsPage({ ...BASE, "GET /api/clients": { clients: [] } });
@@ -124,9 +81,9 @@ test("shows the DNS-activity empty state when there are no clients", async () =>
});
test("edit opens a dialog seeded with the client's name and group", async () => {
await renderClientsPage(BASE);
await renderClientsPage();
fireEvent.click(screen.getAllByRole("button", { name: "Edit" })[0]!);
fireEvent.click(await unlockedEdit(0));
// The dialog portals out of the table, so every field query is scoped to it.
const dialog = within(await screen.findByRole("dialog", { name: "Edit client 192.168.1.10" }));
expect((dialog.getByLabelText("Name") as HTMLInputElement).value).toBe("laptop");
@@ -135,9 +92,9 @@ test("edit opens a dialog seeded with the client's name and group", async () =>
});
test("the group picker offers every group and reports the choice", async () => {
await renderClientsPage(BASE);
await renderClientsPage();
fireEvent.click(screen.getAllByRole("button", { name: "Edit" })[0]!);
fireEvent.click(await unlockedEdit(0));
const dialog = within(await screen.findByRole("dialog", { name: "Edit client 192.168.1.10" }));
fireEvent.click(dialog.getByRole("button", { name: /Group$/ }));
@@ -148,14 +105,178 @@ test("the group picker offers every group and reports the choice", async () => {
expect(screen.getByRole("button", { name: /Group$/ }).textContent).toContain("kids");
});
test("prefix editor starts clean and dirties on add", async () => {
await renderClientsPage(BASE);
test("network assignments start clean and dirty on add", async () => {
await renderClientsPage();
expect((screen.getByLabelText("Prefix 1") as HTMLInputElement).value).toBe("192.168.1.0/24");
const save = screen.getByRole("button", { name: "Save prefixes" }) as HTMLButtonElement;
const range = (await screen.findByLabelText("Range 1")) as HTMLInputElement;
expect(range.value).toBe("192.168.1.0/24");
const save = screen.getByRole("button", { name: "Save assignments" }) as HTMLButtonElement;
expect(save.disabled).toBe(true);
fireEvent.click(screen.getByRole("button", { name: "Add prefix" }));
fireEvent.click(screen.getByRole("button", { name: "Add range" }));
expect(save.disabled).toBe(false);
expect((screen.getByLabelText("Prefix 2") as HTMLInputElement).value).toBe("");
expect((screen.getByLabelText("Range 2") as HTMLInputElement).value).toBe("");
});
test("?group= filters the list to that group", async () => {
const { router } = await renderClientsPage();
await router.navigate({ to: "/clients", search: { group: 2 } });
await waitFor(() => expect(screen.queryByText("192.168.1.10")).toBeNull());
expect(screen.getByText("192.168.1.11")).toBeTruthy();
expect(screen.getByText("Showing clients in kids.")).toBeTruthy();
});
test("an unknown group id filters to nothing and offers a way out", async () => {
const { router } = await renderClientsPage();
await router.navigate({ to: "/clients", search: { group: 999 } });
await screen.findByText("No group with id 999 exists.");
expect(screen.getByText("No clients match this filter.")).toBeTruthy();
expect(screen.queryByRole("table")).toBeNull();
fireEvent.click(screen.getByRole("link", { name: "Clear filter" }));
await waitFor(() => expect(screen.getByText("192.168.1.10")).toBeTruthy());
expect(router.state.location.search).toEqual({});
});
test("file mode drops every edit affordance and keeps the observed delete live (R2-4)", async () => {
await renderClientsPage({ ...BASE, "GET /api/config/status": MANAGED_FILE });
await screen.findAllByLabelText(/Managed by \/etc\/nxdns\/config\.zon/);
expect(screen.queryAllByRole("button", { name: "Edit" })).toEqual([]);
const declared = clientRow("192.168.1.10");
const observed = clientRow("192.168.1.11");
expect((within(declared).getByRole("button", { name: "Delete" }) as HTMLButtonElement).disabled).toBe(true);
expect((within(observed).getByRole("button", { name: "Delete" }) as HTMLButtonElement).disabled).toBe(false);
});
test("file mode renders network assignments with no mutation control at all (R2-4)", async () => {
await renderClientsPage({ ...BASE, "GET /api/config/status": MANAGED_FILE });
const section = await waitFor(() => {
const found = assignmentsSection();
if (found.querySelector("table") === null) throw new Error("still editing");
return found;
});
expect(within(section).getByText("192.168.1.0/24")).toBeTruthy();
expect(
section.querySelectorAll(
"input, textarea, select, [role='combobox'], [role='checkbox'], [contenteditable], button",
),
).toHaveLength(0);
});
test("a failed config status exposes no configuration mutation, and still deletes an observed client (R3-4)", async () => {
await renderClientsPage({ ...BASE, "GET /api/config/status": undefined });
await screen.findAllByLabelText(/Configuration status unavailable/);
expect(screen.queryAllByRole("button", { name: "Edit" })).toEqual([]);
expect(screen.queryByRole("button", { name: "Save assignments" })).toBeNull();
expect(within(assignmentsSection()).getByText(/Configuration status unavailable/)).toBeTruthy();
const observed = clientRow("192.168.1.11");
expect((within(observed).getByRole("button", { name: "Delete" }) as HTMLButtonElement).disabled).toBe(false);
const declared = clientRow("192.168.1.10");
expect((within(declared).getByRole("button", { name: "Delete" }) as HTMLButtonElement).disabled).toBe(true);
});
// The status query polls, so authority can turn while a dialog or a delete
// confirmation is already open. `undefined` is the failed status: the fetch stub
// answers 404 for a key it does not hold.
//
// Both statuses lock the declared delete, but only file authority proves the
// file declares the row; the anchors keep the two sentences apart.
const DECLARED_NOTE = /^This client is declared in the configuration file/;
const UNKNOWN_NOTE = /^nxdns cannot say whether this client is declared/;
describe.each([
["file authority", MANAGED_FILE, DECLARED_NOTE, UNKNOWN_NOTE],
["a failed status", undefined, UNKNOWN_NOTE, DECLARED_NOTE],
])("authority turning to %s under an open affordance", (_label, status, lockNote, otherNote) => {
test("locks the open edit dialog's save path and leaves cancel working", async () => {
const map = { ...BASE };
const { queryClient } = await renderClientsPage(map);
fireEvent.click(await unlockedEdit(0));
expect(
within(await screen.findByRole("dialog", { name: "Edit client 192.168.1.10" })).getByRole("button", {
name: "Save",
}),
).toBeTruthy();
await setConfigStatus(map, queryClient, status);
// The draft survives; only the save path goes, and it says why.
const dialog = screen.getByRole("dialog", { name: "Edit client 192.168.1.10" });
expect(within(dialog).queryByRole("button", { name: "Save" })).toBeNull();
expect((within(dialog).getByLabelText("Name") as HTMLInputElement).value).toBe("laptop");
expect(within(dialog).getByText(/can no longer be saved/)).toBeTruthy();
expect(within(dialog).getByLabelText(/^Locked\./)).toBeTruthy();
fireEvent.click(within(dialog).getByRole("button", { name: "Cancel" }));
await waitFor(() => expect(screen.queryByRole("dialog")).toBeNull());
});
test("locks an open declared-client delete confirmation and leaves cancel working", async () => {
const map = { ...BASE };
const { queryClient, fetchMock } = await renderClientsPage(map);
// The Edit affordance appearing is the proof authority resolved to
// database; the transition under test starts from there.
await unlockedEdit(0);
const declared = clientRow("192.168.1.10");
fireEvent.click(within(declared).getByRole("button", { name: "Delete" }));
expect(within(clientRow("192.168.1.10")).getByRole("button", { name: "Confirm delete" })).toBeTruthy();
await setConfigStatus(map, queryClient, status);
const confirming = clientRow("192.168.1.10");
expect(within(confirming).queryByRole("button", { name: "Confirm delete" })).toBeNull();
expect(within(confirming).getByText(lockNote)).toBeTruthy();
expect(within(confirming).queryByText(otherNote)).toBeNull();
expect(within(confirming).getByLabelText(/^Locked\./)).toBeTruthy();
fireEvent.click(within(confirming).getByRole("button", { name: "Cancel" }));
await waitFor(() =>
expect(within(clientRow("192.168.1.10")).getByRole("button", { name: "Delete" })).toBeTruthy(),
);
expect(fetchMock.mock.calls.filter(([, init]) => init?.method === "DELETE")).toEqual([]);
});
test("keeps an open observed-client delete confirmation live (R3-4)", async () => {
const map = { ...BASE, "DELETE /api/clients/2": {} };
const { queryClient, fetchMock } = await renderClientsPage(map);
// The Edit affordance appearing is the proof authority resolved to
// database; the transition under test starts from there.
await unlockedEdit(0);
const observed = clientRow("192.168.1.11");
fireEvent.click(within(observed).getByRole("button", { name: "Delete" }));
await setConfigStatus(map, queryClient, status);
fireEvent.click(within(clientRow("192.168.1.11")).getByRole("button", { name: "Confirm delete" }));
await waitFor(() =>
expect(
fetchMock.mock.calls.filter(
([input, init]) => init?.method === "DELETE" && String(input).endsWith("/2"),
),
).toHaveLength(1),
);
});
});
test("a pending config status holds the same line as a failed one (R3-4)", async () => {
// The status request never settles, so authority stays pending for the whole
// test: nothing configuration owns may be offered on that guess.
await renderClientsPage({ ...BASE, "GET /api/config/status": NEVER });
await screen.findAllByLabelText(/Checking which configuration source/);
expect(screen.queryAllByRole("button", { name: "Edit" })).toEqual([]);
expect(screen.queryByRole("button", { name: "Save assignments" })).toBeNull();
expect(within(assignmentsSection()).getByText(/Checking which configuration source/)).toBeTruthy();
const observed = clientRow("192.168.1.11");
expect((within(observed).getByRole("button", { name: "Delete" }) as HTMLButtonElement).disabled).toBe(false);
});
+105 -67
View File
@@ -1,22 +1,35 @@
import { useState } from "react";
import { useMutation, useQueryClient, useSuspenseQuery } from "@tanstack/react-query";
import { Link, useSearch } from "@tanstack/react-router";
import * as stylex from "@stylexjs/stylex";
import { clientDeleteMutation, clientPrefixesQuery, clientsQuery, groupsQuery } from "@/lib/queries";
import { formatTime } from "@/lib/format";
import type { Client } from "@/lib/types";
import type { Client, Group } from "@/lib/types";
import ClientEditDialog from "./ClientEditDialog";
import PrefixesEditor from "./PrefixesEditor";
import NetworkAssignments from "./NetworkAssignments";
import { ClientDisplayName } from "./clientIdentity";
import InlineError from "@/lib/InlineError";
import ConfigLockIndicator from "@/features/configuration/ConfigLockIndicator";
import { useAuthority, useReadOnlyConfig, type Authority } from "@/features/configuration/authority";
import { styles as shared } from "@/ui/styles";
import { colors } from "@/ui/tokens.stylex";
import { READ_ONLY_HINT, useReadOnlyConfig } from "@/features/settings/authority";
/**
* Deleting an observed row discards runtime state the file never declared, so
* it stays live under file authority; deleting a hand-edited row contradicts
* the file and is the one client DELETE the server answers 403 (ruling 7).
* it stays live under every authority; deleting a declared row contradicts the
* file and is the one client DELETE the server answers 403 (ruling 7).
*
* The lock fails closed, so it also holds while authority is pending or
* unreachable. There the file is a possibility and not a fact — `hand_edited`
* alone cannot say which operator surface set the row — so the sentence names
* the doubt rather than asserting a declaration, the way `provenanceOf` does.
*/
const DECLARED_CLIENT_NOTE = "This client is declared in the configuration file; remove it there and restart.";
function declaredDeleteNote(authority: Authority): string {
if (authority.state === "resolved") {
return "This client is declared in the configuration file; remove it there and restart.";
}
return "nxdns cannot say whether this client is declared in the configuration file until it reports its configuration status, so deleting it stays locked.";
}
const styles = stylex.create({
heading: {
@@ -28,6 +41,15 @@ const styles = stylex.create({
marginTop: "1rem",
color: colors.textMuted,
},
filterBar: {
marginTop: "1rem",
display: "flex",
flexWrap: "wrap",
alignItems: "center",
gap: "0.75rem",
fontSize: "0.875rem",
lineHeight: "1.25rem",
},
table: {
width: "100%",
minWidth: "48rem",
@@ -53,19 +75,9 @@ const styles = stylex.create({
right: {
textAlign: "right",
},
dash: {
color: colors.textMuted,
},
badge: {
marginLeft: "0.5rem",
borderRadius: "0.25rem",
backgroundColor: colors.primary,
paddingInline: "0.375rem",
paddingBlock: "0.125rem",
fontSize: "0.75rem",
lineHeight: "1rem",
fontWeight: 500,
color: colors.primaryText,
addressLink: {
color: colors.primaryOnSurface,
textDecorationLine: "none",
},
confirmGroup: {
display: "inline-flex",
@@ -76,6 +88,7 @@ const styles = stylex.create({
},
actionGroup: {
display: "inline-flex",
alignItems: "center",
gap: "0.5rem",
},
note: {
@@ -89,36 +102,54 @@ const styles = stylex.create({
dimWhenDisabled: {
opacity: { default: 1, ":disabled": 0.5 },
},
/**
* The accessible name of the actions column, kept out of the visual table
* without leaving the accessibility tree.
*/
});
export default function ClientsPage() {
const { data: clients } = useSuspenseQuery(clientsQuery());
const { data: prefixes } = useSuspenseQuery(clientPrefixesQuery());
const { data: groups } = useSuspenseQuery(groupsQuery());
const { group } = useSearch({ from: "/shell/clients" });
const queryClient = useQueryClient();
const deleteMutation = useMutation(clientDeleteMutation(queryClient));
const [editing, setEditing] = useState<Client | null>(null);
const [confirmingId, setConfirmingId] = useState<number | null>(null);
const readOnly = useReadOnlyConfig();
const authority = useAuthority();
// A well-formed id the group list does not contain is a link to a group that
// has since been deleted. It filters to nothing, which is the truth, and the
// notice says so rather than quietly showing every client.
const filterGroup: Group | undefined = group === undefined ? undefined : groups.find((row) => row.id === group);
const rows = group === undefined ? clients : clients.filter((client) => client.group_id === group);
return (
<section>
<h1 {...stylex.props(styles.heading)}>Clients</h1>
{group !== undefined && (
<div {...stylex.props(styles.filterBar)}>
<span>
{filterGroup !== undefined
? `Showing clients in ${filterGroup.name}.`
: `No group with id ${group} exists.`}
</span>
<Link to="/clients" search={{}} {...stylex.props(shared.linkButton, shared.focusRing)}>
Clear filter
</Link>
</div>
)}
{clients.length === 0 ? (
<p {...stylex.props(styles.empty)}>
No clients yet. Rows appear automatically as devices on the network make DNS queries there is
nothing to create by hand.
</p>
) : rows.length === 0 ? (
<p {...stylex.props(styles.empty)}>No clients match this filter.</p>
) : (
<div {...stylex.props(shared.tableWrap)}>
<table {...stylex.props(styles.table)}>
<thead>
<tr {...stylex.props(styles.headRow)}>
<th {...stylex.props(styles.cell)}>IP</th>
<th {...stylex.props(styles.cell)}>Address</th>
<th {...stylex.props(styles.cell)}>Name</th>
<th {...stylex.props(styles.cell)}>Group</th>
<th {...stylex.props(styles.cell)}>First seen</th>
@@ -129,21 +160,19 @@ export default function ClientsPage() {
</tr>
</thead>
<tbody>
{clients.map((client) => (
{rows.map((client) => (
<tr key={client.id} {...stylex.props(styles.bodyRow)}>
<td {...stylex.props(styles.cell, shared.mono)}>{client.ip}</td>
<td {...stylex.props(styles.cell, shared.mono)}>
<Link
to="/clients/$id"
params={{ id: String(client.id) }}
{...stylex.props(styles.addressLink, shared.focusRing)}
>
{client.ip}
</Link>
</td>
<td {...stylex.props(styles.cell)}>
{client.name !== "" ? (
client.name
) : client.learned_name !== "" ? (
<span {...stylex.props(shared.learnedName)}>
{client.learned_name}
<span {...stylex.props(shared.learnedTag)}>learned</span>
</span>
) : (
<span {...stylex.props(styles.dash)}></span>
)}
{client.hand_edited && <span {...stylex.props(styles.badge)}>edited</span>}
<ClientDisplayName client={client} />
</td>
<td {...stylex.props(styles.cell)}>{client.group}</td>
<td {...stylex.props(styles.cell)}>{formatTime(client.first_seen)}</td>
@@ -151,23 +180,32 @@ export default function ClientsPage() {
<td {...stylex.props(styles.cell, styles.right)}>
{confirmingId === client.id ? (
<span {...stylex.props(styles.confirmGroup)}>
{/* Authority is polled, so it can turn while a confirmation
sits open. The confirm path reads it on every render
rather than trusting the state that opened it. */}
<span {...stylex.props(styles.note)}>
Deleted clients re-materialize on their next DNS query.
{readOnly && client.hand_edited
? declaredDeleteNote(authority)
: "Deleted clients re-materialize on their next DNS query."}
</span>
<button
type="button"
onClick={() => {
setConfirmingId(null);
deleteMutation.mutate(client.id);
}}
{...stylex.props(
shared.smallButton,
styles.dangerText,
shared.focusRing,
)}
>
Confirm delete
</button>
{readOnly && client.hand_edited ? (
<ConfigLockIndicator />
) : (
<button
type="button"
onClick={() => {
setConfirmingId(null);
deleteMutation.mutate(client.id);
}}
{...stylex.props(
shared.smallButton,
styles.dangerText,
shared.focusRing,
)}
>
Confirm delete
</button>
)}
<button
type="button"
onClick={() => setConfirmingId(null)}
@@ -178,26 +216,26 @@ export default function ClientsPage() {
</span>
) : (
<span {...stylex.props(styles.actionGroup)}>
<button
type="button"
onClick={() => setEditing(client)}
disabled={readOnly}
title={readOnly ? READ_ONLY_HINT : undefined}
{...stylex.props(
shared.smallButton,
styles.dimWhenDisabled,
shared.focusRing,
)}
>
Edit
</button>
{/* Naming a client writes configuration, so the affordance is
absent — not disabled — wherever the write cannot land. */}
{readOnly ? (
<ConfigLockIndicator />
) : (
<button
type="button"
onClick={() => setEditing(client)}
{...stylex.props(shared.smallButton, shared.focusRing)}
>
Edit
</button>
)}
<button
type="button"
onClick={() => setConfirmingId(client.id)}
disabled={readOnly && client.hand_edited}
title={
readOnly && client.hand_edited
? DECLARED_CLIENT_NOTE
? declaredDeleteNote(authority)
: undefined
}
{...stylex.props(
@@ -220,7 +258,7 @@ export default function ClientsPage() {
)}
<InlineError error={deleteMutation.error} />
{editing !== null && <ClientEditDialog client={editing} groups={groups} onClose={() => setEditing(null)} />}
<PrefixesEditor prefixes={prefixes} groups={groups} />
<NetworkAssignments prefixes={prefixes} groups={groups} />
</section>
);
}
@@ -6,10 +6,10 @@ import type { ClientPrefix, Group } from "@/lib/types";
import { defaultGroupId } from "@/lib/defaultGroup";
import { firstProblem, initPrefixEditor, isDirty, prefixEditorReducer, toInputs } from "./prefixEditor";
import InlineError from "@/lib/InlineError";
import AuthorityGate from "@/features/configuration/AuthorityGate";
import Select from "@/ui/Select";
import { styles as shared } from "@/ui/styles";
import { colors } from "@/ui/tokens.stylex";
import { READ_ONLY_HINT, useReadOnlyConfig } from "@/features/settings/authority";
interface Props {
prefixes: ClientPrefix[];
@@ -25,6 +25,13 @@ const styles = stylex.create({
lineHeight: "1.75rem",
fontWeight: 600,
},
headingKey: {
marginLeft: "0.5rem",
fontSize: "0.75rem",
lineHeight: "1rem",
fontWeight: 400,
color: colors.textMuted,
},
intro: {
marginTop: "0.25rem",
fontSize: "0.875rem",
@@ -80,16 +87,84 @@ const styles = stylex.create({
gap: "0.5rem",
marginTop: "1rem",
},
table: {
width: "100%",
minWidth: "max-content",
borderCollapse: "collapse",
fontSize: "0.875rem",
lineHeight: "1.25rem",
},
});
export default function PrefixesEditor({ prefixes, groups }: Props) {
/**
* Address ranges that assign a group to every device inside them.
*
* The section is a configuration rendering, so it goes through the authority
* gate: the editor exists only where a save can land, and file authority gets
* the assignments as a table rather than a form nobody may submit.
*/
export default function NetworkAssignments({ prefixes, groups }: Props) {
return (
<section {...stylex.props(styles.section)}>
<h2 {...stylex.props(styles.heading)}>
Network assignments
<code {...stylex.props(shared.mono, styles.headingKey)}>client_prefixes</code>
</h2>
<p {...stylex.props(styles.intro)}>
An address range assigns its group to every device inside it, for devices with no row of their own. The
highest priority match wins.
</p>
<AuthorityGate>
{(status) =>
status.authority === "database" ? (
<AssignmentsEditor prefixes={prefixes} groups={groups} />
) : (
<AssignmentsTable prefixes={prefixes} />
)
}
</AuthorityGate>
</section>
);
}
function AssignmentsTable({ prefixes }: { prefixes: ClientPrefix[] }) {
if (prefixes.length === 0) return <p {...stylex.props(styles.empty)}>The file declares no network assignments.</p>;
return (
<div {...stylex.props(shared.tableWrap)}>
<table {...stylex.props(styles.table)}>
<thead>
<tr>
<th {...stylex.props(shared.th)}>Range</th>
<th {...stylex.props(shared.th)}>Group</th>
<th {...stylex.props(shared.th)}>Priority</th>
</tr>
</thead>
<tbody>
{prefixes.map((prefix) => (
<tr key={prefix.id}>
<td {...stylex.props(shared.td, shared.mono)}>{prefix.prefix}</td>
<td {...stylex.props(shared.td)}>{prefix.group}</td>
<td {...stylex.props(shared.td, shared.tabularNums)}>{prefix.priority}</td>
</tr>
))}
</tbody>
</table>
</div>
);
}
/**
* The list is saved as a whole, so the editor holds every row and the PUT
* replaces the set. Reached only under resolved database authority: the gate
* above owns that decision, and no control here consults it a second time.
*/
function AssignmentsEditor({ prefixes, groups }: Props) {
const queryClient = useQueryClient();
const mutation = useMutation(clientPrefixesPutMutation(queryClient));
const [state, dispatch] = useReducer(prefixEditorReducer, prefixes, initPrefixEditor);
const [validation, setValidation] = useState<string | null>(null);
const dirty = isDirty(state);
const fallbackGroupId = defaultGroupId(groups);
const readOnly = useReadOnlyConfig();
const groupOptions = groups.map((group) => ({ value: String(group.id), label: group.name }));
const save = () => {
@@ -102,21 +177,16 @@ export default function PrefixesEditor({ prefixes, groups }: Props) {
};
return (
<section {...stylex.props(styles.section)}>
<h2 {...stylex.props(styles.heading)}>Client prefixes</h2>
<p {...stylex.props(styles.intro)}>
Prefixes assign a group to whole address ranges. The list is saved as a whole; the highest priority
match wins.
</p>
<>
{state.rows.length === 0 ? (
<p {...stylex.props(styles.empty)}>No prefixes configured.</p>
<p {...stylex.props(styles.empty)}>No network assignments configured.</p>
) : (
<ul {...stylex.props(styles.rows)}>
{state.rows.map((row, index) => (
<li key={index} {...stylex.props(styles.row)}>
<input
type="text"
aria-label={`Prefix ${index + 1}`}
aria-label={`Range ${index + 1}`}
placeholder="192.168.1.0/24"
value={row.prefix}
onChange={(event) =>
@@ -125,7 +195,7 @@ export default function PrefixesEditor({ prefixes, groups }: Props) {
{...stylex.props(shared.smallInput, styles.prefixInput, shared.focusRing)}
/>
<Select
aria-label={`Group for prefix ${index + 1}`}
aria-label={`Group for range ${index + 1}`}
variant="inline"
value={String(row.group_id)}
onChange={(value) =>
@@ -136,7 +206,7 @@ export default function PrefixesEditor({ prefixes, groups }: Props) {
<input
type="text"
inputMode="numeric"
aria-label={`Priority for prefix ${index + 1}`}
aria-label={`Priority for range ${index + 1}`}
placeholder="100"
value={row.priority}
onChange={(event) =>
@@ -167,16 +237,15 @@ export default function PrefixesEditor({ prefixes, groups }: Props) {
onClick={() => dispatch({ type: "add", groupId: fallbackGroupId })}
{...stylex.props(shared.button, shared.focusRing)}
>
Add prefix
Add range
</button>
<button
type="button"
onClick={save}
disabled={!dirty || mutation.isPending || readOnly}
title={readOnly ? READ_ONLY_HINT : undefined}
disabled={!dirty || mutation.isPending}
{...stylex.props(shared.primaryButton, shared.focusRing)}
>
Save prefixes
Save assignments
</button>
{dirty && (
<button
@@ -191,6 +260,6 @@ export default function PrefixesEditor({ prefixes, groups }: Props) {
</button>
)}
</div>
</section>
</>
);
}
@@ -0,0 +1,72 @@
/**
* How a client says who it is, shared by the list and the detail page.
*
* The learned marker lives here and nowhere else. A client is named once on
* each of these two pages, so the tag is information; the query tables render
* the same muted name through `ClientName` without it, because repeating the
* tag down every row of a log is noise.
*/
import * as stylex from "@stylexjs/stylex";
import type { Client } from "@/lib/types";
import type { Authority } from "@/features/configuration/authority";
import { styles as shared } from "@/ui/styles";
import { colors } from "@/ui/tokens.stylex";
const styles = stylex.create({
unnamed: {
color: colors.textMuted,
},
});
export function ClientDisplayName({ client }: { client: Client }) {
if (client.name !== "") return <>{client.name}</>;
if (client.learned_name !== "") {
return (
<span {...stylex.props(shared.learnedName)}>
{client.learned_name}
<span {...stylex.props(shared.learnedTag)}>learned</span>
</span>
);
}
return <span {...stylex.props(styles.unnamed)}></span>;
}
export interface Provenance {
label: string;
detail: string;
}
/**
* Where this row's name and group came from.
*
* `hand_edited` records that an operator settled this client, but not which
* operator surface did: under file authority the reconciler sets it from the
* declaration, and in database mode the admin's own edit does. Authority is the
* only way to tell them apart, so while it is pending or unreachable the page
* says what it knows and names the doubt rather than picking one.
*/
export function provenanceOf(client: Client, authority: Authority): Provenance {
if (!client.hand_edited) {
return {
label: "Learned",
detail: "This client appeared from DNS traffic. Its name, if any, comes from reverse DNS.",
};
}
if (authority.state === "resolved" && authority.status.authority === "managed_file") {
return {
label: "Declared",
detail: `Declared in ${authority.status.path ?? "the configuration file"}. Reverse DNS does not overwrite it.`,
};
}
if (authority.state === "resolved") {
return {
label: "Edited",
detail: "The name and group were set here. Reverse DNS does not overwrite them.",
};
}
return {
label: "Set by hand",
detail: "Either declared in the configuration file or edited here — nxdns cannot say which until it reports its configuration status.",
};
}
+129
View File
@@ -0,0 +1,129 @@
/**
* The Clients pages under a real router: both of them read the same list, and
* the detail route is reached by deep link as often as by click, so the tests
* drive the router rather than the components.
*/
import { act, render, screen } from "@testing-library/react";
import { QueryClientProvider, type QueryClient } from "@tanstack/react-query";
import { RouterProvider, createMemoryHistory } from "@tanstack/react-router";
import { AuthProvider } from "@/auth/store";
import { createQueryClient } from "@/lib/queryClient";
import { queryKeys } from "@/lib/queries";
import { createAppRouter } from "@/routes";
export const GROUPS = {
groups: [
{ id: 1, name: "default", safe_search: false },
{ id: 2, name: "kids", safe_search: true },
],
};
export const CLIENTS = {
clients: [
{
id: 1,
ip: "192.168.1.10",
name: "laptop",
learned_name: "laptop-1.lan",
group_id: 1,
group: "default",
hand_edited: true,
first_seen: 1700000000,
last_seen: 1700003600,
},
{
id: 2,
ip: "192.168.1.11",
name: "",
learned_name: "kids-tablet.lan",
group_id: 2,
group: "kids",
hand_edited: false,
first_seen: 1700000000,
last_seen: 1700007200,
},
],
};
export const PREFIXES = {
client_prefixes: [{ id: 1, prefix: "192.168.1.0/24", group_id: 2, group: "kids", priority: 100 }],
};
const VERSION = { version: "0.0.0-test", git_commit: "0000000", zig_version: "0.16.0", uptime_seconds: 1 };
export const DATABASE = { authority: "database", path: null, reconciled_at: null, restart_pending: false };
export const MANAGED_FILE = {
authority: "managed_file",
path: "/etc/nxdns/config.zon",
reconciled_at: 1754899200,
restart_pending: false,
};
export const BASE: Record<string, unknown> = {
"GET /api/clients": CLIENTS,
"GET /api/client-prefixes": PREFIXES,
"GET /api/groups": GROUPS,
"GET /api/version": VERSION,
"GET /api/config/status": DATABASE,
};
/** A request that never settles, so its query stays pending for the whole test. */
export const NEVER = Symbol("never");
export function stubFetch(map: Record<string, unknown>): ReturnType<typeof vi.fn> {
const fetchMock = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
const key = `${init?.method ?? "GET"} ${String(input)}`;
const payload = map[key];
if (payload === NEVER) return new Promise<Response>(() => {});
if (payload === undefined) {
return new Response(JSON.stringify({ error: `not stubbed: ${key}` }), { status: 404 });
}
return new Response(JSON.stringify(payload), {
status: 200,
headers: { "content-type": "application/json" },
});
});
vi.stubGlobal("fetch", fetchMock);
return fetchMock;
}
export function renderAt(path: string, map: Record<string, unknown>) {
const fetchMock = stubFetch(map);
const queryClient = createQueryClient();
const router = createAppRouter(createMemoryHistory({ initialEntries: [path] }), queryClient);
render(
<AuthProvider>
<QueryClientProvider client={queryClient}>
<RouterProvider router={router} />
</QueryClientProvider>
</AuthProvider>,
);
return { router, fetchMock, queryClient };
}
export async function renderClientsPage(map: Record<string, unknown> = BASE) {
const handles = renderAt("/clients", map);
await screen.findByRole("heading", { name: "Clients" });
return handles;
}
/**
* Turns configuration authority under a mounted page, the way the status
* query's own poll would: the stub reads the map on each call, so replacing the
* entry and refetching is the whole transition. `undefined` stands for a failed
* status — the stub answers 404 for a key it does not hold.
*/
export async function setConfigStatus(
map: Record<string, unknown>,
queryClient: QueryClient,
status: unknown,
): Promise<void> {
map["GET /api/config/status"] = status;
await act(async () => {
await queryClient.refetchQueries({ queryKey: queryKeys.configStatus });
// The cache lands before its observers are notified — react-query defers
// that notification — so the render pass needs one more turn inside act.
await new Promise((resolve) => setTimeout(resolve, 0));
});
}
@@ -0,0 +1,45 @@
import type { ReactNode } from "react";
import * as stylex from "@stylexjs/stylex";
import InlineError from "@/lib/InlineError";
import type { ConfigStatus } from "@/lib/types";
import { styles as shared } from "@/ui/styles";
import { useAuthority } from "./authority";
import { styles } from "./styles";
/**
* Guards a configuration rendering on resolved authority (D6).
*
* The two renderings — editable forms and file-mode definition lists — are
* mutually exclusive answers to a question only the server can settle, so
* neither is drawn until it has. Pending is a skeleton; a failed status query
* is an error with a Retry, never a form drawn on a guess.
*
* Runtime actions do not pass through here. Pause, update now and reload
* certificates work under every authority, so their pages render them beside
* the gate rather than inside it.
*/
export default function AuthorityGate({ children }: { children: (status: ConfigStatus) => ReactNode }) {
const authority = useAuthority();
if (authority.state === "pending") {
return (
<p role="status" {...stylex.props(styles.pending, shared.pulse)}>
Checking which configuration source this server obeys
</p>
);
}
if (authority.state === "failed") {
return (
<div {...stylex.props(styles.blocked)}>
<p>
Configuration status unavailable. nxdns cannot say whether a file or the database owns this
configuration, so nothing here can be edited until it answers.
</p>
<InlineError error={authority.error} onRetry={authority.retry} />
</div>
);
}
return <>{children(authority.status)}</>;
}
@@ -0,0 +1,40 @@
import * as stylex from "@stylexjs/stylex";
import { formatTime } from "@/lib/format";
import { styles as shared } from "@/ui/styles";
import { colors } from "@/ui/tokens.stylex";
import { useAuthority } from "./authority";
const styles = stylex.create({
line: {
paddingInline: "0.75rem",
paddingBlock: "0.375rem",
fontSize: "0.75rem",
lineHeight: "1rem",
color: colors.textMuted,
},
path: {
overflowWrap: "anywhere",
},
});
/**
* File authority, stated once, in the configuration sub-navigation (§File
* mode). Not a banner on every route: the fact belongs to configuration, and
* repeating it above Overview and Activity buys nothing.
*
* "loaded" is deliberate. `reconciled_at` is when this process read the file;
* the server cannot prove the file still says what it said then, so the line
* never claims to describe the file's current contents.
*/
export default function AuthorityLine() {
const authority = useAuthority();
if (authority.state !== "resolved" || authority.status.authority !== "managed_file") return null;
const { path, reconciled_at } = authority.status;
return (
<p {...stylex.props(styles.line)}>
{"File-managed · "}
<code {...stylex.props(shared.mono, styles.path)}>{path}</code>
{reconciled_at === null ? null : ` · loaded ${formatTime(reconciled_at)}`}
</p>
);
}
@@ -10,9 +10,7 @@ test("swallowMutationError drops an ApiError and rethrows anything else", () =>
test("a rejected submit leaves the typed values in place; a resolved one clears them", async () => {
const rejecting = vi.fn(() => Promise.reject(new ApiError(400, "bad url")));
const { rerender } = render(
<BlocklistForm busy={false} readOnly={false} error={null} onSubmit={rejecting} onCancel={undefined} />,
);
const { rerender } = render(<BlocklistForm busy={false} error={null} onSubmit={rejecting} onCancel={undefined} />);
const url = screen.getByLabelText("URL") as HTMLInputElement;
const name = screen.getByLabelText("Name") as HTMLInputElement;
fireEvent.change(url, { target: { value: "https://example.com/list.txt" } });
@@ -24,7 +22,7 @@ test("a rejected submit leaves the typed values in place; a resolved one clears
expect(name.value).toBe("Example");
const resolving = vi.fn(() => Promise.resolve());
rerender(<BlocklistForm busy={false} readOnly={false} error={null} onSubmit={resolving} onCancel={undefined} />);
rerender(<BlocklistForm busy={false} error={null} onSubmit={resolving} onCancel={undefined} />);
fireEvent.click(screen.getByRole("button", { name: "Add source" }));
await waitFor(() => expect(url.value).toBe(""));
expect(name.value).toBe("");
@@ -4,7 +4,6 @@ import { ApiError } from "@/lib/api";
import InlineError from "@/lib/InlineError";
import type { Blocklist, BlocklistInput } from "@/lib/types";
import { styles as shared } from "@/ui/styles";
import { READ_ONLY_HINT } from "@/features/settings/authority";
const styles = stylex.create({
form: {
@@ -56,14 +55,12 @@ export function swallowMutationError(error: unknown): void {
interface BlocklistFormProps {
initial?: Blocklist;
busy: boolean;
/** File authority: the server answers 403, so the submit stays down. */
readOnly: boolean;
error: Error | null;
onSubmit: (input: BlocklistInput) => Promise<void>;
onCancel?: () => void;
}
export default function BlocklistForm({ initial, busy, readOnly, error, onSubmit, onCancel }: BlocklistFormProps) {
export default function BlocklistForm({ initial, busy, error, onSubmit, onCancel }: BlocklistFormProps) {
const [url, setUrl] = useState(initial?.url ?? "");
const [name, setName] = useState(initial?.name ?? "");
const [enabled, setEnabled] = useState(initial?.enabled ?? true);
@@ -122,12 +119,7 @@ export default function BlocklistForm({ initial, busy, readOnly, error, onSubmit
Enabled
</label>
<div {...stylex.props(styles.buttonRow)}>
<button
type="submit"
disabled={busy || readOnly}
title={readOnly ? READ_ONLY_HINT : undefined}
{...stylex.props(shared.primaryButton, shared.focusRing)}
>
<button type="submit" disabled={busy} {...stylex.props(shared.primaryButton, shared.focusRing)}>
{initial === undefined ? "Add source" : "Save changes"}
</button>
{onCancel !== undefined && (
@@ -0,0 +1,77 @@
import { render, screen, waitFor } from "@testing-library/react";
import { QueryClientProvider } from "@tanstack/react-query";
import { createQueryClient } from "@/lib/queryClient";
import DefinitionList from "@/ui/DefinitionList";
import ConfigLockIndicator from "./ConfigLockIndicator";
import { CONFIG_PATH, DATABASE, MANAGED_FILE, stubApi } from "./testFixtures";
import type { ConfigStatus } from "@/lib/types";
/**
* The two shared pieces the redesign adds: the file-mode rendering of a scalar
* and the compact lock a configuration control outside a configuration page
* carries.
*/
afterEach(() => {
vi.unstubAllGlobals();
});
function renderIndicator(status: ConfigStatus | "failed") {
if (status === "failed") {
stubApi(DATABASE, {
responses: {
"GET /api/config/status": new Response(JSON.stringify({ error: "unavailable" }), { status: 503 }),
},
});
} else {
stubApi(status);
}
render(
<QueryClientProvider client={createQueryClient()}>
<ConfigLockIndicator />
</QueryClientProvider>,
);
}
test("a definition names the value in words and the file key beside it", () => {
render(
<DefinitionList
items={[
{ label: "Port", zonKey: "dns.port", value: "53" },
{ label: "Authentication", value: "required" },
]}
/>,
);
const port = screen.getByText("Port");
expect(port.tagName).toBe("DT");
expect(port.textContent).toBe("Portdns.port");
// A derived value has no key: inventing one would send the reader looking
// for a line that is not in the file.
expect(screen.getByText("Authentication").textContent).toBe("Authentication");
expect(screen.getByText("required").tagName).toBe("DD");
});
test("the lock is silent when the database owns the configuration", async () => {
renderIndicator(DATABASE);
await waitFor(() => expect(screen.queryByText("Locked")).toBeNull());
});
test("under file authority the lock names the file, in words a reader hears", async () => {
renderIndicator(MANAGED_FILE);
const lock = await screen.findByText("Locked");
await waitFor(() =>
expect(lock.getAttribute("aria-label")).toBe(
`Locked. Managed by ${CONFIG_PATH}; edit the file and restart nxdns.`,
),
);
});
test("an unanswered status still locks, and says that is why", async () => {
renderIndicator("failed");
const lock = await screen.findByText("Locked");
await waitFor(() => expect(lock.getAttribute("aria-label")).toContain("Configuration status unavailable"));
});
@@ -0,0 +1,45 @@
import * as stylex from "@stylexjs/stylex";
import { colors } from "@/ui/tokens.stylex";
import { useAuthority } from "./authority";
const styles = stylex.create({
tag: {
marginLeft: "0.5rem",
borderWidth: 1,
borderStyle: "solid",
borderColor: colors.border,
borderRadius: "0.25rem",
paddingInline: "0.375rem",
paddingBlock: "0.125rem",
fontSize: "0.75rem",
lineHeight: "1rem",
color: colors.textMuted,
},
});
/**
* The compact lock, for a configuration control that survives outside a
* configuration page — the Clients page edits a group assignment the file may
* own. The configuration pages themselves do not use it: they change rendering
* rather than annotate a control they left up.
*
* The word is real text, not colour or an icon, so a screen reader announces
* the reason the control will not answer.
*/
export default function ConfigLockIndicator() {
const authority = useAuthority();
if (authority.state === "resolved" && authority.status.authority === "database") return null;
const reason =
authority.state === "pending"
? "Checking which configuration source this server obeys"
: authority.state === "failed"
? "Configuration status unavailable, so edits are held back"
: `Managed by ${authority.status.path ?? "the configuration file"}; edit the file and restart nxdns`;
return (
<span title={reason} aria-label={`Locked. ${reason}.`} {...stylex.props(styles.tag)}>
Locked
</span>
);
}
@@ -0,0 +1,17 @@
import * as stylex from "@stylexjs/stylex";
import { styles as shared } from "@/ui/styles";
import { styles } from "./styles";
/**
* The short note every file-managed page carries: where the values come from,
* and what applies a change to them. It replaces the disabled Save button —
* the reader needs the path, not a control that cannot work.
*/
export default function FileModeNote({ path }: { path: string | null }) {
return (
<p {...stylex.props(styles.fileNote)}>
These values are loaded from <code {...stylex.props(shared.mono)}>{path ?? "the configuration file"}</code>.
Edit that file to change them; most changes need an nxdns restart to take effect.
</p>
);
}
@@ -7,7 +7,6 @@ import { sameSet, toggleSource } from "./sourceSet";
import InlineError from "@/lib/InlineError";
import { styles as shared } from "@/ui/styles";
import { colors } from "@/ui/tokens.stylex";
import { READ_ONLY_HINT, useReadOnlyConfig } from "@/features/settings/authority";
interface Props {
groupId: number;
@@ -48,7 +47,6 @@ export default function GroupSourcesEditor({ groupId, blocklists }: Props) {
const sources = useQuery(groupSourcesQuery(groupId));
const mutation = useMutation(groupSourcesPutMutation(queryClient));
const [selected, setSelected] = useState<number[] | null>(null);
const readOnly = useReadOnlyConfig();
if (sources.isPending) {
return (
@@ -60,7 +58,7 @@ export default function GroupSourcesEditor({ groupId, blocklists }: Props) {
if (sources.isError) return <InlineError error={sources.error} />;
if (blocklists.length === 0) {
return <p {...stylex.props(styles.note)}>No blocklist sources exist yet add them on the Blocklists page.</p>;
return <p {...stylex.props(styles.note)}>No blocklist sources exist yet add them on the Sources tab.</p>;
}
const current = selected ?? sources.data;
@@ -87,8 +85,7 @@ export default function GroupSourcesEditor({ groupId, blocklists }: Props) {
<div {...stylex.props(styles.buttonRow)}>
<button
type="button"
disabled={!dirty || mutation.isPending || readOnly}
title={readOnly ? READ_ONLY_HINT : undefined}
disabled={!dirty || mutation.isPending}
onClick={() =>
mutation.mutate({ id: groupId, sourceIds: current }, { onSuccess: () => setSelected(null) })
}
@@ -0,0 +1,79 @@
import * as stylex from "@stylexjs/stylex";
import type { ForwardZone, LocalRecord } from "@/lib/types";
import { styles as shared } from "@/ui/styles";
import { styles as config } from "./styles";
/**
* Local records and forward zones under file authority. Collections are
* tables, not definition lists, and each names the ZON key it comes from once
* rather than repeating it on every row.
*/
export function RecordsReadOnly({ records }: { records: LocalRecord[] }) {
return (
<section {...stylex.props(config.panel)}>
<h2 {...stylex.props(config.panelHeading)}>
Local records
<code {...stylex.props(shared.mono, config.panelKey)}>local_records</code>
</h2>
{records.length === 0 ? (
<p {...stylex.props(config.empty)}>The file declares no local records.</p>
) : (
<div {...stylex.props(shared.tableWrap)}>
<table {...stylex.props(config.table)}>
<thead>
<tr>
<th {...stylex.props(shared.th)}>Name</th>
<th {...stylex.props(shared.th)}>Type</th>
<th {...stylex.props(shared.th)}>Value</th>
<th {...stylex.props(shared.th)}>TTL</th>
</tr>
</thead>
<tbody>
{records.map((record) => (
<tr key={record.id}>
<td {...stylex.props(shared.td, shared.mono)}>{record.name}</td>
<td {...stylex.props(shared.td)}>{record.rtype}</td>
<td {...stylex.props(shared.td, shared.mono)}>{record.value}</td>
<td {...stylex.props(shared.td, shared.tabularNums)}>{record.ttl}</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</section>
);
}
export function ZonesReadOnly({ zones }: { zones: ForwardZone[] }) {
return (
<section {...stylex.props(config.panel)}>
<h2 {...stylex.props(config.panelHeading)}>
Forward zones
<code {...stylex.props(shared.mono, config.panelKey)}>forward_zones</code>
</h2>
{zones.length === 0 ? (
<p {...stylex.props(config.empty)}>The file declares no forward zones.</p>
) : (
<div {...stylex.props(shared.tableWrap)}>
<table {...stylex.props(config.table)}>
<thead>
<tr>
<th {...stylex.props(shared.th)}>Zone</th>
<th {...stylex.props(shared.th)}>Resolver</th>
</tr>
</thead>
<tbody>
{zones.map((zone) => (
<tr key={zone.id}>
<td {...stylex.props(shared.td, shared.mono)}>{zone.zone}</td>
<td {...stylex.props(shared.td, shared.mono)}>{zone.resolver}</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</section>
);
}
@@ -0,0 +1,596 @@
import { useEffect, useState, type FormEvent } from "react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { Link, useNavigate, useSearch } from "@tanstack/react-router";
import * as stylex from "@stylexjs/stylex";
import { DEFAULT_GROUP_ID } from "@/lib/defaultGroup";
import { formatTime } from "@/lib/format";
import InlineError from "@/lib/InlineError";
import {
blocklistsQuery,
clientsQuery,
groupCreateMutation,
groupDeleteMutation,
groupSourcesQuery,
groupUpdateMutation,
groupsQuery,
ruleCreateMutation,
ruleDeleteMutation,
rulesQuery,
} from "@/lib/queries";
import type { Blocklist, ConfigStatus, Group, Rule, RuleAction, RuleKind } from "@/lib/types";
import ConfirmDialog from "@/ui/ConfirmDialog";
import DefinitionList from "@/ui/DefinitionList";
import Select from "@/ui/Select";
import { styles as shared } from "@/ui/styles";
import { colors } from "@/ui/tokens.stylex";
import AuthorityGate from "./AuthorityGate";
import FileModeNote from "./FileModeNote";
import GroupSourcesEditor from "./GroupSourcesEditor";
import QueryPanel from "./QueryPanel";
import { styles as config } from "./styles";
const DEFAULT_GROUP_NOTE = "The default group cannot be renamed or deleted.";
const KIND_OPTIONS = [
{ value: "exact", label: "exact" },
{ value: "wildcard", label: "wildcard" },
{ value: "regex", label: "regex" },
];
const ACTION_OPTIONS = [
{ value: "allow", label: "allow" },
{ value: "block", label: "block" },
];
const styles = stylex.create({
createForm: {
display: "flex",
flexWrap: "wrap",
alignItems: "center",
gap: "0.5rem",
marginBottom: "0.75rem",
},
fieldLabel: {
display: "block",
fontSize: "0.875rem",
lineHeight: "1.25rem",
fontWeight: 500,
},
detailHeading: {
fontSize: "1.25rem",
lineHeight: "1.75rem",
fontWeight: 600,
},
controlRow: {
marginTop: "0.75rem",
display: "flex",
flexWrap: "wrap",
alignItems: "center",
gap: "0.75rem",
},
checkboxLabel: {
display: "inline-flex",
alignItems: "center",
gap: "0.5rem",
fontSize: "0.875rem",
lineHeight: "1.25rem",
},
spacer: {
marginLeft: "auto",
},
destructive: {
color: colors.danger,
},
ruleForm: {
display: "flex",
flexDirection: "column",
gap: "0.75rem",
marginTop: "1rem",
maxWidth: "36rem",
},
fieldGrid: {
display: "grid",
gap: "0.75rem",
gridTemplateColumns: {
default: "repeat(1, minmax(0, 1fr))",
"@media (min-width: 640px)": "repeat(2, minmax(0, 1fr))",
},
},
allow: {
color: colors.primaryOnSurface,
},
block: {
color: colors.danger,
},
pattern: {
fontWeight: 500,
},
});
export default function ProtectionGroups() {
const groups = useQuery(groupsQuery());
return (
<AuthorityGate>
{(status) => (
<div>
{status.authority === "managed_file" && <FileModeNote path={status.path} />}
<QueryPanel query={groups}>
{(rows) => <GroupsMasterDetail groups={rows} status={status} />}
</QueryPanel>
</div>
)}
</AuthorityGate>
);
}
/**
* Master/detail on one group at a time. The selection is `?group=`, so a view
* of a group is a link and the browser's back button walks the groups the
* reader looked at.
*/
function GroupsMasterDetail({ groups, status }: { groups: Group[]; status: ConfigStatus }) {
const search = useSearch({ from: "/shell/configuration/protection" });
const navigate = useNavigate({ from: "/configuration/protection" });
const known = groups.some((group) => group.id === search.group);
const selectedId = known ? search.group : groups[0]?.id;
const selected = groups.find((group) => group.id === selectedId);
// An id the URL named that no group has — deleted, or hand-typed — falls
// back to the first group, and the URL is rewritten to say so. `replace`,
// because a corrected address is not a place the reader chose to be and a
// back button that returns to it would trap them.
useEffect(() => {
if (selectedId === undefined || selectedId === search.group) return;
void navigate({ search: { tab: search.tab, group: selectedId }, replace: true });
}, [navigate, search.group, search.tab, selectedId]);
const fileMode = status.authority === "managed_file";
return (
<div {...stylex.props(config.split)}>
<div>
{!fileMode && <CreateGroupForm />}
<nav aria-label="Groups" {...stylex.props(styles.controlRow)}>
<ul {...stylex.props(config.masterList)}>
{groups.map((group) => (
<li key={group.id}>
<Link
to="/configuration/protection"
search={{ tab: search.tab, group: group.id }}
activeOptions={{ includeSearch: true }}
{...stylex.props(
config.masterLink,
group.id === selectedId && config.masterLinkActive,
shared.focusRing,
)}
>
{group.name}
</Link>
</li>
))}
</ul>
</nav>
</div>
{selected === undefined ? (
<p {...stylex.props(config.empty)}>No groups exist.</p>
) : fileMode ? (
<GroupDetailReadOnly group={selected} />
) : (
<GroupDetailEditable group={selected} />
)}
</div>
);
}
function CreateGroupForm() {
const queryClient = useQueryClient();
const create = useMutation(groupCreateMutation(queryClient));
const [newName, setNewName] = useState("");
return (
<>
<form
{...stylex.props(styles.createForm)}
onSubmit={(event: FormEvent) => {
event.preventDefault();
const name = newName.trim();
if (name === "") return;
create.mutate({ name }, { onSuccess: () => setNewName("") });
}}
>
<label {...stylex.props(styles.fieldLabel)} htmlFor="new-group-name">
New group
</label>
<input
id="new-group-name"
type="text"
value={newName}
onChange={(event) => setNewName(event.target.value)}
{...stylex.props(shared.smallInput, shared.focusRing)}
/>
<button
type="submit"
disabled={create.isPending}
{...stylex.props(shared.primaryButton, shared.focusRing)}
>
Create
</button>
</form>
<InlineError error={create.error} />
</>
);
}
function ClientCountLink({ group }: { group: Group }) {
const clients = useQuery(clientsQuery());
const count = clients.data?.filter((client) => client.group_id === group.id).length;
return (
<p {...stylex.props(config.note)}>
<Link to="/clients" search={{ group: group.id }} {...stylex.props(shared.focusRing)}>
{count === undefined
? "Clients in this group"
: `${count} client${count === 1 ? "" : "s"} in this group`}
</Link>
</p>
);
}
function GroupDetailReadOnly({ group }: { group: Group }) {
return (
<div>
<h2 {...stylex.props(styles.detailHeading)}>{group.name}</h2>
<section {...stylex.props(config.panel)}>
<DefinitionList
items={[
{ label: "Name", zonKey: "groups[].name", value: group.name },
{ label: "Safe search", zonKey: "groups[].safe_search", value: String(group.safe_search) },
]}
/>
</section>
<GroupSourcesReadOnly group={group} />
<GroupRules group={group} editable={false} />
<ClientCountLink group={group} />
</div>
);
}
function GroupSourcesReadOnly({ group }: { group: Group }) {
const blocklists = useQuery(blocklistsQuery());
const assigned = useQuery(groupSourcesQuery(group.id));
return (
<section {...stylex.props(config.panel)}>
<h3 {...stylex.props(config.panelHeading)}>
Assigned sources
<code {...stylex.props(shared.mono, config.panelKey)}>group_sources</code>
</h3>
<QueryPanel query={assigned}>
{(sourceIds) => (
<QueryPanel query={blocklists}>
{(catalogue) => <AssignedSources sourceIds={sourceIds} catalogue={catalogue} />}
</QueryPanel>
)}
</QueryPanel>
</section>
);
}
function AssignedSources({ sourceIds, catalogue }: { sourceIds: number[]; catalogue: Blocklist[] }) {
const assigned = catalogue.filter((source) => sourceIds.includes(source.id));
if (assigned.length === 0) return <p {...stylex.props(config.empty)}>This group is assigned no sources.</p>;
return (
<div {...stylex.props(shared.tableWrap)}>
<table {...stylex.props(config.table)}>
<thead>
<tr>
<th {...stylex.props(shared.th)}>Source</th>
<th {...stylex.props(shared.th)}>URL</th>
</tr>
</thead>
<tbody>
{assigned.map((source) => (
<tr key={source.id}>
<td {...stylex.props(shared.td)}>{source.name}</td>
<td {...stylex.props(shared.td, shared.mono)}>{source.url}</td>
</tr>
))}
</tbody>
</table>
</div>
);
}
function GroupDetailEditable({ group }: { group: Group }) {
const queryClient = useQueryClient();
const blocklists = useQuery(blocklistsQuery());
const update = useMutation(groupUpdateMutation(queryClient));
const remove = useMutation(groupDeleteMutation(queryClient));
const [renaming, setRenaming] = useState(false);
const [name, setName] = useState(group.name);
const [confirming, setConfirming] = useState(false);
const isDefault = group.id === DEFAULT_GROUP_ID;
return (
<div>
{renaming ? (
<form
{...stylex.props(styles.controlRow)}
onSubmit={(event: FormEvent) => {
event.preventDefault();
const trimmed = name.trim();
if (trimmed === "") return;
update.mutate(
{ id: group.id, input: { name: trimmed, safe_search: group.safe_search } },
{ onSuccess: () => setRenaming(false) },
);
}}
>
<input
type="text"
aria-label={`New name for ${group.name}`}
value={name}
onChange={(event) => setName(event.target.value)}
{...stylex.props(shared.smallInput, shared.focusRing)}
autoFocus
/>
<button
type="submit"
disabled={update.isPending}
{...stylex.props(shared.smallButton, shared.focusRing)}
>
Save
</button>
<button
type="button"
onClick={() => {
setName(group.name);
setRenaming(false);
}}
{...stylex.props(shared.smallButton, shared.focusRing)}
>
Cancel
</button>
</form>
) : (
<h2 {...stylex.props(styles.detailHeading)}>{group.name}</h2>
)}
<div {...stylex.props(styles.controlRow)}>
<label {...stylex.props(styles.checkboxLabel)}>
<input
type="checkbox"
checked={group.safe_search}
disabled={update.isPending}
{...stylex.props(shared.focusRing)}
onChange={(event) =>
update.mutate({
id: group.id,
input: { name: group.name, safe_search: event.target.checked },
})
}
/>
Safe search
</label>
<span {...stylex.props(styles.spacer)}>
{!renaming && (
<button
type="button"
disabled={isDefault}
title={isDefault ? DEFAULT_GROUP_NOTE : undefined}
onClick={() => {
setName(group.name);
setRenaming(true);
}}
{...stylex.props(shared.smallButton, shared.focusRing)}
>
Rename group
</button>
)}{" "}
<button
type="button"
disabled={isDefault || remove.isPending}
title={isDefault ? DEFAULT_GROUP_NOTE : undefined}
onClick={() => setConfirming(true)}
{...stylex.props(shared.smallButton, styles.destructive, shared.focusRing)}
>
Delete group
</button>
</span>
</div>
{isDefault && <p {...stylex.props(config.note)}>{DEFAULT_GROUP_NOTE}</p>}
<InlineError error={update.error ?? remove.error} />
<section {...stylex.props(config.panel)}>
<h3 {...stylex.props(config.panelHeading)}>Assigned sources</h3>
<QueryPanel query={blocklists}>
{(catalogue) => <GroupSourcesEditor groupId={group.id} blocklists={catalogue} />}
</QueryPanel>
</section>
<GroupRules group={group} editable />
<ClientCountLink group={group} />
<ConfirmDialog
isOpen={confirming}
title="Delete group"
message={`Delete group "${group.name}"? Its clients fall back to the default group.`}
confirmLabel="Delete"
onConfirm={() => {
setConfirming(false);
remove.mutate(group.id);
}}
onCancel={() => setConfirming(false)}
/>
</div>
);
}
/**
* The rules that apply to the selected group, and nothing else. Rules are
* always scoped to a group, so the group-centred page is the only place they
* need to be read: a flat list of every rule in the household was a list of
* facts about no particular policy.
*/
function GroupRules({ group, editable }: { group: Group; editable: boolean }) {
const rules = useQuery(rulesQuery());
return (
<section {...stylex.props(config.panel)}>
<h3 {...stylex.props(config.panelHeading)}>
Rules
{!editable && <code {...stylex.props(shared.mono, config.panelKey)}>rules</code>}
</h3>
<QueryPanel query={rules}>
{(all) => {
const scoped = all.filter((rule) => rule.group_id === group.id);
return (
<>
{scoped.length === 0 ? (
<p {...stylex.props(config.empty)}>No allow or block rules for this group.</p>
) : (
<RulesTable rules={scoped} editable={editable} />
)}
{editable && <CreateRuleForm group={group} />}
</>
);
}}
</QueryPanel>
</section>
);
}
function RulesTable({ rules, editable }: { rules: Rule[]; editable: boolean }) {
const queryClient = useQueryClient();
const remove = useMutation(ruleDeleteMutation(queryClient));
const [pendingDelete, setPendingDelete] = useState<Rule | null>(null);
return (
<>
<div {...stylex.props(shared.tableWrap)}>
<table {...stylex.props(config.table)}>
<thead>
<tr>
<th {...stylex.props(shared.th)}>Pattern</th>
<th {...stylex.props(shared.th)}>Kind</th>
<th {...stylex.props(shared.th)}>Action</th>
<th {...stylex.props(shared.th)}>Created</th>
{editable && (
<th {...stylex.props(shared.th)}>
<span {...stylex.props(shared.srOnly)}>Actions</span>
</th>
)}
</tr>
</thead>
<tbody>
{rules.map((rule) => (
<tr key={rule.id}>
<td {...stylex.props(shared.td, styles.pattern)}>{rule.pattern}</td>
<td {...stylex.props(shared.td)}>{rule.kind}</td>
<td {...stylex.props(shared.td)}>
<span {...stylex.props(rule.action === "allow" ? styles.allow : styles.block)}>
{rule.action}
</span>
</td>
<td {...stylex.props(shared.td)}>{formatTime(rule.created_at)}</td>
{editable && (
<td {...stylex.props(shared.td)}>
<button
type="button"
onClick={() => setPendingDelete(rule)}
disabled={remove.isPending}
{...stylex.props(shared.dangerLinkButton, shared.focusRing)}
>
Delete
</button>
</td>
)}
</tr>
))}
</tbody>
</table>
</div>
<InlineError error={remove.error} />
<ConfirmDialog
isOpen={pendingDelete !== null}
title="Delete rule"
message={
pendingDelete === null
? ""
: `Delete the ${pendingDelete.action} rule for "${pendingDelete.pattern}"?`
}
confirmLabel="Delete"
onConfirm={() => {
if (pendingDelete !== null) remove.mutate(pendingDelete.id);
setPendingDelete(null);
}}
onCancel={() => setPendingDelete(null)}
/>
</>
);
}
function CreateRuleForm({ group }: { group: Group }) {
const queryClient = useQueryClient();
const create = useMutation(ruleCreateMutation(queryClient));
const [pattern, setPattern] = useState("");
const [kind, setKind] = useState<RuleKind>("exact");
const [action, setAction] = useState<RuleAction>("block");
function onSubmit(event: FormEvent) {
event.preventDefault();
// A regex pattern is stored and matched byte for byte, so the UI must not
// edit it: trimming here would make a UI-created rule differ from the same
// bytes posted to /api/rules. Name-shaped kinds are normalized server-side,
// so trimming them only spares a pasted space a 400.
const sent = kind === "regex" ? pattern : pattern.trim();
create.mutate({ group_id: group.id, pattern: sent, kind, action }, { onSuccess: () => setPattern("") });
}
return (
<form onSubmit={onSubmit} {...stylex.props(styles.ruleForm)}>
<h4 {...stylex.props(styles.fieldLabel)}>Create rule in {group.name}</h4>
<div>
<label htmlFor="rule-pattern" {...stylex.props(styles.fieldLabel)}>
Pattern
</label>
<input
id="rule-pattern"
type="text"
required
value={pattern}
onChange={(event) => setPattern(event.target.value)}
placeholder="ads.example.com, *.example.com or ^ad[0-9]+-"
// A phone keyboard capitalizing the first letter is silent for
// exact and wildcard (normalized server-side) but fatal for a
// regex, which matches the lowercase query name byte for byte.
autoCapitalize="none"
autoCorrect="off"
spellCheck={false}
{...stylex.props(shared.input, shared.focusRing)}
/>
</div>
<div {...stylex.props(styles.fieldGrid)}>
<Select
label="Kind"
value={kind}
onChange={(value) => setKind(value as RuleKind)}
options={KIND_OPTIONS}
/>
<Select
label="Action"
value={action}
onChange={(value) => setAction(value as RuleAction)}
options={ACTION_OPTIONS}
/>
</div>
<div>
<button
type="submit"
disabled={create.isPending}
{...stylex.props(shared.primaryButton, shared.focusRing)}
>
{create.isPending ? "Creating…" : "Create rule"}
</button>
</div>
<InlineError error={create.error} />
</form>
);
}
@@ -0,0 +1,295 @@
import { fireEvent, screen, waitFor, within } from "@testing-library/react";
import { DATABASE, renderPage, stubApi, type Call } from "./testFixtures";
/**
* Protection in database mode: the group-centred master/detail, the rules
* scoped to the selected group, and the shared source catalogue with its one
* runtime action.
*/
let calls: Call[];
afterEach(() => {
vi.unstubAllGlobals();
});
async function openProtection(group?: number) {
calls = stubApi(DATABASE);
const suffix = group === undefined ? "" : `?group=${group}`;
return renderPage(`/configuration/protection${suffix}`, "Protection");
}
function writes(method: string): Call[] {
return calls.filter((call) => call.method === method);
}
test("the group list is the master, and the selected group is the detail", async () => {
await openProtection();
const list = within(screen.getByRole("navigation", { name: "Groups" }));
expect(list.getByRole("link", { name: "default" })).toBeTruthy();
expect(list.getByRole("link", { name: "kids" })).toBeTruthy();
await screen.findByRole("heading", { name: "default", level: 2 });
});
test("the default group cannot be renamed or deleted, and says why", async () => {
await openProtection(1);
await screen.findByRole("heading", { name: "default", level: 2 });
expect((screen.getByRole("button", { name: "Rename group" }) as HTMLButtonElement).disabled).toBe(true);
expect((screen.getByRole("button", { name: "Delete group" }) as HTMLButtonElement).disabled).toBe(true);
expect(screen.getByText("The default group cannot be renamed or deleted.")).toBeTruthy();
});
test("another group can be renamed and deleted, and carries its safe-search state", async () => {
await openProtection(2);
await screen.findByRole("heading", { name: "kids", level: 2 });
expect((screen.getByRole("button", { name: "Rename group" }) as HTMLButtonElement).disabled).toBe(false);
expect((screen.getByRole("checkbox", { name: "Safe search" }) as HTMLInputElement).checked).toBe(true);
fireEvent.click(screen.getByRole("button", { name: "Delete group" }));
const dialog = await screen.findByRole("alertdialog");
expect(dialog.textContent).toContain('Delete group "kids"?');
fireEvent.click(within(dialog).getByRole("button", { name: "Cancel" }));
await waitFor(() => expect(screen.queryByRole("alertdialog")).toBeNull());
expect(writes("DELETE")).toEqual([]);
});
test("toggling safe search resends the whole group row", async () => {
await openProtection(2);
await screen.findByRole("heading", { name: "kids", level: 2 });
fireEvent.click(screen.getByRole("checkbox", { name: "Safe search" }));
await waitFor(() => expect(writes("PUT")).toHaveLength(1));
expect(writes("PUT")[0]).toMatchObject({
url: "/api/groups/2",
body: { name: "kids", safe_search: false },
});
});
test("the source assignment saves the full set via PUT", async () => {
await openProtection(2);
await screen.findByRole("heading", { name: "kids", level: 2 });
const ads = (await screen.findByRole("checkbox", { name: "Ads" })) as HTMLInputElement;
expect(ads.checked).toBe(false);
const save = screen.getByRole("button", { name: "Save sources" }) as HTMLButtonElement;
expect(save.disabled).toBe(true);
fireEvent.click(ads);
expect(save.disabled).toBe(false);
fireEvent.click(save);
await waitFor(() => expect(writes("PUT")).toHaveLength(1));
expect(writes("PUT")[0]).toMatchObject({
url: "/api/groups/2/sources",
body: { source_ids: [1] },
});
});
test("only the selected group's rules are listed", async () => {
await openProtection(2);
await screen.findByRole("heading", { name: "kids", level: 2 });
expect(await screen.findByText("*.social.example")).toBeTruthy();
expect(screen.queryByText("ads.example.com")).toBeNull();
});
test("a new rule is created in the selected group, with the pattern posted verbatim for a regex", async () => {
await openProtection(2);
await screen.findByRole("heading", { name: "Create rule in kids", level: 4 });
// An exact pattern is trimmed; a regex is stored and matched byte for byte.
fireEvent.change(screen.getByLabelText("Pattern"), { target: { value: " ads.example.net " } });
fireEvent.click(screen.getByRole("button", { name: "Create rule" }));
await waitFor(() => expect(writes("POST")).toHaveLength(1));
expect(writes("POST")[0]?.body).toEqual({
group_id: 2,
pattern: "ads.example.net",
kind: "exact",
action: "block",
});
});
test("a rate-limited rule create shows the countdown from Retry-After", async () => {
calls = stubApi(DATABASE, {
onWrite: (call) =>
call.url === "/api/rules"
? new Response(JSON.stringify({ error: "rate limited" }), {
status: 429,
headers: { "content-type": "application/json", "Retry-After": "12" },
})
: null,
});
await renderPage("/configuration/protection?group=2", "Protection");
await screen.findByRole("heading", { name: "Create rule in kids", level: 4 });
fireEvent.change(screen.getByLabelText("Pattern"), { target: { value: "ads.example.net" } });
fireEvent.click(screen.getByRole("button", { name: "Create rule" }));
expect((await screen.findByRole("alert")).textContent).toBe("Rate limited. Try again in 12s.");
});
test("cancelling the rule delete confirmation leaves the rule alone", async () => {
await openProtection(2);
await screen.findByText("*.social.example");
fireEvent.click(screen.getByRole("button", { name: "Delete" }));
const dialog = await screen.findByRole("alertdialog");
fireEvent.click(within(dialog).getByRole("button", { name: "Cancel" }));
await waitFor(() => expect(screen.queryByRole("alertdialog")).toBeNull());
expect(writes("DELETE")).toEqual([]);
expect(screen.getByText("*.social.example")).toBeTruthy();
});
test("the pattern field opts out of mobile autocapitalize and autocorrect", async () => {
await openProtection(2);
const pattern = await screen.findByLabelText("Pattern");
expect(pattern.getAttribute("autocapitalize")).toBe("none");
expect(pattern.getAttribute("autocorrect")).toBe("off");
expect(pattern.getAttribute("spellcheck")).toBe("false");
});
test("the kind selector offers the three contract kinds and can pick regex", async () => {
await openProtection(2);
await screen.findByLabelText("Pattern");
fireEvent.click(screen.getByRole("button", { name: /Kind$/ }));
const options = await screen.findAllByRole("option");
expect(options.map((option) => option.textContent)).toEqual(["exact", "wildcard", "regex"]);
fireEvent.click(screen.getByRole("option", { name: "regex" }));
await waitFor(() => expect(screen.queryByRole("listbox")).toBeNull());
fireEvent.change(screen.getByLabelText("Pattern"), { target: { value: " ^ad[0-9]+- " } });
fireEvent.click(screen.getByRole("button", { name: "Create rule" }));
await waitFor(() => expect(writes("POST")).toHaveLength(1));
expect(writes("POST")[0]?.body).toMatchObject({ pattern: " ^ad[0-9]+- ", kind: "regex" });
});
test("deleting a rule asks first, then issues the DELETE", async () => {
await openProtection(2);
await screen.findByText("*.social.example");
fireEvent.click(screen.getByRole("button", { name: "Delete" }));
const dialog = await screen.findByRole("alertdialog");
expect(dialog.textContent).toContain('Delete the block rule for "*.social.example"?');
fireEvent.click(within(dialog).getByRole("button", { name: "Delete" }));
await waitFor(() => expect(writes("DELETE")).toHaveLength(1));
expect(writes("DELETE")[0]?.url).toBe("/api/rules/2");
});
test("the client count links into Clients filtered by the group (D3)", async () => {
await openProtection(2);
const link = await screen.findByRole("link", { name: "1 client in this group" });
expect(link.getAttribute("href")).toBe("/clients?group=2");
});
test("a group can be created from the master column", async () => {
await openProtection();
fireEvent.change(await screen.findByLabelText("New group"), { target: { value: " guests " } });
fireEvent.click(screen.getByRole("button", { name: "Create" }));
await waitFor(() => expect(writes("POST")).toHaveLength(1));
expect(writes("POST")[0]).toMatchObject({ url: "/api/groups", body: { name: "guests" } });
});
test("the Sources tab lists the catalogue with both skipped columns and their note", async () => {
calls = stubApi(DATABASE);
await renderPage("/configuration/protection?tab=sources", "Protection");
expect(await screen.findByText("Ads")).toBeTruthy();
expect(screen.getByText("Trackers")).toBeTruthy();
expect(screen.getByText("Suggested")).toBeTruthy();
expect(screen.getByRole("columnheader", { name: "Skipped regex" })).toBeTruthy();
expect(screen.getByRole("columnheader", { name: "Skipped unsupported" })).toBeTruthy();
expect(
screen.getByText(/Skipped unsupported lines are syntax nxdns cannot translate into a DNS decision/),
).toBeTruthy();
expect((screen.getByLabelText("Ads enabled") as HTMLInputElement).checked).toBe(true);
expect((screen.getByLabelText("Trackers enabled") as HTMLInputElement).checked).toBe(false);
expect(screen.getByRole("heading", { name: "Add source" })).toBeTruthy();
});
test("Update now says it started, and says nothing once it succeeds", async () => {
let release: ((response: Response) => void) | null = null;
calls = stubApi(DATABASE, {
onWrite: (call) =>
// Held open so the started state is observable, not a frame that resolves
// before the assertion.
call.url === "/api/blocklists/update"
? new Promise<Response>((resolve) => {
release = resolve;
})
: null,
});
await renderPage("/configuration/protection?tab=sources", "Protection");
fireEvent.click(await screen.findByRole("button", { name: "Update now" }));
const pending = (await screen.findByRole("button", { name: "Updating…" })) as HTMLButtonElement;
expect(pending.disabled).toBe(true);
expect(screen.getByRole("status").textContent).toBe("Update started…");
release!(
new Response(JSON.stringify({ sources: [] }), {
status: 202,
headers: { "content-type": "application/json" },
}),
);
await waitFor(() => expect(screen.getByRole("button", { name: "Update now" })).toBeTruthy());
// Success leaves no standing claim behind: the refreshed counters are the
// signal, and a "counters refreshed" line would outlive a failed refetch.
expect(screen.queryByRole("status")).toBeNull();
});
test("a rate-limited Update now shows the countdown from Retry-After", async () => {
calls = stubApi(DATABASE, {
onWrite: (call) =>
call.url === "/api/blocklists/update"
? new Response(JSON.stringify({ error: "rate limited" }), {
status: 429,
headers: { "content-type": "application/json", "Retry-After": "7" },
})
: null,
});
await renderPage("/configuration/protection?tab=sources", "Protection");
fireEvent.click(await screen.findByRole("button", { name: "Update now" }));
const alert = await screen.findByRole("alert");
expect(alert.textContent).toBe("Rate limited. Try again in 7s.");
});
test("deleting a source asks first, then issues the DELETE for that source", async () => {
calls = stubApi(DATABASE);
await renderPage("/configuration/protection?tab=sources", "Protection");
await screen.findByText("Ads");
fireEvent.click(screen.getAllByRole("button", { name: "Delete" })[1]!);
const dialog = await screen.findByRole("alertdialog");
expect(dialog.textContent).toContain('Delete blocklist "Trackers"? Its domains stop being blocked.');
fireEvent.click(within(dialog).getByRole("button", { name: "Delete" }));
await waitFor(() => expect(writes("DELETE")).toHaveLength(1));
expect(writes("DELETE")[0]?.url).toBe("/api/blocklists/2");
});
test("cancelling the source delete confirmation leaves the source alone", async () => {
calls = stubApi(DATABASE);
await renderPage("/configuration/protection?tab=sources", "Protection");
await screen.findByText("Ads");
fireEvent.click(screen.getAllByRole("button", { name: "Delete" })[1]!);
const dialog = await screen.findByRole("alertdialog");
fireEvent.click(within(dialog).getByRole("button", { name: "Cancel" }));
await waitFor(() => expect(screen.queryByRole("alertdialog")).toBeNull());
expect(writes("DELETE")).toEqual([]);
expect(screen.getByText("Trackers")).toBeTruthy();
});
@@ -0,0 +1,38 @@
import { useNavigate, useSearch } from "@tanstack/react-router";
import * as stylex from "@stylexjs/stylex";
import Tabs from "@/ui/Tabs";
import ProtectionGroups from "./ProtectionGroups";
import ProtectionSources from "./ProtectionSources";
import { styles } from "./styles";
import type { ProtectionTab } from "./search";
/**
* Protection: what policy governs each group, and which rules and lists
* produce it. Group-centred, because a rule or a source only means something
* once you know whose queries it applies to.
*/
export default function ProtectionPage() {
const search = useSearch({ from: "/shell/configuration/protection" });
const tab = search.tab ?? "groups";
const navigate = useNavigate({ from: "/configuration/protection" });
return (
<section>
<h1 {...stylex.props(styles.heading)}>Protection</h1>
<p {...stylex.props(styles.intro)}>What each group of clients is allowed to resolve, and why.</p>
<Tabs
label="Protection"
selectedKey={tab}
// The group rides along, so switching tabs and coming back returns to
// the group the reader was looking at rather than the first one.
onSelectionChange={(key) =>
void navigate({ search: { tab: key as ProtectionTab, group: search.group } })
}
tabs={[
{ id: "groups", label: "Groups", content: <ProtectionGroups /> },
{ id: "sources", label: "Sources", content: <ProtectionSources /> },
]}
/>
</section>
);
}
@@ -1,5 +1,5 @@
import { useState } from "react";
import { useMutation, useQueryClient, useSuspenseQuery } from "@tanstack/react-query";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import * as stylex from "@stylexjs/stylex";
import { formatTime } from "@/lib/format";
import InlineError from "@/lib/InlineError";
@@ -11,48 +11,23 @@ import {
blocklistsUpdateNowMutation,
} from "@/lib/queries";
import type { Blocklist, BlocklistInput } from "@/lib/types";
import BlocklistForm from "./BlocklistForm";
import { useRefreshStatus } from "./refreshStore";
import SourceStatusSection from "./SourceStatusSection";
import ConfirmDialog from "@/ui/ConfirmDialog";
import { styles as shared } from "@/ui/styles";
import { colors } from "@/ui/tokens.stylex";
import { READ_ONLY_HINT, useReadOnlyConfig } from "@/features/settings/authority";
import AuthorityGate from "./AuthorityGate";
import BlocklistForm from "./BlocklistForm";
import FileModeNote from "./FileModeNote";
import QueryPanel from "./QueryPanel";
import { styles as config } from "./styles";
const SKIPPED_NOTE =
"Both “Skipped” columns count lines nxdns read and did not take. Skipped regex lines are patterns nxdns accepts " +
"only from you — adopt one you trust as a regex rule. Skipped unsupported lines are syntax nxdns cannot translate " +
"into a DNS decision: cosmetic element hiding, browser-only modifiers. A skipped unsupported count that dwarfs the " +
"domain count usually means the list is written for a browser extension, and its DNS or hosts variant will block " +
"more here.";
const styles = stylex.create({
header: {
display: "flex",
flexWrap: "wrap",
alignItems: "center",
justifyContent: "space-between",
gap: "0.75rem",
},
heading: {
fontSize: "1.5rem",
lineHeight: "2rem",
fontWeight: 600,
},
done: {
marginTop: "0.5rem",
fontSize: "0.875rem",
lineHeight: "1.25rem",
color: colors.primaryOnSurface,
},
empty: {
marginTop: "1rem",
color: colors.textMuted,
},
note: {
marginTop: "0.5rem",
color: colors.textMuted,
},
table: {
width: "100%",
minWidth: "max-content",
borderCollapse: "collapse",
fontSize: "0.875rem",
lineHeight: "1.25rem",
},
name: {
fontWeight: 500,
},
@@ -82,9 +57,129 @@ const styles = stylex.create({
},
});
export default function BlocklistsPage() {
/**
* A runtime action: it re-downloads the sources the running process already
* knows about, so it stays enabled under file authority and while
* `/api/config/status` is still answering.
*
* The feedback is the action's own, and it is transient: started while the
* request is in flight, the failure verbatim if it fails, and nothing on
* success the refreshed counters are the success signal, and a standing
* "counters refreshed" line would claim a refetch that may itself have failed.
* Durable per-source outcomes live in Diagnostics.
*/
function UpdateNowAction() {
const queryClient = useQueryClient();
const updateNow = useMutation(blocklistsUpdateNowMutation(queryClient));
return (
<div {...stylex.props(config.actionRow)}>
<button
type="button"
onClick={() => updateNow.mutate()}
disabled={updateNow.isPending}
{...stylex.props(shared.primaryButton, shared.focusRing)}
>
{updateNow.isPending ? "Updating…" : "Update now"}
</button>
{updateNow.isPending && (
<p role="status" {...stylex.props(config.note)}>
Update started
</p>
)}
<InlineError error={updateNow.error} />
</div>
);
}
export default function ProtectionSources() {
const blocklists = useQuery(blocklistsQuery());
return (
<div>
<p {...stylex.props(config.intro)}>
The shared catalogue every group draws from. A group subscribes to sources on the Groups tab.
</p>
<UpdateNowAction />
<AuthorityGate>
{(status) =>
status.authority === "managed_file" ? (
<>
<FileModeNote path={status.path} />
<QueryPanel query={blocklists}>
{(rows) => <SourcesReadOnly blocklists={rows} />}
</QueryPanel>
</>
) : (
<QueryPanel query={blocklists}>{(rows) => <SourcesEditor blocklists={rows} />}</QueryPanel>
)
}
</AuthorityGate>
</div>
);
}
/**
* File mode is a different rendering of the same facts, not a smaller set of
* them: the Suggested provenance and both skipped-line counters belong here
* too. A list whose lines nxdns could not take is a failure the reader must
* see under either authority.
*/
function SourcesReadOnly({ blocklists }: { blocklists: Blocklist[] }) {
return (
<section {...stylex.props(config.panel)}>
<h2 {...stylex.props(config.panelHeading)}>
Blocklist sources
<code {...stylex.props(shared.mono, config.panelKey)}>blocklist_sources</code>
</h2>
{blocklists.length === 0 ? (
<p {...stylex.props(config.empty)}>The file declares no blocklist sources.</p>
) : (
<div {...stylex.props(shared.tableWrap)}>
<table {...stylex.props(config.table)}>
<thead>
<tr>
<th {...stylex.props(shared.th)}>Name</th>
<th {...stylex.props(shared.th)}>URL</th>
<th {...stylex.props(shared.th)}>Enabled</th>
<th {...stylex.props(shared.th)}>Domains</th>
<th {...stylex.props(shared.th)}>Wildcards</th>
<th {...stylex.props(shared.th)}>Exceptions</th>
<th {...stylex.props(shared.th)}>Skipped regex</th>
<th {...stylex.props(shared.th)}>Skipped unsupported</th>
<th {...stylex.props(shared.th)}>Last updated</th>
</tr>
</thead>
<tbody>
{blocklists.map((b) => (
<tr key={b.id}>
<td {...stylex.props(shared.td)}>
<span {...stylex.props(styles.name)}>{b.name}</span>
{b.is_suggested && <span {...stylex.props(styles.badge)}>Suggested</span>}
</td>
<td {...stylex.props(shared.td, shared.mono)}>{b.url}</td>
<td {...stylex.props(shared.td)}>{String(b.enabled)}</td>
<td {...stylex.props(shared.td, shared.tabularNums)}>{b.domain_count}</td>
<td {...stylex.props(shared.td, shared.tabularNums)}>{b.wildcard_count}</td>
<td {...stylex.props(shared.td, shared.tabularNums)}>{b.exception_count}</td>
<td {...stylex.props(shared.td, shared.tabularNums)}>{b.skipped_regex_count}</td>
<td {...stylex.props(shared.td, shared.tabularNums)}>
{b.skipped_unsupported_count}
</td>
<td {...stylex.props(shared.td)}>
{b.last_updated === null ? "never" : formatTime(b.last_updated)}
</td>
</tr>
))}
</tbody>
</table>
<p {...stylex.props(config.note)}>{SKIPPED_NOTE}</p>
</div>
)}
</section>
);
}
function SourcesEditor({ blocklists }: { blocklists: Blocklist[] }) {
const queryClient = useQueryClient();
const { data: blocklists } = useSuspenseQuery(blocklistsQuery());
const [editing, setEditing] = useState<Blocklist | null>(null);
const [pendingDelete, setPendingDelete] = useState<Blocklist | null>(null);
@@ -92,13 +187,6 @@ export default function BlocklistsPage() {
const save = useMutation(blocklistUpdateMutation(queryClient));
const toggle = useMutation(blocklistUpdateMutation(queryClient));
const remove = useMutation(blocklistDeleteMutation(queryClient));
const updateNow = useMutation(blocklistsUpdateNowMutation(queryClient));
const sources = useRefreshStatus();
const namesById = new Map(blocklists.map((b) => [b.id, b.name]));
// The refresh below re-fetches the sources the config already declares, so
// it stays live in file mode; every other control here writes config.
const readOnly = useReadOnlyConfig();
async function submitForm(input: BlocklistInput) {
if (editing === null) {
@@ -126,30 +214,12 @@ export default function BlocklistsPage() {
const tableError = remove.error ?? toggle.error;
return (
<section>
<div {...stylex.props(styles.header)}>
<h1 {...stylex.props(styles.heading)}>Blocklists</h1>
<button
type="button"
onClick={() => updateNow.mutate()}
disabled={updateNow.isPending}
{...stylex.props(shared.primaryButton, shared.focusRing)}
>
{updateNow.isPending ? "Updating…" : "Update now"}
</button>
</div>
{updateNow.isSuccess && !updateNow.isPending && (
<p {...stylex.props(styles.done)} role="status">
Update completed; source status refreshed below.
</p>
)}
<InlineError error={updateNow.error} />
<div>
{blocklists.length === 0 ? (
<p {...stylex.props(styles.empty)}>No blocklist sources yet. Add one below.</p>
<p {...stylex.props(config.empty)}>No blocklist sources yet. Add one below.</p>
) : (
<div {...stylex.props(shared.tableWrap)}>
<table {...stylex.props(styles.table)}>
<table {...stylex.props(config.table)}>
<thead>
<tr>
<th {...stylex.props(shared.th)}>Name</th>
@@ -183,8 +253,7 @@ export default function BlocklistsPage() {
type="checkbox"
aria-label={`${b.name} enabled`}
checked={b.enabled}
disabled={toggle.isPending || readOnly}
title={readOnly ? READ_ONLY_HINT : undefined}
disabled={toggle.isPending}
onChange={() => toggleEnabled(b)}
{...stylex.props(shared.focusRing)}
/>
@@ -204,22 +273,19 @@ export default function BlocklistsPage() {
<button
type="button"
onClick={() => setEditing(b)}
disabled={readOnly}
title={readOnly ? READ_ONLY_HINT : undefined}
{...stylex.props(
shared.linkButton,
styles.dimWhenDisabled,
shared.focusRing,
)}
{...stylex.props(shared.linkButton, shared.focusRing)}
>
Edit
</button>
<button
type="button"
onClick={() => setPendingDelete(b)}
disabled={remove.isPending || readOnly}
title={readOnly ? READ_ONLY_HINT : undefined}
{...stylex.props(shared.dangerLinkButton, shared.focusRing)}
disabled={remove.isPending}
{...stylex.props(
shared.dangerLinkButton,
styles.dimWhenDisabled,
shared.focusRing,
)}
>
Delete
</button>
@@ -229,13 +295,7 @@ export default function BlocklistsPage() {
))}
</tbody>
</table>
<p {...stylex.props(styles.note)}>
Both Skipped columns count lines nxdns read and did not take. Skipped regex lines are patterns
nxdns accepts only from you adopt one you trust as a regex rule. Skipped unsupported lines are
syntax nxdns cannot translate into a DNS decision: cosmetic element hiding, browser-only
modifiers. A skipped unsupported count that dwarfs the domain count usually means the list is
written for a browser extension, and its DNS or hosts variant will block more here.
</p>
<p {...stylex.props(config.note)}>{SKIPPED_NOTE}</p>
</div>
)}
<InlineError error={tableError} />
@@ -244,14 +304,11 @@ export default function BlocklistsPage() {
key={editing?.id ?? "add"}
initial={editing ?? undefined}
busy={editing === null ? create.isPending : save.isPending}
readOnly={readOnly}
error={formError}
onSubmit={submitForm}
onCancel={editing === null ? undefined : () => setEditing(null)}
/>
<SourceStatusSection sources={sources} namesById={namesById} />
<ConfirmDialog
isOpen={pendingDelete !== null}
title="Delete blocklist"
@@ -264,6 +321,6 @@ export default function BlocklistsPage() {
onConfirm={confirmDelete}
onCancel={() => setPendingDelete(null)}
/>
</section>
</div>
);
}
@@ -0,0 +1,30 @@
import type { ReactNode } from "react";
import type { UseQueryResult } from "@tanstack/react-query";
import * as stylex from "@stylexjs/stylex";
import InlineError from "@/lib/InlineError";
import { styles as shared } from "@/ui/styles";
import { styles } from "./styles";
/**
* One panel's data, with the loading and error surfaces the fire-and-forget
* route loaders leave to the page. A configuration page holds several
* independent collections; each states its own condition instead of the whole
* page waiting on the slowest request.
*/
export default function QueryPanel<T>({
query,
children,
}: {
query: UseQueryResult<T, Error>;
children: (data: T) => ReactNode;
}) {
if (query.isPending) {
return (
<p role="status" {...stylex.props(styles.pending, shared.pulse)}>
Loading
</p>
);
}
if (query.isError) return <InlineError error={query.error} onRetry={() => void query.refetch()} />;
return <>{children(query.data)}</>;
}
@@ -1,5 +1,5 @@
import { useId, useState, type FormEvent } from "react";
import { useSuspenseQuery } from "@tanstack/react-query";
import { useQuery } from "@tanstack/react-query";
import * as stylex from "@stylexjs/stylex";
import {
localRecordCreateMutation,
@@ -12,9 +12,9 @@ import InlineError from "@/lib/InlineError";
import ConfirmDialog from "@/ui/ConfirmDialog";
import Select from "@/ui/Select";
import { useCrudForm } from "@/ui/useCrudForm";
import QueryPanel from "./QueryPanel";
import { styles as shared } from "@/ui/styles";
import { colors } from "@/ui/tokens.stylex";
import { READ_ONLY_HINT, useReadOnlyConfig } from "@/features/settings/authority";
const RTYPES: readonly LocalRecordType[] = ["A", "AAAA", "CNAME"];
const RTYPE_OPTIONS = RTYPES.map((rtype) => ({ value: rtype, label: rtype }));
@@ -93,14 +93,12 @@ const styles = stylex.create({
function RecordForm({
initial,
busy,
readOnly,
error,
onSubmit,
onCancel,
}: {
initial?: LocalRecord;
busy: boolean;
readOnly: boolean;
error: unknown;
onSubmit: (input: LocalRecordInput) => void;
onCancel: () => void;
@@ -174,12 +172,7 @@ function RecordForm({
/>
</div>
<div {...stylex.props(styles.buttonRow)}>
<button
type="submit"
disabled={busy || readOnly}
title={readOnly ? READ_ONLY_HINT : undefined}
{...stylex.props(shared.largePrimaryButton, shared.focusRing)}
>
<button type="submit" disabled={busy} {...stylex.props(shared.largePrimaryButton, shared.focusRing)}>
{busy ? "Saving…" : "Save"}
</button>
<button type="button" onClick={onCancel} {...stylex.props(shared.largeButton, shared.focusRing)}>
@@ -192,7 +185,7 @@ function RecordForm({
}
export default function RecordsTab() {
const records = useSuspenseQuery(localRecordsQuery()).data;
const query = useQuery(localRecordsQuery());
const {
create,
update,
@@ -211,7 +204,6 @@ export default function RecordsTab() {
remove: localRecordDeleteMutation,
confirmDelete: (record) => `Delete record "${record.name}"?`,
});
const readOnly = useReadOnlyConfig();
return (
<div>
@@ -220,8 +212,6 @@ export default function RecordsTab() {
<button
type="button"
onClick={() => openForm({ mode: "create" })}
disabled={readOnly}
title={readOnly ? READ_ONLY_HINT : undefined}
{...stylex.props(shared.largePrimaryButton, shared.focusRing)}
>
Add record
@@ -229,98 +219,92 @@ export default function RecordsTab() {
</div>
<InlineError error={remove.error} />
{form?.mode === "create" && (
<RecordForm
busy={create.isPending}
readOnly={readOnly}
error={create.error}
onSubmit={onSubmit}
onCancel={closeForm}
/>
<RecordForm busy={create.isPending} error={create.error} onSubmit={onSubmit} onCancel={closeForm} />
)}
<div {...stylex.props(shared.tableWrap)}>
<table {...stylex.props(styles.table)}>
<thead>
<tr {...stylex.props(styles.headRow)}>
<th scope="col" {...stylex.props(styles.headCell)}>
Name
</th>
<th scope="col" {...stylex.props(styles.headCell)}>
Type
</th>
<th scope="col" {...stylex.props(styles.headCell)}>
Value
</th>
<th scope="col" {...stylex.props(styles.headCell)}>
TTL
</th>
<th scope="col" {...stylex.props(styles.headCellLast)}>
<span {...stylex.props(shared.srOnly)}>Actions</span>
</th>
</tr>
</thead>
<tbody>
{records.length === 0 && (
<tr>
<td colSpan={5} {...stylex.props(styles.emptyCell)}>
No local records yet.
</td>
</tr>
)}
{records.map((record) => (
<tr key={record.id} {...stylex.props(styles.bodyRow)}>
{form?.mode === "edit" && form.entity.id === record.id ? (
<td colSpan={5}>
<RecordForm
initial={record}
busy={update.isPending}
readOnly={readOnly}
error={update.error}
onSubmit={onSubmit}
onCancel={closeForm}
/>
</td>
) : (
<>
<td {...stylex.props(styles.cell, shared.mono)}>{record.name}</td>
<td {...stylex.props(styles.cell)}>{record.rtype}</td>
<td {...stylex.props(styles.cell, shared.mono)}>{record.value}</td>
<td {...stylex.props(styles.cell)}>{record.ttl}</td>
<td {...stylex.props(styles.actionCell)}>
<button
type="button"
onClick={() => openForm({ mode: "edit", entity: record })}
disabled={readOnly}
title={readOnly ? READ_ONLY_HINT : undefined}
{...stylex.props(
shared.rowButton,
styles.dimWhenDisabled,
shared.focusRing,
)}
>
Edit
</button>
<button
type="button"
onClick={() => onDelete(record)}
disabled={remove.isPending || readOnly}
title={readOnly ? READ_ONLY_HINT : undefined}
{...stylex.props(
shared.rowButton,
styles.dangerText,
styles.dimWhenDisabled,
shared.focusRing,
)}
>
Delete
</button>
<QueryPanel query={query}>
{(records) => (
<div {...stylex.props(shared.tableWrap)}>
<table {...stylex.props(styles.table)}>
<thead>
<tr {...stylex.props(styles.headRow)}>
<th scope="col" {...stylex.props(styles.headCell)}>
Name
</th>
<th scope="col" {...stylex.props(styles.headCell)}>
Type
</th>
<th scope="col" {...stylex.props(styles.headCell)}>
Value
</th>
<th scope="col" {...stylex.props(styles.headCell)}>
TTL
</th>
<th scope="col" {...stylex.props(styles.headCellLast)}>
<span {...stylex.props(shared.srOnly)}>Actions</span>
</th>
</tr>
</thead>
<tbody>
{records.length === 0 && (
<tr>
<td colSpan={5} {...stylex.props(styles.emptyCell)}>
No local records yet.
</td>
</>
</tr>
)}
</tr>
))}
</tbody>
</table>
</div>
{records.map((record) => (
<tr key={record.id} {...stylex.props(styles.bodyRow)}>
{form?.mode === "edit" && form.entity.id === record.id ? (
<td colSpan={5}>
<RecordForm
initial={record}
busy={update.isPending}
error={update.error}
onSubmit={onSubmit}
onCancel={closeForm}
/>
</td>
) : (
<>
<td {...stylex.props(styles.cell, shared.mono)}>{record.name}</td>
<td {...stylex.props(styles.cell)}>{record.rtype}</td>
<td {...stylex.props(styles.cell, shared.mono)}>{record.value}</td>
<td {...stylex.props(styles.cell)}>{record.ttl}</td>
<td {...stylex.props(styles.actionCell)}>
<button
type="button"
onClick={() => openForm({ mode: "edit", entity: record })}
{...stylex.props(
shared.rowButton,
styles.dimWhenDisabled,
shared.focusRing,
)}
>
Edit
</button>
<button
type="button"
onClick={() => onDelete(record)}
disabled={remove.isPending}
{...stylex.props(
shared.rowButton,
styles.dangerText,
styles.dimWhenDisabled,
shared.focusRing,
)}
>
Delete
</button>
</td>
</>
)}
</tr>
))}
</tbody>
</table>
</div>
)}
</QueryPanel>
<ConfirmDialog
isOpen={pendingDelete !== null}
title="Delete record"
@@ -0,0 +1,47 @@
import { useMutation } from "@tanstack/react-query";
import * as stylex from "@stylexjs/stylex";
import InlineError from "@/lib/InlineError";
import { reloadCerts } from "@/lib/api";
import type { CertReloadOutcome, CertsReload } from "@/lib/types";
import { styles as shared } from "@/ui/styles";
import { styles } from "./styles";
function describe(name: string, outcome: CertReloadOutcome): string {
if (!outcome.enabled) return `${name}: not enabled`;
if (outcome.reloaded) return `${name}: reloaded`;
return `${name}: failed — ${outcome.error ?? "no reason given"}`;
}
/**
* A runtime action, not a configuration write: it re-reads the certificate
* files the running listeners already point at, so it stays enabled under
* every authority — including a file-managed process, where renewing a
* certificate is exactly the job that must not need a restart.
*
* The endpoint answers 200 even when a reload fails, per endpoint, because a
* failed reload leaves the previous certificate serving. So the outcome is
* rendered as a result, and only a transport or auth failure is an error.
*/
export default function ReloadCertsAction() {
const mutation = useMutation<CertsReload>({ mutationFn: reloadCerts });
const result = mutation.data;
return (
<div {...stylex.props(styles.actionRow)}>
<button
type="button"
onClick={() => mutation.mutate()}
disabled={mutation.isPending}
{...stylex.props(shared.button, shared.focusRing)}
>
{mutation.isPending ? "Reloading certificates…" : "Reload certificates"}
</button>
{result !== undefined && (
<p role="status" {...stylex.props(styles.success)}>
{describe("DoH", result.doh)}. {describe("DoT", result.dot)}.
</p>
)}
<InlineError error={mutation.error} />
</div>
);
}
@@ -0,0 +1,253 @@
import { fireEvent, screen, waitFor, within } from "@testing-library/react";
import { DATABASE, contentArea, renderPage, stubApi, type Call } from "./testFixtures";
/**
* Resolution in database mode: the upstream pool, the local records and the
* forward zones, each rehomed from its own page onto a tab of one.
*/
let calls: Call[];
afterEach(() => {
vi.unstubAllGlobals();
});
function writes(): Call[] {
return calls;
}
async function openResolution(tab?: string, options: Parameters<typeof stubApi>[1] = {}) {
calls = stubApi(DATABASE, options);
const suffix = tab === undefined ? "" : `?tab=${tab}`;
return renderPage(`/configuration/resolution${suffix}`, "Resolution");
}
/** The row Delete opens the dialog; the dialog's own Delete is the confirm. */
async function openDeleteDialog(index = 0) {
fireEvent.click(screen.getAllByRole("button", { name: "Delete" })[index]!);
return await screen.findByRole("alertdialog");
}
test("the upstream pool is the default tab and lists every field", async () => {
await openResolution();
expect(await screen.findByText("udp://1.1.1.1:53")).toBeTruthy();
expect(screen.getByText("tls://9.9.9.9:853")).toBeTruthy();
expect(screen.getByText("dns.quad9.net")).toBeTruthy();
expect((screen.getByLabelText("udp://1.1.1.1:53 enabled") as HTMLInputElement).checked).toBe(true);
expect((screen.getByLabelText("tls://9.9.9.9:853 enabled") as HTMLInputElement).checked).toBe(false);
expect(screen.getByRole("heading", { name: "Add upstream" })).toBeTruthy();
expect(screen.getByText(/applies to the next query/)).toBeTruthy();
});
test("adding an upstream posts every field", async () => {
await openResolution();
await screen.findByRole("heading", { name: "Add upstream" });
fireEvent.change(screen.getByLabelText("URL"), { target: { value: "udp://8.8.8.8:53" } });
fireEvent.change(screen.getByLabelText("Priority"), { target: { value: "150" } });
fireEvent.click(screen.getByRole("button", { name: "Add upstream" }));
await waitFor(() => expect(writes()).toHaveLength(1));
expect(writes()[0]).toEqual({
url: "/api/upstreams",
method: "POST",
body: { url: "udp://8.8.8.8:53", priority: 150, enabled: true, tls_name: "" },
});
});
test("an upstream write applies live, so the tab says nothing about a restart", async () => {
// The server rebuilds the pool on the write and echoes `restart_required:
// false`, so `restart_pending` stays down and silence is the whole report.
await openResolution(undefined, { responses: { "GET /api/config/status": () => DATABASE } });
await screen.findByRole("heading", { name: "Add upstream" });
fireEvent.change(screen.getByLabelText("URL"), { target: { value: "udp://8.8.8.8:53" } });
fireEvent.click(screen.getByRole("button", { name: "Add upstream" }));
await waitFor(() => expect(writes()).toHaveLength(1));
expect(screen.queryByText(/Restart nxdns to apply them/)).toBeNull();
expect(contentArea().textContent).not.toMatch(/restart/i);
});
test("toggling enabled resends the whole row", async () => {
await openResolution();
await screen.findByLabelText("tls://9.9.9.9:853 enabled");
fireEvent.click(screen.getByLabelText("tls://9.9.9.9:853 enabled"));
await waitFor(() => expect(writes()).toHaveLength(1));
expect(writes()[0]).toEqual({
url: "/api/upstreams/2",
method: "PUT",
body: { url: "tls://9.9.9.9:853", priority: 200, enabled: true, tls_name: "dns.quad9.net" },
});
});
test("upstream delete asks for confirmation and skips the request when cancelled", async () => {
await openResolution();
await screen.findByText("udp://1.1.1.1:53");
const dialog = await openDeleteDialog();
expect(dialog.textContent).toContain('Delete upstream "udp://1.1.1.1:53"?');
fireEvent.click(within(dialog).getByRole("button", { name: "Cancel" }));
await waitFor(() => expect(screen.queryByRole("alertdialog")).toBeNull());
expect(writes()).toHaveLength(0);
});
test("confirming the upstream delete dialog issues the DELETE", async () => {
await openResolution();
await screen.findByText("udp://1.1.1.1:53");
const dialog = await openDeleteDialog();
fireEvent.click(within(dialog).getByRole("button", { name: "Delete" }));
await waitFor(() => expect(writes()).toHaveLength(1));
expect(writes()[0]).toMatchObject({ method: "DELETE", url: "/api/upstreams/1" });
});
test("a 409 on create renders the conflict text inline", async () => {
await openResolution(undefined, {
onWrite: () =>
new Response(JSON.stringify({ error: "an upstream with that url already exists" }), {
status: 409,
headers: { "content-type": "application/json" },
}),
});
await screen.findByRole("heading", { name: "Add upstream" });
fireEvent.change(screen.getByLabelText("URL"), { target: { value: "udp://1.1.1.1:53" } });
fireEvent.click(screen.getByRole("button", { name: "Add upstream" }));
const alert = await screen.findByRole("alert");
expect(alert.textContent).toBe("an upstream with that url already exists");
});
test("a 409 on toggle renders the last-enabled conflict", async () => {
await openResolution(undefined, {
onWrite: () =>
new Response(JSON.stringify({ error: "the last enabled upstream cannot be disabled" }), {
status: 409,
headers: { "content-type": "application/json" },
}),
});
await screen.findByLabelText("udp://1.1.1.1:53 enabled");
fireEvent.click(screen.getByLabelText("udp://1.1.1.1:53 enabled"));
const alert = await screen.findByRole("alert");
expect(alert.textContent).toBe("the last enabled upstream cannot be disabled");
});
test("a 409 on delete renders the last-enabled conflict", async () => {
await openResolution(undefined, {
onWrite: () =>
new Response(JSON.stringify({ error: "the last enabled upstream cannot be removed" }), {
status: 409,
headers: { "content-type": "application/json" },
}),
});
await screen.findByText("udp://1.1.1.1:53");
const dialog = await openDeleteDialog();
fireEvent.click(within(dialog).getByRole("button", { name: "Delete" }));
const alert = await screen.findByRole("alert");
expect(alert.textContent).toBe("the last enabled upstream cannot be removed");
});
test("editing a row seeds the form and PUTs the replaced row", async () => {
await openResolution();
await screen.findByText("tls://9.9.9.9:853");
fireEvent.click(screen.getAllByRole("button", { name: "Edit" })[1]!);
await screen.findByRole("heading", { name: "Edit tls://9.9.9.9:853" });
expect((screen.getByLabelText("URL") as HTMLInputElement).value).toBe("tls://9.9.9.9:853");
expect((screen.getByLabelText("Priority") as HTMLInputElement).value).toBe("200");
expect((screen.getByLabelText("TLS name") as HTMLInputElement).value).toBe("dns.quad9.net");
fireEvent.change(screen.getByLabelText("Priority"), { target: { value: "10" } });
fireEvent.click(screen.getByRole("button", { name: "Save changes" }));
await waitFor(() => expect(writes()).toHaveLength(1));
expect(writes()[0]).toEqual({
url: "/api/upstreams/2",
method: "PUT",
body: { url: "tls://9.9.9.9:853", priority: 10, enabled: false, tls_name: "dns.quad9.net" },
});
await screen.findByRole("heading", { name: "Add upstream" });
});
test("the arrow keys move between tabs, and the panel follows", async () => {
await openResolution();
await screen.findByText("udp://1.1.1.1:53");
const tablist = screen.getByRole("tablist", { name: "Resolution" });
expect(screen.getByRole("tab", { name: "Upstreams" }).getAttribute("aria-selected")).toBe("true");
fireEvent.keyDown(tablist, { key: "ArrowRight" });
await waitFor(() =>
expect(screen.getByRole("tab", { name: "Records" }).getAttribute("aria-selected")).toBe("true"),
);
await screen.findByText("nas.lan.home");
fireEvent.keyDown(tablist, { key: "ArrowLeft" });
await waitFor(() =>
expect(screen.getByRole("tab", { name: "Upstreams" }).getAttribute("aria-selected")).toBe("true"),
);
await screen.findByText("udp://1.1.1.1:53");
});
test("creating a local record posts exactly the LocalRecordInput", async () => {
await openResolution("records");
await screen.findByText("nas.lan.home");
fireEvent.click(screen.getByRole("button", { name: "Add record" }));
fireEvent.change(screen.getByLabelText("Name"), { target: { value: "printer.lan.home" } });
// The record type is a RAC Select: open the listbox, then pick.
fireEvent.click(screen.getByRole("button", { name: /Type$/ }));
fireEvent.click(await screen.findByRole("option", { name: "AAAA" }));
fireEvent.change(screen.getByLabelText("Value"), { target: { value: "fd00::11" } });
fireEvent.click(screen.getByRole("button", { name: "Save" }));
await waitFor(() => expect(writes()).toHaveLength(1));
expect(writes()[0]).toMatchObject({
url: "/api/local-records",
method: "POST",
body: { name: "printer.lan.home", rtype: "AAAA", value: "fd00::11" },
});
});
test("the record delete dialog names the record and only deletes on confirm", async () => {
await openResolution("records");
await screen.findByText("nas.lan.home");
let dialog = await openDeleteDialog();
expect(dialog.textContent).toContain('Delete record "nas.lan.home"?');
fireEvent.click(within(dialog).getByRole("button", { name: "Cancel" }));
await waitFor(() => expect(screen.queryByRole("alertdialog")).toBeNull());
expect(writes()).toHaveLength(0);
dialog = await openDeleteDialog();
fireEvent.click(within(dialog).getByRole("button", { name: "Delete" }));
await waitFor(() => expect(writes()).toHaveLength(1));
expect(writes()[0]).toMatchObject({ method: "DELETE", url: "/api/local-records/1" });
});
test("the forward zone delete dialog names the zone and only deletes on confirm", async () => {
await openResolution("zones");
await screen.findByText("lan.home");
let dialog = await openDeleteDialog();
expect(dialog.textContent).toContain('Delete forward zone "lan.home"?');
fireEvent.click(within(dialog).getByRole("button", { name: "Cancel" }));
await waitFor(() => expect(screen.queryByRole("alertdialog")).toBeNull());
expect(writes()).toHaveLength(0);
dialog = await openDeleteDialog();
fireEvent.click(within(dialog).getByRole("button", { name: "Delete" }));
await waitFor(() => expect(writes()).toHaveLength(1));
expect(writes()[0]).toMatchObject({ method: "DELETE", url: "/api/forward-zones/1" });
});
@@ -0,0 +1,77 @@
import { useQuery } from "@tanstack/react-query";
import { useNavigate, useSearch } from "@tanstack/react-router";
import * as stylex from "@stylexjs/stylex";
import { forwardZonesQuery, localRecordsQuery } from "@/lib/queries";
import Tabs from "@/ui/Tabs";
import AuthorityGate from "./AuthorityGate";
import FileModeNote from "./FileModeNote";
import { RecordsReadOnly, ZonesReadOnly } from "./LocalReadOnly";
import QueryPanel from "./QueryPanel";
import RecordsTab from "./RecordsTab";
import UpstreamsTab from "./UpstreamsTab";
import ZonesTab from "./ZonesTab";
import { styles } from "./styles";
import type { ResolutionTab } from "./search";
function RecordsPanel() {
const records = useQuery(localRecordsQuery());
return (
<AuthorityGate>
{(status) =>
status.authority === "managed_file" ? (
<>
<FileModeNote path={status.path} />
<QueryPanel query={records}>{(rows) => <RecordsReadOnly records={rows} />}</QueryPanel>
</>
) : (
<RecordsTab />
)
}
</AuthorityGate>
);
}
function ZonesPanel() {
const zones = useQuery(forwardZonesQuery());
return (
<AuthorityGate>
{(status) =>
status.authority === "managed_file" ? (
<>
<FileModeNote path={status.path} />
<QueryPanel query={zones}>{(rows) => <ZonesReadOnly zones={rows} />}</QueryPanel>
</>
) : (
<ZonesTab />
)
}
</AuthorityGate>
);
}
/**
* Resolution: where a permitted name gets its answer. Three tabs in the order
* a query meets them — the pool that answers most of them, the records nxdns
* answers itself, and the zones it hands to another resolver.
*/
export default function ResolutionPage() {
const tab = useSearch({ from: "/shell/configuration/resolution" }).tab ?? "upstreams";
const navigate = useNavigate({ from: "/configuration/resolution" });
return (
<section>
<h1 {...stylex.props(styles.heading)}>Resolution</h1>
<p {...stylex.props(styles.intro)}>Where nxdns answers or forwards the names it permits.</p>
<Tabs
label="Resolution"
selectedKey={tab}
onSelectionChange={(key) => void navigate({ search: { tab: key as ResolutionTab } })}
tabs={[
{ id: "upstreams", label: "Upstreams", content: <UpstreamsTab /> },
{ id: "records", label: "Records", content: <RecordsPanel /> },
{ id: "zones", label: "Forward zones", content: <ZonesPanel /> },
]}
/>
</section>
);
}
@@ -0,0 +1,67 @@
import * as stylex from "@stylexjs/stylex";
import type { Settings } from "@/lib/types";
import DefinitionList, { type Definition } from "@/ui/DefinitionList";
import { colors } from "@/ui/tokens.stylex";
import { SECTIONS, sectionValues, type AnyFieldDef } from "./settingsSections";
import { styles as config } from "./styles";
const styles = stylex.create({
absent: {
color: colors.textMuted,
},
});
/** The field key as a sentence. The exact key travels beside it, so this is free to read well. */
export function humanize(key: string): string {
const spaced = key.replace(/_/g, " ");
return spaced.charAt(0).toUpperCase() + spaced.slice(1);
}
/**
* Values are shown as the file spells them: `true`, not "Yes". The reader's
* next step is editing that file, and a value they cannot type back is a
* translation they have to undo.
*/
function renderValue(value: unknown) {
if (typeof value === "boolean") return String(value);
if (typeof value === "number") return String(value);
if (value === "") return <span {...stylex.props(styles.absent)}>empty</span>;
return String(value);
}
/**
* The settings under file authority: definition lists, one per section, each
* scalar carrying its exact ZON key. No inputs, no Save — the file is the
* form.
*/
export default function SettingsDefinitions({ settings }: { settings: Settings }) {
return (
<>
{SECTIONS.map(({ section, title, fields }) => {
const values = sectionValues(settings, section);
const items: Definition[] = (fields as readonly AnyFieldDef[]).map((def) => ({
label: humanize(def.key),
zonKey: `${section}.${def.key}`,
value: renderValue(values[def.key]),
}));
if (section === "web") {
// Derived from whether a password hash is stored, so it has no key of
// its own (D13). Naming one would send the reader to a line that is
// not in the file.
items.push({
label: "Authentication",
value: settings.web.auth_enabled ? "required" : "not configured",
});
}
return (
<section key={section} {...stylex.props(config.panel)}>
<h2 {...stylex.props(config.panelHeading)}>{title}</h2>
<div {...stylex.props(config.note)}>
<DefinitionList items={items} />
</div>
</section>
);
})}
</>
);
}
@@ -0,0 +1,331 @@
import { useState, type FormEvent } from "react";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import * as stylex from "@stylexjs/stylex";
import InlineError from "@/lib/InlineError";
import { settingsPutMutation } from "@/lib/queries";
import { buildSettingsPatch } from "@/lib/settingsDiff";
import type { Settings, SettingsEnvelope } from "@/lib/types";
import Select from "@/ui/Select";
import { styles as shared } from "@/ui/styles";
import { colors } from "@/ui/tokens.stylex";
import { SECTIONS, sectionValues, type AnyFieldDef } from "./settingsSections";
import { styles as config } from "./styles";
const DARK = "@media (prefers-color-scheme: dark)";
const styles = stylex.create({
form: {
marginTop: "1rem",
maxWidth: "48rem",
},
/** A `fieldset` has a browser default border and padding; the layout wants neither. */
sections: {
display: "flex",
flexDirection: "column",
gap: "1.5rem",
borderStyle: "none",
margin: 0,
padding: 0,
},
section: {
borderRadius: "0.25rem",
borderWidth: 1,
borderStyle: "solid",
borderColor: colors.border,
padding: "1rem",
},
legend: {
paddingInline: "0.25rem",
fontSize: "0.875rem",
lineHeight: "1.25rem",
fontWeight: 600,
},
/** One column on a phone, two from `sm`. */
fieldGrid: {
display: "grid",
gap: "0.75rem",
gridTemplateColumns: {
default: "repeat(1, minmax(0, 1fr))",
"@media (min-width: 640px)": "repeat(2, minmax(0, 1fr))",
},
},
label: {
fontSize: "0.875rem",
lineHeight: "1.25rem",
color: {
default: "oklch(37% 0.013 285.805)",
[DARK]: "oklch(87.1% 0.006 286.286)",
},
},
checkboxRow: {
display: "flex",
alignItems: "center",
gap: "0.5rem",
},
field: {
display: "flex",
flexDirection: "column",
gap: "0.25rem",
},
fieldInput: {
borderRadius: "0.25rem",
borderWidth: 1,
borderStyle: "solid",
borderColor: colors.borderStrong,
backgroundColor: colors.surfaceRaised,
color: colors.text,
paddingInline: "0.5rem",
paddingBlock: "0.25rem",
fontSize: "0.875rem",
lineHeight: "1.25rem",
},
derived: {
color: colors.textMuted,
},
/** Both notices span the whole grid so the wrapped sentence stays readable. */
spanRow: {
gridColumn: { default: null, "@media (min-width: 640px)": "span 2 / span 2" },
fontSize: "0.875rem",
lineHeight: "1.25rem",
},
passwordNotice: {
color: { default: "oklch(55.5% 0.163 48.998)", [DARK]: "oklch(82.8% 0.189 84.429)" },
},
mismatchNotice: {
color: colors.danger,
},
submitRow: {
display: "flex",
alignItems: "center",
gap: "0.75rem",
},
save: {
borderStyle: "none",
borderRadius: "0.25rem",
paddingInline: "1rem",
paddingBlock: "0.375rem",
fontSize: "0.875rem",
lineHeight: "1.25rem",
fontWeight: 500,
backgroundColor: {
default: colors.primary,
":disabled": "oklch(87.1% 0.006 286.286)",
[DARK]: { default: colors.primary, ":disabled": "oklch(27.4% 0.006 286.033)" },
},
color: { default: colors.primaryText, ":disabled": "oklch(55.2% 0.016 285.938)" },
},
});
function FieldLabel({ id, text, restart }: { id: string; text: string; restart: boolean }) {
return (
<label htmlFor={id} {...stylex.props(styles.label)}>
{text}
{restart && <span {...stylex.props(config.restartTag)}>needs restart</span>}
</label>
);
}
function FieldRow({
section,
def,
value,
restart,
onChange,
}: {
section: string;
def: AnyFieldDef;
value: unknown;
restart: boolean;
onChange: (value: unknown) => void;
}) {
const id = `${section}.${def.key}`;
if (def.kind === "boolean") {
return (
<div {...stylex.props(styles.checkboxRow)}>
<input
id={id}
type="checkbox"
checked={value as boolean}
onChange={(e) => onChange(e.target.checked)}
{...stylex.props(shared.focusRing)}
/>
<FieldLabel id={id} text={def.key} restart={restart} />
</div>
);
}
if (Array.isArray(def.kind)) {
// `Select` renders its own `<label>` from a string, so the marker cannot be
// placed inside that label the way `FieldLabel` does it; it goes through the
// description slot instead, which puts it under the control and on the
// trigger's `aria-describedby`. An enum key that owes a restart owes it just
// as much as a number one, so it must be marked either way.
return (
<div {...stylex.props(styles.field)}>
<Select
variant="inline"
label={def.key}
value={value as string}
onChange={onChange}
options={def.kind.map((option) => ({ value: option, label: option }))}
description={restart ? "needs restart" : undefined}
/>
</div>
);
}
if (def.kind === "number") {
const numeric = value as number;
return (
<div {...stylex.props(styles.field)}>
<FieldLabel id={id} text={def.key} restart={restart} />
<input
id={id}
type="number"
value={Number.isNaN(numeric) ? "" : numeric}
onChange={(e) => onChange(e.target.valueAsNumber)}
{...stylex.props(styles.fieldInput, shared.focusRing)}
/>
</div>
);
}
return (
<div {...stylex.props(styles.field)}>
<FieldLabel id={id} text={def.key} restart={restart} />
<input
id={id}
type="text"
value={value as string}
onChange={(e) => onChange(e.target.value)}
{...stylex.props(styles.fieldInput, shared.focusRing)}
/>
</div>
);
}
/**
* The editable settings, in database mode only. Nothing here is ever disabled
* for authority: under file authority the page renders definitions instead, so
* this form is never drawn as a shell the reader cannot use.
*
* Which keys owe a restart is the server's answer, carried on the envelope's
* `restart_required` list; whether one is owed *now* is `restart_pending` on
* `/api/config/status`, which the shell notice reads.
*/
export default function SettingsForm({ envelope }: { envelope: SettingsEnvelope }) {
const queryClient = useQueryClient();
const mutation = useMutation(settingsPutMutation(queryClient));
// Frozen at mount and re-frozen on save: diffing against live query data would
// turn a background refetch's out-of-band changes into phantom user edits.
const [baseline, setBaseline] = useState<Settings>(() => structuredClone(envelope.settings));
const [edited, setEdited] = useState<Settings>(() => structuredClone(envelope.settings));
const [password, setPassword] = useState("");
const [confirm, setConfirm] = useState("");
const restartKeys = new Set(envelope.restart_required);
const passwordsMismatch = (password !== "" || confirm !== "") && password !== confirm;
const hasInvalidNumber = SECTIONS.some(({ section, fields }) => {
const values = sectionValues(edited, section);
return (fields as readonly AnyFieldDef[]).some(
(field) => field.kind === "number" && Number.isNaN(values[field.key]),
);
});
const patch = buildSettingsPatch(baseline, edited, password === "" ? undefined : password);
const saveDisabled = patch === null || passwordsMismatch || hasInvalidNumber || mutation.isPending;
function setField(section: keyof Settings, key: string, value: unknown): void {
setEdited((prev) => ({
...prev,
[section]: { ...sectionValues(prev, section), [key]: value },
}));
}
function handleSubmit(event: FormEvent): void {
event.preventDefault();
if (patch === null || passwordsMismatch || hasInvalidNumber) return;
mutation.mutate(patch, {
onSuccess: (saved) => {
setBaseline(structuredClone(saved.settings));
setEdited(structuredClone(saved.settings));
setPassword("");
setConfirm("");
},
});
}
return (
<form onSubmit={handleSubmit} {...stylex.props(styles.form)}>
<fieldset disabled={mutation.isPending} {...stylex.props(styles.sections)}>
{SECTIONS.map(({ section, title, fields }) => (
<fieldset key={section} {...stylex.props(styles.section)}>
<legend {...stylex.props(styles.legend)}>{title}</legend>
<div {...stylex.props(styles.fieldGrid)}>
{(fields as readonly AnyFieldDef[]).map((def) => (
<FieldRow
key={def.key}
section={section}
def={def}
value={sectionValues(edited, section)[def.key]}
restart={restartKeys.has(`${section}.${def.key}`)}
onChange={(value) => setField(section, def.key, value)}
/>
))}
{section === "web" && (
<>
<p {...stylex.props(styles.label)}>
Authentication:{" "}
{envelope.settings.web.auth_enabled ? "required" : "not configured"}{" "}
<span {...stylex.props(styles.derived)}>
(derived from whether a password is stored)
</span>
</p>
<div {...stylex.props(styles.field)}>
<label htmlFor="web.password" {...stylex.props(styles.label)}>
password
</label>
<input
id="web.password"
type="password"
autoComplete="new-password"
value={password}
onChange={(e) => setPassword(e.target.value)}
{...stylex.props(styles.fieldInput, shared.focusRing)}
/>
</div>
<div {...stylex.props(styles.field)}>
<label htmlFor="web.password_confirm" {...stylex.props(styles.label)}>
confirm password
</label>
<input
id="web.password_confirm"
type="password"
autoComplete="new-password"
value={confirm}
onChange={(e) => setConfirm(e.target.value)}
{...stylex.props(styles.fieldInput, shared.focusRing)}
/>
</div>
{password !== "" && (
<p {...stylex.props(styles.spanRow, styles.passwordNotice)}>
Changing the password signs out every session; you will be asked to log in
again.
</p>
)}
{passwordsMismatch && (
<p {...stylex.props(styles.spanRow, styles.mismatchNotice)}>
Passwords do not match.
</p>
)}
</>
)}
</div>
</fieldset>
))}
<div {...stylex.props(styles.submitRow)}>
<button type="submit" disabled={saveDisabled} {...stylex.props(styles.save, shared.focusRing)}>
{mutation.isPending ? "Saving…" : "Save"}
</button>
{mutation.isError && <InlineError error={mutation.error} />}
</div>
</fieldset>
</form>
);
}
@@ -0,0 +1,363 @@
import { act, fireEvent, screen, waitFor, within } from "@testing-library/react";
import { queryKeys } from "@/lib/queries";
import type { Settings, SettingsPatch } from "@/lib/types";
import { DATABASE, MANAGED_FILE, RESTART_REQUIRED_KEYS, baseSettings, renderPage, stubApi } from "./testFixtures";
/**
* System in database mode: the settings form, its diff contract, and the
* certificate reload that is a runtime action under both authorities.
*/
// What the server actually reports: the listener binds and `web.enabled`.
// Every other key applies live, so it carries no mark at all.
const RESTART_KEYS = RESTART_REQUIRED_KEYS;
let stored: Settings;
let putBodies: SettingsPatch[];
let putResponse: (() => Response | Promise<Response>) | null;
let restartPending: boolean;
function json(payload: unknown, status = 200): Response {
return new Response(JSON.stringify(payload), { status, headers: { "content-type": "application/json" } });
}
/** The server's echo: the patch merged into the stored settings, password excepted. */
function applyPatch(patch: SettingsPatch): void {
const target = stored as unknown as Record<string, Record<string, unknown>>;
for (const [section, fields] of Object.entries(patch)) {
for (const [key, value] of Object.entries(fields as Record<string, unknown>)) {
if (section === "web" && key === "password") continue;
target[section]![key] = value;
}
}
}
/** Mirrors apply.zig's table: only a listed key leaves the server owing a restart. */
function needsRestart(patch: SettingsPatch, keys: readonly string[]): boolean {
return Object.entries(patch).some(([section, fields]) =>
Object.keys(fields as Record<string, unknown>).some((key) => keys.includes(`${section}.${key}`)),
);
}
beforeEach(() => {
stored = baseSettings();
putBodies = [];
putResponse = null;
restartPending = false;
});
afterEach(() => {
vi.unstubAllGlobals();
});
async function openSystem(restartKeys: readonly string[] = RESTART_KEYS) {
stubApi(DATABASE, {
responses: {
"GET /api/config/status": () => ({ ...DATABASE, restart_pending: restartPending }),
"GET /api/settings": () => ({ settings: stored, restart_required: restartKeys }),
},
onWrite: (call) => {
if (call.url !== "/api/settings") return null;
const patch = call.body as SettingsPatch;
putBodies.push(patch);
if (putResponse !== null) return putResponse();
applyPatch(patch);
if (needsRestart(patch, restartKeys)) restartPending = true;
return json({ settings: stored, restart_required: restartKeys });
},
});
const router = await renderPage("/configuration/system", "System");
await screen.findByRole("button", { name: "Save" });
return router;
}
function saveButton(): HTMLButtonElement {
return screen.getByRole("button", { name: "Save" }) as HTMLButtonElement;
}
function restartNotice(): HTMLElement | null {
return screen.queryByText(/Saved changes are not running yet/);
}
test("no changes means Save is disabled, and authentication reads as derived", async () => {
await openSystem();
expect(saveButton().disabled).toBe(true);
const auth = screen.getByText(/^Authentication: required/);
expect(auth.textContent).toContain("derived from whether a password is stored");
});
test("a changed field enables Save and the PUT body is exactly the diff", async () => {
await openSystem();
const dns = screen.getByRole("group", { name: "DNS" });
fireEvent.change(within(dns).getByLabelText(/^port/), { target: { value: "5353" } });
expect(saveButton().disabled).toBe(false);
fireEvent.click(saveButton());
await waitFor(() => expect(putBodies).toHaveLength(1));
expect(putBodies[0]).toEqual({ dns: { port: 5353 } });
await waitFor(() => expect(saveButton().disabled).toBe(true));
});
test("a restart-required key is marked as one, from the envelope's list", async () => {
await openSystem();
// The DNS binds and the port are the section's whole share of the list;
// `rate_limit` and `rate_window_seconds` apply live and carry no mark.
const dns = screen.getByRole("group", { name: "DNS" });
expect(within(dns).getAllByText("needs restart")).toHaveLength(3);
const cache = screen.getByRole("group", { name: "Cache" });
expect(within(cache).queryByText("needs restart")).toBeNull();
});
test("every key the server applies live is drawn without restart messaging", async () => {
await openSystem();
// Silence is the report for a live key: no mark on the field, and editing
// one owes nothing afterwards either.
for (const title of ["Upstream", "Blocking", "Cache", "EDNS", "Logging", "Disk", "Blocklist Update"]) {
const section = screen.getByRole("group", { name: title });
expect(within(section).queryByText("needs restart")).toBeNull();
}
const logging = screen.getByRole("group", { name: "Logging" });
fireEvent.change(within(logging).getByLabelText("retention_days"), { target: { value: "14" } });
fireEvent.click(saveButton());
await waitFor(() => expect(putBodies).toHaveLength(1));
expect(putBodies[0]).toEqual({ logging: { retention_days: 14 } });
await waitFor(() => expect(saveButton().disabled).toBe(true));
expect(restartNotice()).toBeNull();
});
test("a port edit still owes a restart, and the shell says so", async () => {
await openSystem();
const dns = screen.getByRole("group", { name: "DNS" });
fireEvent.change(within(dns).getByLabelText(/^port/), { target: { value: "5353" } });
fireEvent.click(saveButton());
await waitFor(() => expect(putBodies).toHaveLength(1));
await screen.findByText(/Saved changes are not running yet/);
});
test("an enum-backed key on the list is marked too, not only text and number fields", async () => {
// No shipped restart-required key is enum-backed, but the list is the
// server's to change, so the `Select` rendering is pinned against one.
await openSystem(["logging.level"]);
const logging = screen.getByRole("group", { name: "Logging" });
// `logging.level` is a Select and `logging.output` is not on the list, so
// exactly one mark belongs to this section.
expect(within(logging).getAllByText("needs restart")).toHaveLength(1);
const marker = within(logging).getByText("needs restart");
const marked = marker.parentElement!;
const trigger = within(marked).getByRole("button", { name: /level$/ });
// Visible next to the control is not enough: the marker sits outside the
// label, so only `aria-describedby` carries it to a screen reader.
expect(marker.id).not.toBe("");
expect(trigger.getAttribute("aria-describedby")?.split(" ")).toContain(marker.id);
});
test("enum and boolean fields diff as their own types", async () => {
await openSystem();
const logging = screen.getByRole("group", { name: "Logging" });
// A RAC Select names its trigger with the current value and then the label,
// and carries the options only while the listbox is open.
fireEvent.click(within(logging).getByRole("button", { name: /level$/ }));
fireEvent.click(await screen.findByRole("option", { name: "debug" }));
await waitFor(() => expect(screen.queryByRole("listbox")).toBeNull());
fireEvent.click(within(logging).getByLabelText("hide_domains"));
fireEvent.click(saveButton());
await waitFor(() => expect(putBodies).toHaveLength(1));
expect(putBodies[0]).toEqual({ logging: { level: "debug", hide_domains: true } });
});
test("clearing a number field disables Save instead of sending NaN", async () => {
await openSystem();
const cache = screen.getByRole("group", { name: "Cache" });
fireEvent.change(within(cache).getByLabelText("size"), { target: { value: "" } });
expect(saveButton().disabled).toBe(true);
});
test("password flow: note shown, confirm required, PUT sends web.password, no restart notice", async () => {
await openSystem();
const web = screen.getByRole("group", { name: "Web" });
const passwordInput = within(web).getByLabelText("password") as HTMLInputElement;
const confirmInput = within(web).getByLabelText("confirm password") as HTMLInputElement;
expect(passwordInput.value).toBe("");
fireEvent.change(passwordInput, { target: { value: "hunter2" } });
expect(screen.getByText(/signs out every session/)).toBeTruthy();
expect(screen.getByText("Passwords do not match.")).toBeTruthy();
expect(saveButton().disabled).toBe(true);
fireEvent.change(confirmInput, { target: { value: "hunter2" } });
expect(screen.queryByText("Passwords do not match.")).toBeNull();
expect(saveButton().disabled).toBe(false);
fireEvent.click(saveButton());
await waitFor(() => expect(putBodies).toHaveLength(1));
expect(putBodies[0]).toEqual({ web: { password: "hunter2" } });
await waitFor(() => expect(passwordInput.value).toBe(""));
expect(confirmInput.value).toBe("");
// The password applies live, so the server never raises the flag.
expect(restartNotice()).toBeNull();
});
test("a patch of live keys alone leaves the server owing nothing", async () => {
await openSystem();
const web = screen.getByRole("group", { name: "Web" });
fireEvent.change(within(web).getByLabelText("session_ttl_hours"), { target: { value: "48" } });
fireEvent.change(within(web).getByLabelText("password"), { target: { value: "hunter2" } });
fireEvent.change(within(web).getByLabelText("confirm password"), { target: { value: "hunter2" } });
fireEvent.click(saveButton());
await waitFor(() => expect(putBodies).toHaveLength(1));
expect(putBodies[0]).toEqual({ web: { session_ttl_hours: 48, password: "hunter2" } });
await waitFor(() => expect(saveButton().disabled).toBe(true));
expect(restartNotice()).toBeNull();
});
test("the form is disabled while the PUT is pending and re-enabled after success", async () => {
await openSystem();
let resolvePut!: (response: Response) => void;
putResponse = () => new Promise<Response>((resolve) => (resolvePut = resolve));
const dns = screen.getByRole("group", { name: "DNS" });
const port = within(dns).getByLabelText(/^port/) as HTMLInputElement;
fireEvent.change(port, { target: { value: "5353" } });
fireEvent.click(saveButton());
await screen.findByRole("button", { name: "Saving…" });
expect(port.matches(":disabled")).toBe(true);
expect(screen.getByRole("group", { name: "Web" }).querySelector("#web\\.password")?.matches(":disabled")).toBe(
true,
);
applyPatch(putBodies[putBodies.length - 1]!);
resolvePut(json({ settings: stored, restart_required: RESTART_KEYS }));
await waitFor(() => expect(port.matches(":disabled")).toBe(false));
expect(saveButton().textContent).toBe("Save");
});
test("a 429 shows the rate-limit countdown from Retry-After", async () => {
await openSystem();
putResponse = () =>
new Response(JSON.stringify({ error: "too many requests" }), {
status: 429,
headers: { "content-type": "application/json", "Retry-After": "30" },
});
const dns = screen.getByRole("group", { name: "DNS" });
fireEvent.change(within(dns).getByLabelText(/^port/), { target: { value: "5353" } });
fireEvent.click(saveButton());
expect((await screen.findByRole("alert")).textContent).toBe("Rate limited. Try again in 30s.");
expect(restartNotice()).toBeNull();
});
test("a 400 validation error surfaces inline and owes no restart", async () => {
await openSystem();
putResponse = () => json({ error: "dns.port out of range" }, 400);
const dns = screen.getByRole("group", { name: "DNS" });
fireEvent.change(within(dns).getByLabelText(/^port/), { target: { value: "70000" } });
fireEvent.click(saveButton());
expect((await screen.findByRole("alert")).textContent).toBe("dns.port out of range");
expect(restartNotice()).toBeNull();
expect(saveButton().disabled).toBe(false);
});
test("a background refetch does not turn out-of-band changes into phantom patch entries", async () => {
const router = await openSystem();
const queryClient = router.options.context.queryClient;
const dns = screen.getByRole("group", { name: "DNS" });
fireEvent.change(within(dns).getByLabelText(/^port/), { target: { value: "5353" } });
// Someone else changes cache.size; a background refetch brings it in. The
// derived authentication line is read straight from the query data, so it
// witnesses that the refetch reached the component.
stored.cache.size = 99999;
stored.web.auth_enabled = false;
await act(async () => {
await queryClient.invalidateQueries({ queryKey: queryKeys.settings });
});
await waitFor(() => expect(screen.getByText(/^Authentication: not configured/)).toBeTruthy());
const cache = screen.getByRole("group", { name: "Cache" });
expect((within(cache).getByLabelText("size") as HTMLInputElement).value).toBe("10000");
fireEvent.click(saveButton());
await waitFor(() => expect(putBodies).toHaveLength(1));
expect(putBodies[0]).toEqual({ dns: { port: 5353 } });
});
test("saving re-freezes the baseline, so the next diff starts from the server echo", async () => {
await openSystem();
const dns = screen.getByRole("group", { name: "DNS" });
fireEvent.change(within(dns).getByLabelText(/^port/), { target: { value: "5353" } });
fireEvent.click(saveButton());
await waitFor(() => expect(putBodies).toHaveLength(1));
await waitFor(() => expect(saveButton().disabled).toBe(true));
fireEvent.change(within(dns).getByLabelText(/^port/), { target: { value: "5454" } });
fireEvent.click(saveButton());
await waitFor(() => expect(putBodies).toHaveLength(2));
expect(putBodies[1]).toEqual({ dns: { port: 5454 } });
});
test("Reload certificates reports each endpoint's outcome in database mode (D8)", async () => {
stubApi(DATABASE, {
responses: {
"POST /api/certs/reload": {
doh: { enabled: true, reloaded: true, error: null },
dot: { enabled: false, reloaded: false, error: null },
},
},
});
await renderPage("/configuration/system", "System");
fireEvent.click(screen.getByRole("button", { name: "Reload certificates" }));
const result = await screen.findByText(/DoH: reloaded/);
expect(result.textContent).toContain("DoT: not enabled");
});
test("Reload certificates works under file authority too, and states a failure (D8)", async () => {
stubApi(MANAGED_FILE, {
responses: {
"POST /api/certs/reload": {
doh: { enabled: true, reloaded: false, error: "cert.pem: no such file" },
dot: { enabled: true, reloaded: true, error: null },
},
},
});
await renderPage("/configuration/system", "System");
const button = screen.getByRole("button", { name: "Reload certificates" }) as HTMLButtonElement;
expect(button.disabled).toBe(false);
fireEvent.click(button);
const result = await screen.findByText(/DoH: failed/);
expect(result.textContent).toContain("cert.pem: no such file");
expect(result.textContent).toContain("DoT: reloaded");
});
test("a failed certificate reload request is an error, not an outcome", async () => {
stubApi(DATABASE, {
onWrite: (call) => (call.url === "/api/certs/reload" ? json({ error: "reload is busy" }, 409) : null),
});
await renderPage("/configuration/system", "System");
fireEvent.click(screen.getByRole("button", { name: "Reload certificates" }));
expect((await screen.findByRole("alert")).textContent).toBe("reload is busy");
});
@@ -0,0 +1,47 @@
import { useQuery } from "@tanstack/react-query";
import * as stylex from "@stylexjs/stylex";
import { settingsQuery } from "@/lib/queries";
import AuthorityGate from "./AuthorityGate";
import FileModeNote from "./FileModeNote";
import QueryPanel from "./QueryPanel";
import ReloadCertsAction from "./ReloadCertsAction";
import SettingsDefinitions from "./SettingsDefinitions";
import SettingsForm from "./SettingsForm";
import { styles } from "./styles";
/**
* System: what this process is running with. No tabs the settings registry
* is already sectioned, and splitting it further would hide the section the
* reader came for behind a guess about which tab holds it.
*
* "Reload certificates" sits above the gate: it is a runtime action on the
* running listeners, so it works whatever owns the configuration and whether
* or not `/api/config/status` has answered.
*/
export default function SystemPage() {
const settings = useQuery(settingsQuery());
return (
<section>
<h1 {...stylex.props(styles.heading)}>System</h1>
<p {...stylex.props(styles.intro)}>
The service, storage, logging, TLS and web settings this nxdns process is running with.
</p>
<ReloadCertsAction />
<AuthorityGate>
{(status) =>
status.authority === "managed_file" ? (
<>
<FileModeNote path={status.path} />
<QueryPanel query={settings}>
{(envelope) => <SettingsDefinitions settings={envelope.settings} />}
</QueryPanel>
</>
) : (
<QueryPanel query={settings}>{(envelope) => <SettingsForm envelope={envelope} />}</QueryPanel>
)
}
</AuthorityGate>
</section>
);
}
@@ -4,15 +4,12 @@ import InlineError from "@/lib/InlineError";
import type { Upstream, UpstreamInput } from "@/lib/types";
import { styles as shared } from "@/ui/styles";
import { colors } from "@/ui/tokens.stylex";
import { READ_ONLY_HINT } from "@/features/settings/authority";
const DEFAULT_PRIORITY = "100";
interface UpstreamFormProps {
initial?: Upstream;
busy: boolean;
/** File authority: the server answers 403, so the submit stays down. */
readOnly: boolean;
error: Error | null;
onSubmit: (input: UpstreamInput) => Promise<void>;
onCancel?: () => void;
@@ -61,7 +58,7 @@ const styles = stylex.create({
},
});
export default function UpstreamForm({ initial, busy, readOnly, error, onSubmit, onCancel }: UpstreamFormProps) {
export default function UpstreamForm({ initial, busy, error, onSubmit, onCancel }: UpstreamFormProps) {
const [url, setUrl] = useState(initial?.url ?? "");
const [priority, setPriority] = useState(initial === undefined ? DEFAULT_PRIORITY : String(initial.priority));
const [enabled, setEnabled] = useState(initial?.enabled ?? true);
@@ -145,12 +142,7 @@ export default function UpstreamForm({ initial, busy, readOnly, error, onSubmit,
Enabled
</label>
<div {...stylex.props(styles.actions)}>
<button
type="submit"
disabled={busy || readOnly}
title={readOnly ? READ_ONLY_HINT : undefined}
{...stylex.props(shared.primaryButton, shared.focusRing)}
>
<button type="submit" disabled={busy} {...stylex.props(shared.primaryButton, shared.focusRing)}>
{initial === undefined ? "Add upstream" : "Save changes"}
</button>
{onCancel !== undefined && (
@@ -1,40 +1,21 @@
import { useState } from "react";
import { useMutation, useQueryClient, useSuspenseQuery } from "@tanstack/react-query";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import * as stylex from "@stylexjs/stylex";
import InlineError from "@/lib/InlineError";
import { upstreamCreateMutation, upstreamDeleteMutation, upstreamUpdateMutation, upstreamsQuery } from "@/lib/queries";
import type { Upstream, UpstreamInput } from "@/lib/types";
import { raiseRestartBanner } from "../settings/restartBanner";
import UpstreamForm from "./UpstreamForm";
import ConfirmDialog from "@/ui/ConfirmDialog";
import { styles as shared } from "@/ui/styles";
import { colors } from "@/ui/tokens.stylex";
import { READ_ONLY_HINT, useReadOnlyConfig } from "@/features/settings/authority";
import AuthorityGate from "./AuthorityGate";
import FileModeNote from "./FileModeNote";
import QueryPanel from "./QueryPanel";
import UpstreamForm from "./UpstreamForm";
import { styles as config } from "./styles";
const INTRO = "The pool is rebuilt as you save, so an edit here applies to the next query.";
const styles = stylex.create({
heading: {
fontSize: "1.5rem",
lineHeight: "2rem",
fontWeight: 600,
},
intro: {
marginTop: "0.5rem",
maxWidth: "42rem",
fontSize: "0.875rem",
lineHeight: "1.25rem",
color: colors.textMuted,
},
empty: {
marginTop: "1rem",
color: colors.textMuted,
},
table: {
width: "100%",
minWidth: "max-content",
borderCollapse: "collapse",
fontSize: "0.875rem",
lineHeight: "1.25rem",
},
url: {
display: "block",
maxWidth: "18rem",
@@ -50,11 +31,79 @@ const styles = stylex.create({
dimWhenDisabled: {
opacity: { default: 1, ":disabled": 0.5 },
},
absent: {
color: colors.textMuted,
},
});
export default function UpstreamsPage() {
export default function UpstreamsTab() {
const upstreams = useQuery(upstreamsQuery());
return (
<AuthorityGate>
{(status) => (
<div>
<p {...stylex.props(config.intro)}>{INTRO}</p>
{status.authority === "managed_file" && <FileModeNote path={status.path} />}
<QueryPanel query={upstreams}>
{(rows) =>
status.authority === "managed_file" ? (
<UpstreamsReadOnly upstreams={rows} />
) : (
<UpstreamsEditor upstreams={rows} />
)
}
</QueryPanel>
</div>
)}
</AuthorityGate>
);
}
function UpstreamsReadOnly({ upstreams }: { upstreams: Upstream[] }) {
return (
<section {...stylex.props(config.panel)}>
<h2 {...stylex.props(config.panelHeading)}>
Upstream pool
<code {...stylex.props(shared.mono, config.panelKey)}>upstreams</code>
</h2>
{upstreams.length === 0 ? (
<p {...stylex.props(config.empty)}>The file declares no upstreams.</p>
) : (
<div {...stylex.props(shared.tableWrap)}>
<table {...stylex.props(config.table)}>
<thead>
<tr>
<th {...stylex.props(shared.th)}>URL</th>
<th {...stylex.props(shared.th)}>Priority</th>
<th {...stylex.props(shared.th)}>Enabled</th>
<th {...stylex.props(shared.th)}>TLS name</th>
</tr>
</thead>
<tbody>
{upstreams.map((u) => (
<tr key={u.id}>
<td {...stylex.props(shared.td, shared.mono)}>{u.url}</td>
<td {...stylex.props(shared.td, shared.tabularNums)}>{u.priority}</td>
<td {...stylex.props(shared.td)}>{String(u.enabled)}</td>
<td {...stylex.props(shared.td)}>
{u.tls_name === "" ? (
<span {...stylex.props(styles.absent)}>empty</span>
) : (
u.tls_name
)}
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</section>
);
}
function UpstreamsEditor({ upstreams }: { upstreams: Upstream[] }) {
const queryClient = useQueryClient();
const { data: upstreams } = useSuspenseQuery(upstreamsQuery());
const [editing, setEditing] = useState<Upstream | null>(null);
const [pendingDelete, setPendingDelete] = useState<Upstream | null>(null);
@@ -62,7 +111,6 @@ export default function UpstreamsPage() {
const save = useMutation(upstreamUpdateMutation(queryClient));
const toggle = useMutation(upstreamUpdateMutation(queryClient));
const remove = useMutation(upstreamDeleteMutation(queryClient));
const readOnly = useReadOnlyConfig();
async function submitForm(input: UpstreamInput) {
if (editing === null) {
@@ -71,22 +119,18 @@ export default function UpstreamsPage() {
await save.mutateAsync({ id: editing.id, input });
setEditing(null);
}
raiseRestartBanner();
}
function toggleEnabled(u: Upstream) {
toggle.mutate(
{
id: u.id,
input: { url: u.url, priority: u.priority, enabled: !u.enabled, tls_name: u.tls_name },
},
{ onSuccess: () => raiseRestartBanner() },
);
toggle.mutate({
id: u.id,
input: { url: u.url, priority: u.priority, enabled: !u.enabled, tls_name: u.tls_name },
});
}
function confirmDelete() {
if (pendingDelete === null) return;
remove.mutate(pendingDelete.id, { onSuccess: () => raiseRestartBanner() });
remove.mutate(pendingDelete.id);
setPendingDelete(null);
}
@@ -94,18 +138,12 @@ export default function UpstreamsPage() {
const tableError = remove.error ?? toggle.error;
return (
<section>
<h1 {...stylex.props(styles.heading)}>Upstreams</h1>
<p {...stylex.props(styles.intro)}>
The pool builds its clients at startup, so an edit here takes effect at the next restart. The Upstreams
row on Overview counts the running pool, not this list.
</p>
<div>
{upstreams.length === 0 ? (
<p {...stylex.props(styles.empty)}>No upstreams yet. Add one below.</p>
<p {...stylex.props(config.empty)}>No upstreams yet. Add one below.</p>
) : (
<div {...stylex.props(shared.tableWrap)}>
<table {...stylex.props(styles.table)}>
<table {...stylex.props(config.table)}>
<thead>
<tr>
<th {...stylex.props(shared.th)}>URL</th>
@@ -131,8 +169,7 @@ export default function UpstreamsPage() {
type="checkbox"
aria-label={`${u.url} enabled`}
checked={u.enabled}
disabled={toggle.isPending || readOnly}
title={readOnly ? READ_ONLY_HINT : undefined}
disabled={toggle.isPending}
onChange={() => toggleEnabled(u)}
{...stylex.props(shared.focusRing)}
/>
@@ -143,22 +180,19 @@ export default function UpstreamsPage() {
<button
type="button"
onClick={() => setEditing(u)}
disabled={readOnly}
title={readOnly ? READ_ONLY_HINT : undefined}
{...stylex.props(
shared.linkButton,
styles.dimWhenDisabled,
shared.focusRing,
)}
{...stylex.props(shared.linkButton, shared.focusRing)}
>
Edit
</button>
<button
type="button"
onClick={() => setPendingDelete(u)}
disabled={remove.isPending || readOnly}
title={readOnly ? READ_ONLY_HINT : undefined}
{...stylex.props(shared.dangerLinkButton, shared.focusRing)}
disabled={remove.isPending}
{...stylex.props(
shared.dangerLinkButton,
styles.dimWhenDisabled,
shared.focusRing,
)}
>
Delete
</button>
@@ -176,7 +210,6 @@ export default function UpstreamsPage() {
key={editing?.id ?? "add"}
initial={editing ?? undefined}
busy={editing === null ? create.isPending : save.isPending}
readOnly={readOnly}
error={formError}
onSubmit={submitForm}
onCancel={editing === null ? undefined : () => setEditing(null)}
@@ -194,6 +227,6 @@ export default function UpstreamsPage() {
onConfirm={confirmDelete}
onCancel={() => setPendingDelete(null)}
/>
</section>
</div>
);
}
@@ -1,5 +1,5 @@
import { useId, useState, type FormEvent } from "react";
import { useSuspenseQuery } from "@tanstack/react-query";
import { useQuery } from "@tanstack/react-query";
import * as stylex from "@stylexjs/stylex";
import {
forwardZoneCreateMutation,
@@ -11,9 +11,9 @@ import type { ForwardZone, ForwardZoneInput } from "@/lib/types";
import InlineError from "@/lib/InlineError";
import ConfirmDialog from "@/ui/ConfirmDialog";
import { useCrudForm } from "@/ui/useCrudForm";
import QueryPanel from "./QueryPanel";
import { styles as shared } from "@/ui/styles";
import { colors } from "@/ui/tokens.stylex";
import { READ_ONLY_HINT, useReadOnlyConfig } from "@/features/settings/authority";
const styles = stylex.create({
formHeading: {
@@ -89,14 +89,12 @@ const styles = stylex.create({
function ZoneForm({
initial,
busy,
readOnly,
error,
onSubmit,
onCancel,
}: {
initial?: ForwardZone;
busy: boolean;
readOnly: boolean;
error: unknown;
onSubmit: (input: ForwardZoneInput) => void;
onCancel: () => void;
@@ -142,12 +140,7 @@ function ZoneForm({
/>
</div>
<div {...stylex.props(styles.buttonRow)}>
<button
type="submit"
disabled={busy || readOnly}
title={readOnly ? READ_ONLY_HINT : undefined}
{...stylex.props(shared.largePrimaryButton, shared.focusRing)}
>
<button type="submit" disabled={busy} {...stylex.props(shared.largePrimaryButton, shared.focusRing)}>
{busy ? "Saving…" : "Save"}
</button>
<button type="button" onClick={onCancel} {...stylex.props(shared.largeButton, shared.focusRing)}>
@@ -160,7 +153,7 @@ function ZoneForm({
}
export default function ZonesTab() {
const zones = useSuspenseQuery(forwardZonesQuery()).data;
const query = useQuery(forwardZonesQuery());
const {
create,
update,
@@ -179,7 +172,6 @@ export default function ZonesTab() {
remove: forwardZoneDeleteMutation,
confirmDelete: (zone) => `Delete forward zone "${zone.zone}"?`,
});
const readOnly = useReadOnlyConfig();
return (
<div>
@@ -190,8 +182,6 @@ export default function ZonesTab() {
<button
type="button"
onClick={() => openForm({ mode: "create" })}
disabled={readOnly}
title={readOnly ? READ_ONLY_HINT : undefined}
{...stylex.props(shared.largePrimaryButton, shared.focusRing)}
>
Add zone
@@ -199,90 +189,84 @@ export default function ZonesTab() {
</div>
<InlineError error={remove.error} />
{form?.mode === "create" && (
<ZoneForm
busy={create.isPending}
readOnly={readOnly}
error={create.error}
onSubmit={onSubmit}
onCancel={closeForm}
/>
<ZoneForm busy={create.isPending} error={create.error} onSubmit={onSubmit} onCancel={closeForm} />
)}
<div {...stylex.props(shared.tableWrap)}>
<table {...stylex.props(styles.table)}>
<thead>
<tr {...stylex.props(styles.headRow)}>
<th scope="col" {...stylex.props(styles.headCell)}>
Zone
</th>
<th scope="col" {...stylex.props(styles.headCell)}>
Resolver
</th>
<th scope="col" {...stylex.props(styles.headCellLast)}>
<span {...stylex.props(shared.srOnly)}>Actions</span>
</th>
</tr>
</thead>
<tbody>
{zones.length === 0 && (
<tr>
<td colSpan={3} {...stylex.props(styles.emptyCell)}>
No forward zones yet.
</td>
</tr>
)}
{zones.map((zone) => (
<tr key={zone.id} {...stylex.props(styles.bodyRow)}>
{form?.mode === "edit" && form.entity.id === zone.id ? (
<td colSpan={3}>
<ZoneForm
initial={zone}
busy={update.isPending}
readOnly={readOnly}
error={update.error}
onSubmit={onSubmit}
onCancel={closeForm}
/>
</td>
) : (
<>
<td {...stylex.props(styles.cell, shared.mono)}>{zone.zone}</td>
<td {...stylex.props(styles.cell, shared.mono)}>{zone.resolver}</td>
<td {...stylex.props(styles.actionCell)}>
<button
type="button"
onClick={() => openForm({ mode: "edit", entity: zone })}
disabled={readOnly}
title={readOnly ? READ_ONLY_HINT : undefined}
{...stylex.props(
shared.rowButton,
styles.dimWhenDisabled,
shared.focusRing,
)}
>
Edit
</button>
<button
type="button"
onClick={() => onDelete(zone)}
disabled={remove.isPending || readOnly}
title={readOnly ? READ_ONLY_HINT : undefined}
{...stylex.props(
shared.rowButton,
styles.dangerText,
styles.dimWhenDisabled,
shared.focusRing,
)}
>
Delete
</button>
<QueryPanel query={query}>
{(zones) => (
<div {...stylex.props(shared.tableWrap)}>
<table {...stylex.props(styles.table)}>
<thead>
<tr {...stylex.props(styles.headRow)}>
<th scope="col" {...stylex.props(styles.headCell)}>
Zone
</th>
<th scope="col" {...stylex.props(styles.headCell)}>
Resolver
</th>
<th scope="col" {...stylex.props(styles.headCellLast)}>
<span {...stylex.props(shared.srOnly)}>Actions</span>
</th>
</tr>
</thead>
<tbody>
{zones.length === 0 && (
<tr>
<td colSpan={3} {...stylex.props(styles.emptyCell)}>
No forward zones yet.
</td>
</>
</tr>
)}
</tr>
))}
</tbody>
</table>
</div>
{zones.map((zone) => (
<tr key={zone.id} {...stylex.props(styles.bodyRow)}>
{form?.mode === "edit" && form.entity.id === zone.id ? (
<td colSpan={3}>
<ZoneForm
initial={zone}
busy={update.isPending}
error={update.error}
onSubmit={onSubmit}
onCancel={closeForm}
/>
</td>
) : (
<>
<td {...stylex.props(styles.cell, shared.mono)}>{zone.zone}</td>
<td {...stylex.props(styles.cell, shared.mono)}>{zone.resolver}</td>
<td {...stylex.props(styles.actionCell)}>
<button
type="button"
onClick={() => openForm({ mode: "edit", entity: zone })}
{...stylex.props(
shared.rowButton,
styles.dimWhenDisabled,
shared.focusRing,
)}
>
Edit
</button>
<button
type="button"
onClick={() => onDelete(zone)}
disabled={remove.isPending}
{...stylex.props(
shared.rowButton,
styles.dangerText,
styles.dimWhenDisabled,
shared.focusRing,
)}
>
Delete
</button>
</td>
</>
)}
</tr>
))}
</tbody>
</table>
</div>
)}
</QueryPanel>
<ConfirmDialog
isOpen={pendingDelete !== null}
title="Delete forward zone"
@@ -0,0 +1,225 @@
import { screen, waitFor, within } from "@testing-library/react";
import { CONFIG_PATH, DATABASE, MANAGED_FILE, contentArea, renderPage, renderRoute, stubApi } from "./testFixtures";
/**
* Authority is three-state, and the difference between the states is the whole
* point: an unresolved status is never treated as database mode, and file mode
* is a different rendering rather than the same forms with their controls
* turned off.
*/
const NEVER = new Promise<Response>(() => {});
/**
* Every button the file-mode configuration content is allowed to contain: the
* runtime actions, and the Retry an error surface offers. Anything else is a
* mutation control that should not have been rendered at all.
*/
const RUNTIME_BUTTONS = ["Update now", "Reload certificates", "Retry"];
afterEach(() => {
vi.unstubAllGlobals();
});
function mutationControls(): Element[] {
return [
...contentArea().querySelectorAll(
'input, textarea, select, [role="combobox"], [role="checkbox"], [contenteditable]',
),
];
}
function buttonLabels(): string[] {
return [...contentArea().querySelectorAll("button")].map((button) => (button.textContent ?? "").trim());
}
test("a pending status renders neither form nor definition list on Protection", async () => {
stubApi(DATABASE, { responses: { "GET /api/config/status": NEVER } });
await renderPage("/configuration/protection", "Protection");
expect(await screen.findByText(/which configuration source this server obeys/i)).toBeTruthy();
expect(mutationControls()).toHaveLength(0);
expect(screen.queryByRole("button", { name: "Create" })).toBeNull();
});
test("a pending status still leaves the runtime actions live (R3-4)", async () => {
stubApi(DATABASE, { responses: { "GET /api/config/status": NEVER } });
await renderPage("/configuration/system", "System");
const reload = (await screen.findByRole("button", { name: "Reload certificates" })) as HTMLButtonElement;
expect(reload.disabled).toBe(false);
// The settings form is not drawn behind it.
expect(screen.queryByRole("button", { name: "Save" })).toBeNull();
});
test("a pending status renders neither form nor definition list on Resolution", async () => {
stubApi(DATABASE, { responses: { "GET /api/config/status": NEVER } });
await renderPage("/configuration/resolution", "Resolution");
expect(await screen.findByText(/which configuration source this server obeys/i)).toBeTruthy();
expect(mutationControls()).toHaveLength(0);
expect(screen.queryByRole("button", { name: "Add upstream" })).toBeNull();
});
test("a failed status renders the error and a Retry, never editable forms", async () => {
stubApi(DATABASE, {
responses: { "GET /api/config/status": new Response(JSON.stringify({ error: "gone" }), { status: 404 }) },
});
await renderPage("/configuration/protection", "Protection");
await screen.findByText(/cannot say whether a file or the database owns/i);
expect(screen.getByRole("button", { name: "Retry" })).toBeTruthy();
expect(mutationControls()).toHaveLength(0);
});
test("a failed status renders the error and a Retry on Resolution too", async () => {
stubApi(DATABASE, {
responses: { "GET /api/config/status": new Response(JSON.stringify({ error: "gone" }), { status: 404 }) },
});
await renderPage("/configuration/resolution", "Resolution");
await screen.findByText(/cannot say whether a file or the database owns/i);
expect(screen.getByRole("button", { name: "Retry" })).toBeTruthy();
expect(mutationControls()).toHaveLength(0);
expect(screen.queryByRole("button", { name: "Add upstream" })).toBeNull();
});
test("a failed status keeps Update now enabled on the Sources tab", async () => {
stubApi(DATABASE, {
responses: { "GET /api/config/status": new Response(JSON.stringify({ error: "gone" }), { status: 404 }) },
});
await renderPage("/configuration/protection?tab=sources", "Protection");
await screen.findByText(/cannot say whether a file or the database owns/i);
const update = screen.getByRole("button", { name: "Update now" }) as HTMLButtonElement;
expect(update.disabled).toBe(false);
});
test("a failed status is announced by the shell on a page that is not configuration", async () => {
stubApi(DATABASE, {
responses: {
"GET /api/config/status": new Response(JSON.stringify({ error: "gone" }), { status: 404 }),
"GET /api/overview?period=24h": {
period: "24h",
since: 0,
until: 86400,
bucket_seconds: 1800,
totals: { queries: 0, blocked: 0, clients: 0, avg_response_time_us: null },
buckets: [],
clients: [],
other: [],
types: [],
routes: [],
coverage: { complete: true, available_since: 0 },
},
},
});
renderRoute("/overview");
await waitFor(() => expect(screen.getByText(/file authority and pending restarts cannot be shown/i)).toBeTruthy());
});
test("database authority renders the editable groups form", async () => {
stubApi(DATABASE);
await renderPage("/configuration/protection", "Protection");
expect(await screen.findByRole("button", { name: "Create" })).toBeTruthy();
expect(screen.getByLabelText("New group")).toBeTruthy();
expect(screen.queryByText(/loaded from/i)).toBeNull();
});
test("file authority renders definitions with their exact ZON keys, not a form", async () => {
stubApi(MANAGED_FILE);
await renderPage("/configuration/protection", "Protection");
const note = await screen.findByText(/are loaded from/i);
expect(note.textContent).toContain(CONFIG_PATH);
const detail = await screen.findByText("Safe search");
expect(within(detail).getByText("groups[].safe_search")).toBeTruthy();
expect(screen.queryByRole("button", { name: "Create" })).toBeNull();
});
test("file mode: Protection renders zero mutation controls (D12)", async () => {
stubApi(MANAGED_FILE);
await renderPage("/configuration/protection", "Protection");
await screen.findByText("groups[].safe_search");
expect(mutationControls()).toHaveLength(0);
for (const label of buttonLabels()) expect(RUNTIME_BUTTONS).toContain(label);
});
test("file mode: the Sources tab shows the catalogue with its key and only Update now", async () => {
stubApi(MANAGED_FILE);
await renderPage("/configuration/protection?tab=sources", "Protection");
await screen.findByText("blocklist_sources");
expect(mutationControls()).toHaveLength(0);
expect(buttonLabels()).toEqual(["Update now"]);
});
test("file mode: the catalogue keeps provenance and both skipped counters", async () => {
stubApi(MANAGED_FILE);
await renderPage("/configuration/protection?tab=sources", "Protection");
await screen.findByText("blocklist_sources");
// Trackers is the suggested source, and the one with skipped lines: hiding
// either fact under file authority would hide a parse failure.
const row = screen.getByText("Trackers").closest("tr")!;
expect(within(row).getByText("Suggested")).toBeTruthy();
expect(screen.getByRole("columnheader", { name: "Skipped regex" })).toBeTruthy();
expect(screen.getByRole("columnheader", { name: "Skipped unsupported" })).toBeTruthy();
const cells = [...row.querySelectorAll("td")].map((cell) => cell.textContent);
expect(cells).toContain("3");
expect(cells).toContain("4");
expect(
screen.getByText(/Skipped unsupported lines are syntax nxdns cannot translate into a DNS decision/),
).toBeTruthy();
});
test("file mode: the Resolution upstream pool is a table with no controls", async () => {
stubApi(MANAGED_FILE);
await renderPage("/configuration/resolution", "Resolution");
await screen.findByText("upstreams");
expect(mutationControls()).toHaveLength(0);
expect(buttonLabels()).toEqual([]);
});
test("file mode: the Records tab is a table with no controls", async () => {
stubApi(MANAGED_FILE);
await renderPage("/configuration/resolution?tab=records", "Resolution");
await screen.findByText("local_records");
expect(mutationControls()).toHaveLength(0);
expect(buttonLabels()).toEqual([]);
});
test("file mode: the Forward zones tab is a table with no controls", async () => {
stubApi(MANAGED_FILE);
await renderPage("/configuration/resolution?tab=zones", "Resolution");
await screen.findByText("forward_zones");
expect(mutationControls()).toHaveLength(0);
expect(buttonLabels()).toEqual([]);
});
test("file mode: System renders scalars as definitions and keeps Reload certificates", async () => {
stubApi(MANAGED_FILE);
await renderPage("/configuration/system", "System");
const retention = await screen.findByText("Retention days");
expect(within(retention).getByText("logging.retention_days")).toBeTruthy();
expect(mutationControls()).toHaveLength(0);
expect(buttonLabels()).toEqual(["Reload certificates"]);
});
test("file mode: authentication is a derived status with no invented key (D13)", async () => {
stubApi(MANAGED_FILE);
await renderPage("/configuration/system", "System");
const auth = await screen.findByText("Authentication");
expect(auth.textContent).toBe("Authentication");
expect(within(auth).queryByText(/web\.auth_enabled/)).toBeNull();
expect(screen.queryByText("web.auth_enabled")).toBeNull();
});
@@ -0,0 +1,49 @@
import { useQuery } from "@tanstack/react-query";
import { configStatusQuery } from "@/lib/queries";
import type { ConfigStatus } from "@/lib/types";
/**
* Configuration authority as the UI must treat it: three states, never two.
*
* `undefined` is not database mode. Until `/api/config/status` answers, the
* running process may be file-managed, and a form rendered on that guess
* invites edits the server will reject. So a page shows neither an editable
* form nor a definition list until the query resolves, and a failed query is
* an explicit error with a way to retry.
*/
export type Authority =
| { state: "pending" }
| { state: "failed"; error: unknown; retry: () => void }
| { state: "resolved"; status: ConfigStatus };
/**
* The running server's configuration status. Every page may call this it is
* the shared `["configStatus"]` key, so one subscription serves them all from
* cache.
*/
export function useAuthority(): Authority {
const query = useQuery(configStatusQuery());
if (query.isPending) return { state: "pending" };
if (query.isError) {
return {
state: "failed",
error: query.error,
retry: () => void query.refetch(),
};
}
return { state: "resolved", status: query.data };
}
/**
* True unless the server has said the database owns the configuration.
*
* The lock is global and it fails closed: pending, failed and `managed_file`
* all read as locked, because only a resolved database authority proves a
* configuration mutation can succeed. Runtime actions pause, update now,
* reload certificates, deleting an observed client, login and logout do not
* consult it; they work under every authority.
*/
export function useReadOnlyConfig(): boolean {
const authority = useAuthority();
return !(authority.state === "resolved" && authority.status.authority === "database");
}
@@ -0,0 +1,98 @@
import { act, fireEvent, screen, waitFor } from "@testing-library/react";
import { createAppRouter } from "@/routes";
import { validateGroupId, validateProtectionSearch, validateResolutionSearch } from "@/features/configuration/search";
import { DATABASE, renderPage, stubApi } from "./testFixtures";
/**
* The configuration URL is the applied state: which page, which tab, which
* group. A view of a page is a link, and the back button walks what the reader
* chose rather than what the page corrected on their behalf.
*/
afterEach(() => {
vi.unstubAllGlobals();
});
test("the six resource routes are gone, with no alias left behind", () => {
const paths = new Set(Object.keys(createAppRouter().routesByPath));
for (const gone of ["/groups", "/blocklists", "/rules", "/local-dns", "/upstreams", "/settings"]) {
expect(paths.has(gone)).toBe(false);
}
for (const kept of ["/configuration/protection", "/configuration/resolution", "/configuration/system"]) {
expect(paths.has(kept)).toBe(true);
}
// No landing route either: `/configuration` is not a page.
expect(paths.has("/configuration")).toBe(false);
});
test("an unknown tab falls back to the page default rather than an empty panel", () => {
expect(validateProtectionSearch({ tab: "upstreams" }).tab).toBe("groups");
expect(validateProtectionSearch({}).tab).toBe("groups");
expect(validateResolutionSearch({ tab: "sources" }).tab).toBe("upstreams");
expect(validateResolutionSearch({ tab: "zones" }).tab).toBe("zones");
});
test("a group id is a positive integer or nothing", () => {
expect(validateGroupId(3)).toBe(3);
expect(validateGroupId(0)).toBeUndefined();
expect(validateGroupId(-1)).toBeUndefined();
expect(validateGroupId(1.5)).toBeUndefined();
expect(validateGroupId("2")).toBeUndefined();
});
test("an unknown group falls back to the first one and rewrites the URL in place", async () => {
stubApi(DATABASE);
const router = await renderPage("/configuration/protection?group=99", "Protection");
await waitFor(() => expect(router.state.location.search.group).toBe(1));
await screen.findByRole("heading", { name: "default", level: 2 });
// `replace`: the corrected address did not become a place to go back to.
expect(router.history.length).toBe(1);
});
test("selecting a group pushes a history entry the back button walks", async () => {
stubApi(DATABASE);
const router = await renderPage("/configuration/protection", "Protection");
await waitFor(() => expect(router.state.location.search.group).toBe(1));
fireEvent.click(screen.getByRole("link", { name: "kids" }));
await waitFor(() => expect(router.state.location.search.group).toBe(2));
await screen.findByRole("heading", { name: "kids", level: 2 });
act(() => router.history.back());
await waitFor(() => expect(router.state.location.search.group).toBe(1));
});
test("the selected group survives a tab change, and the change is a history entry", async () => {
stubApi(DATABASE);
const router = await renderPage("/configuration/protection?group=2", "Protection");
await screen.findByRole("heading", { name: "kids", level: 2 });
fireEvent.click(screen.getByRole("tab", { name: "Sources" }));
await screen.findByRole("button", { name: "Update now" });
expect(router.state.location.search).toEqual({ tab: "sources", group: 2 });
act(() => router.history.back());
await waitFor(() => expect(router.state.location.search.tab).toBe("groups"));
expect(router.state.location.search.group).toBe(2);
await screen.findByRole("heading", { name: "kids", level: 2 });
});
test("the Resolution tab is URL state too", async () => {
stubApi(DATABASE);
const router = await renderPage("/configuration/resolution", "Resolution");
fireEvent.click(screen.getByRole("tab", { name: "Forward zones" }));
await waitFor(() => expect(router.state.location.search.tab).toBe("zones"));
await screen.findByRole("button", { name: "Add zone" });
});
test("the loaders are started, not awaited: the page renders while a collection is in flight", async () => {
// Groups never answers. If the loader were awaited the navigation would hang
// and neither the heading nor the tabs would ever paint.
stubApi(DATABASE, { responses: { "GET /api/groups": new Promise<Response>(() => {}) } });
await renderPage("/configuration/protection", "Protection");
expect(screen.getByRole("tab", { name: "Sources" })).toBeTruthy();
expect(await screen.findByText("Loading…")).toBeTruthy();
});
@@ -0,0 +1,59 @@
/**
* The configuration pages' URL state, validated as pure functions so each
* route's `validateSearch` stays a one-liner and every rejection is testable
* without a router.
*
* A tab that is not one of the page's tabs falls back to that page's default:
* a hand-typed `?tab=upstreams` on Protection opens Protection's first tab
* rather than an empty panel.
*/
export const PROTECTION_TABS = ["groups", "sources"] as const;
export type ProtectionTab = (typeof PROTECTION_TABS)[number];
export const RESOLUTION_TABS = ["upstreams", "records", "zones"] as const;
export type ResolutionTab = (typeof RESOLUTION_TABS)[number];
/**
* Both fields are optional so a link to the page need not spell out a tab it
* does not care about the same shape Overview's `period` uses. Validation
* still resolves an unknown tab to the page default, so a *rendered* page
* always has one.
*/
export interface ProtectionSearch {
tab?: ProtectionTab;
/**
* The selected group. Absent until the page resolves one, which it then
* writes back so a view of the page is a link.
*/
group?: number;
}
export interface ResolutionSearch {
tab?: ResolutionTab;
}
function validateTab<T extends string>(options: readonly T[], value: unknown, fallback: T): T {
return options.includes(value as T) ? (value as T) : fallback;
}
/**
* A group row id. Ids are positive integers, so anything else a fraction, a
* string, a zero is not an id that could ever exist and becomes `undefined`.
* An id that is well-formed but unknown is a different case: the page has to
* load the groups before it can tell, so it falls back there, not here.
*/
export function validateGroupId(value: unknown): number | undefined {
return Number.isSafeInteger(value) && (value as number) > 0 ? (value as number) : undefined;
}
export function validateProtectionSearch(search: Record<string, unknown>): ProtectionSearch {
return {
tab: validateTab(PROTECTION_TABS, search["tab"], "groups"),
group: validateGroupId(search["group"]),
};
}
export function validateResolutionSearch(search: Record<string, unknown>): ResolutionSearch {
return { tab: validateTab(RESOLUTION_TABS, search["tab"], "upstreams") };
}
@@ -0,0 +1,132 @@
import type { Settings } from "@/lib/types";
/**
* The settings registry. One list drives both renderings: the editable form
* builds a control per field, the file-mode page builds a definition per
* field, and neither can drift from the other or from `Settings`.
*/
export interface FieldDef<S extends keyof Settings> {
key: keyof Settings[S] & string;
kind: "number" | "text" | "boolean" | readonly string[];
}
export interface SectionDef<S extends keyof Settings> {
section: S;
title: string;
fields: readonly FieldDef<S>[];
}
/** Binds each section's field keys to that section's Settings type at definition. */
function defineSection<S extends keyof Settings>(def: SectionDef<S>): SectionDef<S> {
return def;
}
/** The registry read back as a heterogeneous list, once the per-section binding has been proven. */
export type AnyFieldDef = { [S in keyof Settings]: FieldDef<S> }[keyof Settings];
export type AnySectionDef = { [S in keyof Settings]: SectionDef<S> }[keyof Settings];
/**
* A section's values as a string-keyed view. The keys are proven against
* `Settings[S]` where each section is defined; iterating the heterogeneous
* registry loses that correlation, so consumption widens here in one place.
*/
export function sectionValues(settings: Settings, section: keyof Settings): Record<string, unknown> {
return settings[section] as Record<string, unknown>;
}
const TLS_FIELDS: readonly FieldDef<"doh_server" | "dot_server">[] = [
{ key: "enabled", kind: "boolean" },
{ key: "bind", kind: "text" },
{ key: "port", kind: "number" },
{ key: "cert_path", kind: "text" },
{ key: "key_path", kind: "text" },
];
export const SECTIONS: readonly AnySectionDef[] = [
defineSection({
section: "upstream",
title: "Upstream",
fields: [
{ key: "attempt_timeout_ms", kind: "number" },
{ key: "read_timeout_ms", kind: "number" },
{ key: "total_timeout_ms", kind: "number" },
],
}),
defineSection({
section: "dns",
title: "DNS",
fields: [
{ key: "bind_ipv4", kind: "text" },
{ key: "bind_ipv6", kind: "text" },
{ key: "port", kind: "number" },
{ key: "rate_limit", kind: "number" },
{ key: "rate_window_seconds", kind: "number" },
],
}),
defineSection({
section: "blocking",
title: "Blocking",
fields: [
{ key: "response", kind: ["zero", "nxdomain"] },
{ key: "ttl", kind: "number" },
],
}),
defineSection({
section: "cache",
title: "Cache",
fields: [
{ key: "size", kind: "number" },
{ key: "negative_ttl_max", kind: "number" },
],
}),
defineSection({
section: "web",
title: "Web",
fields: [
{ key: "enabled", kind: "boolean" },
{ key: "bind", kind: "text" },
{ key: "port", kind: "number" },
{ key: "session_ttl_hours", kind: "number" },
{ key: "api_rate_limit_per_min", kind: "number" },
{ key: "api_localhost_exempt", kind: "boolean" },
{ key: "sse_max_connections_per_ip", kind: "number" },
{ key: "trusted_proxies", kind: "text" },
],
}),
defineSection({ section: "doh_server", title: "DoH Server", fields: TLS_FIELDS }),
defineSection({ section: "dot_server", title: "DoT Server", fields: TLS_FIELDS }),
defineSection({ section: "edns", title: "EDNS", fields: [{ key: "ecs_mode", kind: ["strip", "forward"] }] }),
defineSection({
section: "logging",
title: "Logging",
fields: [
{ key: "level", kind: ["error", "warn", "info", "debug"] },
{ key: "retention_days", kind: "number" },
{ key: "query_log_buffer_max", kind: "number" },
{ key: "query_log_flush_interval_s", kind: "number" },
{ key: "hide_domains", kind: "boolean" },
{ key: "hide_client_ips", kind: "boolean" },
{ key: "output", kind: ["stderr", "syslog", "file"] },
{ key: "file_path", kind: "text" },
{ key: "max_size_mb", kind: "number" },
{ key: "max_files", kind: "number" },
],
}),
defineSection({
section: "disk",
title: "Disk",
fields: [
{ key: "min_free_mb", kind: "number" },
{ key: "warn_free_mb", kind: "number" },
],
}),
defineSection({
section: "blocklist_update",
title: "Blocklist Update",
fields: [
{ key: "enabled", kind: "boolean" },
{ key: "interval_hours", kind: "number" },
],
}),
];
+142
View File
@@ -0,0 +1,142 @@
/**
* The vocabulary the three configuration pages share. Both renderings the
* editable forms and the file-mode definition lists sit on the same panels
* and headings, so the page keeps its shape when authority changes.
*/
import * as stylex from "@stylexjs/stylex";
import { colors } from "@/ui/tokens.stylex";
export const styles = stylex.create({
heading: {
fontSize: "1.5rem",
lineHeight: "2rem",
fontWeight: 600,
},
intro: {
marginTop: "0.25rem",
maxWidth: "48rem",
fontSize: "0.875rem",
lineHeight: "1.25rem",
color: colors.textMuted,
},
panel: {
marginTop: "1rem",
borderRadius: "0.25rem",
borderWidth: 1,
borderStyle: "solid",
borderColor: colors.border,
padding: "1rem",
},
panelHeading: {
fontSize: "1.125rem",
lineHeight: "1.75rem",
fontWeight: 500,
},
/** The collection's own key in the configuration file, beside its heading. */
panelKey: {
marginLeft: "0.5rem",
fontSize: "0.75rem",
lineHeight: "1rem",
fontWeight: 400,
color: colors.textMuted,
},
note: {
marginTop: "0.5rem",
fontSize: "0.875rem",
lineHeight: "1.25rem",
color: colors.textMuted,
},
/** The file-mode page note: where edits happen, and what applies them. */
fileNote: {
marginTop: "1rem",
borderRadius: "0.25rem",
borderWidth: 1,
borderStyle: "solid",
borderColor: colors.border,
backgroundColor: colors.surfaceHover,
paddingInline: "0.75rem",
paddingBlock: "0.5rem",
fontSize: "0.875rem",
lineHeight: "1.25rem",
color: colors.textSecondary,
},
table: {
width: "100%",
minWidth: "max-content",
borderCollapse: "collapse",
fontSize: "0.875rem",
lineHeight: "1.25rem",
},
empty: {
marginTop: "0.5rem",
color: colors.textMuted,
},
/** Master/detail: the group list beside the selected group. */
split: {
marginTop: "1rem",
display: "grid",
gap: "1rem",
gridTemplateColumns: {
default: "repeat(1, minmax(0, 1fr))",
"@media (min-width: 900px)": "16rem 1fr",
},
alignItems: "start",
},
masterList: {
display: "flex",
flexDirection: "column",
gap: "0.25rem",
},
masterLink: {
display: "block",
borderRadius: "0.25rem",
paddingInline: "0.75rem",
paddingBlock: "0.375rem",
fontSize: "0.875rem",
lineHeight: "1.25rem",
textDecorationLine: "none",
color: colors.textSecondary,
backgroundColor: { default: "transparent", ":hover": colors.surfaceHover },
},
masterLinkActive: {
backgroundColor: colors.surfaceHover,
color: colors.text,
fontWeight: 500,
},
actionRow: {
marginTop: "1rem",
display: "flex",
flexWrap: "wrap",
alignItems: "center",
gap: "0.75rem",
},
success: {
fontSize: "0.875rem",
lineHeight: "1.25rem",
color: colors.primaryOnSurface,
},
/** The authority error state: no forms, no definition list, one way forward. */
blocked: {
marginTop: "1rem",
borderRadius: "0.25rem",
borderWidth: 1,
borderStyle: "solid",
borderColor: colors.warnBorder,
backgroundColor: colors.warnSurface,
color: colors.warnText,
padding: "1rem",
fontSize: "0.875rem",
lineHeight: "1.25rem",
},
pending: {
marginTop: "1rem",
color: colors.textMuted,
},
restartTag: {
marginLeft: "0.375rem",
fontSize: "0.75rem",
lineHeight: "1rem",
color: colors.textMuted,
},
});
@@ -0,0 +1,272 @@
/**
* The fixtures and the stubbed API the configuration tests share.
*
* All three pages read the same handful of collections plus
* `/api/config/status`, so a per-file copy of the stub would be five copies of
* one contract drifting apart. Test-only: nothing in `src` imports it, so it
* never reaches the bundle.
*/
import { render, screen } from "@testing-library/react";
import { QueryClientProvider } from "@tanstack/react-query";
import { RouterProvider, createMemoryHistory } from "@tanstack/react-router";
import { AuthProvider } from "@/auth/store";
import { health } from "@/lib/healthFixture";
import { createQueryClient } from "@/lib/queryClient";
import { createAppRouter } from "@/routes";
import { sample_get_settings } from "@/lib/contractSamples.gen";
import type { ConfigStatus, Settings } from "@/lib/types";
export const CONFIG_PATH = "/etc/nxdns/config.zon";
export const RECONCILED_AT = 1754899200;
export const DATABASE: ConfigStatus = {
authority: "database",
path: null,
reconciled_at: null,
restart_pending: false,
};
export const MANAGED_FILE: ConfigStatus = {
authority: "managed_file",
path: CONFIG_PATH,
reconciled_at: RECONCILED_AT,
restart_pending: false,
};
/**
* The keys `/api/settings` still reports as restart-required, taken from the
* committed contract sample so a server-side change to the set fails the tests
* that pin it rather than passing against a stale copy.
*/
export const RESTART_REQUIRED_KEYS: readonly string[] = sample_get_settings.restart_required;
export function baseSettings(): Settings {
return {
upstream: { attempt_timeout_ms: 2500, read_timeout_ms: 3000, total_timeout_ms: 5000 },
dns: { bind_ipv4: "0.0.0.0", bind_ipv6: "::", port: 53, rate_limit: 100, rate_window_seconds: 60 },
blocking: { response: "zero", ttl: 300 },
cache: { size: 10000, negative_ttl_max: 300 },
web: {
enabled: true,
bind: "127.0.0.1",
port: 8080,
session_ttl_hours: 24,
api_rate_limit_per_min: 60,
api_localhost_exempt: true,
sse_max_connections_per_ip: 2,
trusted_proxies: "",
auth_enabled: true,
},
doh_server: { enabled: false, bind: "0.0.0.0", port: 443, cert_path: "", key_path: "" },
dot_server: { enabled: false, bind: "0.0.0.0", port: 853, cert_path: "", key_path: "" },
edns: { ecs_mode: "strip" },
logging: {
level: "info",
retention_days: 30,
query_log_buffer_max: 10000,
query_log_flush_interval_s: 60,
hide_domains: false,
hide_client_ips: false,
output: "stderr",
file_path: "",
max_size_mb: 50,
max_files: 3,
},
disk: { min_free_mb: 100, warn_free_mb: 500 },
blocklist_update: { enabled: true, interval_hours: 24 },
};
}
export const GROUPS = [
{ id: 1, name: "default", safe_search: false },
{ id: 2, name: "kids", safe_search: true },
];
export const BLOCKLISTS = [
{
id: 1,
url: "https://example.com/ads.txt",
name: "Ads",
enabled: true,
is_suggested: false,
last_updated: null,
domain_count: 100,
wildcard_count: 2,
exception_count: 1,
skipped_regex_count: 0,
skipped_unsupported_count: 0,
checksum: null,
},
{
id: 2,
url: "https://example.com/trackers.txt",
name: "Trackers",
enabled: false,
is_suggested: true,
last_updated: 1700000000,
domain_count: 50,
wildcard_count: 0,
exception_count: 0,
skipped_regex_count: 3,
skipped_unsupported_count: 4,
checksum: null,
},
];
export const RULES = [
{
id: 1,
group_id: 1,
group: "default",
pattern: "ads.example.com",
kind: "exact",
action: "block",
created_at: 1700000000,
},
{
id: 2,
group_id: 2,
group: "kids",
pattern: "*.social.example",
kind: "wildcard",
action: "block",
created_at: 1700000100,
},
];
export const CLIENTS = [
{
id: 1,
ip: "192.168.1.10",
name: "laptop",
learned_name: "",
group_id: 1,
group: "default",
hand_edited: true,
first_seen: 1700000000,
last_seen: 1700003600,
},
{
id: 2,
ip: "192.168.1.11",
name: "",
learned_name: "tablet.lan",
group_id: 2,
group: "kids",
hand_edited: false,
first_seen: 1700000000,
last_seen: 1700007200,
},
];
export const UPSTREAMS = [
{ id: 1, url: "udp://1.1.1.1:53", priority: 100, enabled: true, tls_name: "" },
{ id: 2, url: "tls://9.9.9.9:853", priority: 200, enabled: false, tls_name: "dns.quad9.net" },
];
export const LOCAL_RECORDS = [{ id: 1, name: "nas.lan.home", rtype: "A", value: "192.168.1.5", ttl: 300 }];
export const FORWARD_ZONES = [{ id: 1, zone: "lan.home", resolver: "udp://192.168.1.1:53" }];
export interface Call {
url: string;
method: string;
body: unknown;
}
export interface StubOptions {
/**
* Overrides and additions, keyed `"GET /api/x"`. A `Response` is used
* verbatim; a function is called per request, so a test can change what the
* server says between two reads of the same endpoint.
*/
responses?: Record<string, unknown>;
/**
* First refusal on every non-GET; return null to fall through to the default
* echo. An unsettled promise holds the mutation in flight, which is how a
* test observes a pending control.
*/
onWrite?: (call: Call) => Response | Promise<Response> | null;
}
function defaultResponses(status: ConfigStatus): Record<string, unknown> {
return {
"GET /api/config/status": status,
"GET /api/health": health(),
"GET /api/version": { version: "0.0.0-test", git_commit: "0000000", zig_version: "0.16.0", uptime_seconds: 1 },
"GET /api/groups": { groups: GROUPS },
"GET /api/groups/1/sources": { source_ids: [1] },
"GET /api/groups/2/sources": { source_ids: [] },
"GET /api/blocklists": { blocklists: BLOCKLISTS },
"GET /api/rules": { rules: RULES },
"GET /api/clients": { clients: CLIENTS },
"GET /api/client-prefixes": { client_prefixes: [] },
"GET /api/upstreams": { upstreams: UPSTREAMS },
"GET /api/local-records": { local_records: LOCAL_RECORDS },
"GET /api/forward-zones": { forward_zones: FORWARD_ZONES },
"GET /api/settings": { settings: baseSettings(), restart_required: RESTART_REQUIRED_KEYS },
};
}
function json(payload: unknown, status = 200): Response {
return new Response(JSON.stringify(payload), { status, headers: { "content-type": "application/json" } });
}
/** Installs the stub and returns the list every non-GET request is appended to. */
export function stubApi(status: ConfigStatus = DATABASE, options: StubOptions = {}): Call[] {
const map = { ...defaultResponses(status), ...options.responses };
const calls: Call[] = [];
vi.stubGlobal(
"fetch",
vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
const url = String(input);
const method = init?.method ?? "GET";
const body = typeof init?.body === "string" ? JSON.parse(init.body) : undefined;
const key = `${method} ${url}`;
const configured = map[key];
// A promise is handed back unsettled on purpose: it is how a test holds a
// query in its pending state for as long as it needs to.
if (configured instanceof Promise) return configured;
if (configured instanceof Response) return configured.clone();
if (typeof configured === "function") return json((configured as () => unknown)());
if (method !== "GET") {
calls.push({ url, method, body });
const override = options.onWrite?.({ url, method, body });
if (override !== null && override !== undefined) return override;
if (configured !== undefined) return json(configured);
if (method === "DELETE") return new Response(null, { status: 204 });
return json(body ?? {});
}
if (configured === undefined) return json({ error: `not stubbed: ${key}` }, 404);
return json(configured);
}),
);
return calls;
}
export function renderRoute(route: string) {
const queryClient = createQueryClient();
const router = createAppRouter(createMemoryHistory({ initialEntries: [route] }), queryClient);
render(
<AuthProvider>
<QueryClientProvider client={queryClient}>
<RouterProvider router={router} />
</QueryClientProvider>
</AuthProvider>,
);
return router;
}
export async function renderPage(route: string, heading: string) {
const router = renderRoute(route);
await screen.findByRole("heading", { name: heading, level: 1 });
return router;
}
/** The configuration page's own content, excluding the shell chrome around it. */
export function contentArea(): HTMLElement {
const main = document.querySelector("main");
if (main === null) throw new Error("no main element");
return main;
}
@@ -100,7 +100,9 @@ test("an open episode shows its facts, its copy and the error the server sent",
expect(screen.getByText(EVENT_COPY["blocklist.refresh"].impact)).toBeTruthy();
expect(screen.getByText(EVENT_COPY["blocklist.refresh"].remediation)).toBeTruthy();
expect(screen.getByText("download failed: ConnectionTimedOut")).toBeTruthy();
expect(screen.getByRole("link", { name: "Go to Blocklists" }).getAttribute("href")).toBe("/blocklists");
expect(screen.getByRole("link", { name: "Go to Blocklist sources" }).getAttribute("href")).toBe(
"/configuration/protection?tab=sources",
);
});
test("a resolved episode states how long it lasted, not how long it has run", async () => {
@@ -207,9 +207,27 @@ export default function DiagnosticDetailPage() {
{copy.link !== undefined && (
<p {...stylex.props(styles.links)}>
<Link to={copy.link.to} {...stylex.props(styles.link, shared.focusRing)}>
Go to {copy.link.label}
</Link>
{copy.link.to === "/configuration/protection" ? (
<Link
to="/configuration/protection"
search={{ tab: "sources" }}
{...stylex.props(styles.link, shared.focusRing)}
>
Go to {copy.link.label}
</Link>
) : copy.link.to === "/configuration/resolution" ? (
<Link
to="/configuration/resolution"
search={{ tab: "upstreams" }}
{...stylex.props(styles.link, shared.focusRing)}
>
Go to {copy.link.label}
</Link>
) : (
<Link to={copy.link.to} {...stylex.props(styles.link, shared.focusRing)}>
Go to {copy.link.label}
</Link>
)}
</p>
)}
@@ -99,7 +99,7 @@ test("the five conditions are stated in words, healthy ones without a way out",
expect(within(strip()).queryByRole("link")).toBeNull();
});
test("protection unavailable sends the reader to Blocklists, upstreams to Upstreams", async () => {
test("protection unavailable sends the reader to the sources, upstreams to the pool", async () => {
healthBody = health({
protection: { state: "unavailable", until: null },
upstreams: { state: "unavailable", available: 0, total: 2 },
@@ -107,10 +107,12 @@ test("protection unavailable sends the reader to Blocklists, upstreams to Upstre
renderDiagnostics();
await waitFor(() => expect(strip()).toBeTruthy());
expect(within(fact("Protection")).getByRole("link", { name: "Blocklists" }).getAttribute("href")).toBe(
"/blocklists",
expect(within(fact("Protection")).getByRole("link", { name: "Blocklist sources" }).getAttribute("href")).toBe(
"/configuration/protection?tab=sources",
);
expect(within(fact("Upstreams")).getByRole("link", { name: "Upstreams" }).getAttribute("href")).toBe(
"/configuration/resolution?tab=upstreams",
);
expect(within(fact("Upstreams")).getByRole("link", { name: "Upstreams" }).getAttribute("href")).toBe("/upstreams");
});
test("a losing query log narrows this page to the disk, a failed writer to the query log", async () => {
@@ -159,7 +161,8 @@ test("the strip says it is loading before the first reading, never empty conditi
renderDiagnostics();
expect(await screen.findByText("Loading status…")).toBeTruthy();
expect(screen.queryByText("Protection")).toBeNull();
// Scoped to the page: "Protection" is also a nav destination now.
expect(within(document.querySelector("main") as HTMLElement).queryByText("Protection")).toBeNull();
release();
await waitFor(() => expect(strip()).toBeTruthy());
+18 -1
View File
@@ -124,8 +124,25 @@ function FactLinkAnchor({ link }: { link: FactLink }) {
</Link>
);
}
// The tab belongs to the destination, not to the fact: a source that stopped
// loading is read on Protection's Sources tab, an upstream on Resolution's.
if (link.to === "/configuration/protection") {
return (
<Link
to="/configuration/protection"
search={{ tab: "sources" }}
{...stylex.props(styles.link, shared.focusRing)}
>
{link.label}
</Link>
);
}
return (
<Link to={link.to} {...stylex.props(styles.link, shared.focusRing)}>
<Link
to="/configuration/resolution"
search={{ tab: "upstreams" }}
{...stylex.props(styles.link, shared.focusRing)}
>
{link.label}
</Link>
);
+8 -6
View File
@@ -8,14 +8,16 @@
* `DIAGNOSTIC_CODES` to prove it at runtime too. A sixteenth code added to the
* enum fails `tsc` here before it can reach the page as a bare dotted string.
*
* `link` points at the configuration surface that governs the failure. Those
* are today's routes; the navigation restructure re-points them.
* `link` points at the configuration surface that governs the failure. The
* path alone decides which tab of that surface the detail page opens, so the
* copy never carries a tab of its own to drift from it.
*/
import { DIAGNOSTIC_CODES, type DiagnosticCode } from "@/lib/types";
/** The literal paths keep `link.to` assignable to a typed router `Link`. */
export type CopyLinkPath = "/settings" | "/blocklists" | "/upstreams" | "/clients";
export type CopyLinkPath =
"/configuration/system" | "/configuration/protection" | "/configuration/resolution" | "/clients";
export interface EventCopy {
title: string;
@@ -39,9 +41,9 @@ export function copyFor(code: DiagnosticCode): EventCopy {
);
}
const SETTINGS = { to: "/settings", label: "Settings" } as const;
const BLOCKLISTS = { to: "/blocklists", label: "Blocklists" } as const;
const UPSTREAMS = { to: "/upstreams", label: "Upstreams" } as const;
const SETTINGS = { to: "/configuration/system", label: "System" } as const;
const BLOCKLISTS = { to: "/configuration/protection", label: "Blocklist sources" } as const;
const UPSTREAMS = { to: "/configuration/resolution", label: "Upstreams" } as const;
const CLIENTS = { to: "/clients", label: "Clients" } as const;
/**
@@ -28,7 +28,7 @@ test("protection: active, paused indefinitely, paused until a time, unavailable"
expect(timed.value).toBe("Paused until 14:05");
const gone = factsBy({ protection: { state: "unavailable", until: null } })["protection"];
expect(gone.value).toBe("Unavailable");
expect(gone.link).toEqual({ kind: "route", to: "/blocklists", label: "Blocklists" });
expect(gone.link).toEqual({ kind: "route", to: "/configuration/protection", label: "Blocklist sources" });
});
test("a pause never reads as a fault, and never carries a way out", () => {
@@ -44,7 +44,7 @@ test("upstreams count the enabled pool, and only an empty one links out", () =>
expect(ok.link).toBeUndefined();
const none = factsBy({ upstreams: { state: "unavailable", available: 0, total: 3 } })["upstreams"];
expect(none.value).toBe("None reachable");
expect(none.link).toEqual({ kind: "route", to: "/upstreams", label: "Upstreams" });
expect(none.link).toEqual({ kind: "route", to: "/configuration/resolution", label: "Upstreams" });
});
test("query history: losing blames the disk gate, a failed writer blames the query log", () => {
@@ -20,7 +20,7 @@ export type FactTone = "ok" | "notice" | "warn" | "danger";
* that can fix the condition.
*/
export type FactLink =
| { kind: "route"; to: "/blocklists" | "/upstreams"; label: string }
| { kind: "route"; to: "/configuration/protection" | "/configuration/resolution"; label: string }
| { kind: "filter"; component: string; label: string };
export interface HealthFact {
@@ -50,7 +50,7 @@ function protectionFact(protection: Health["protection"], locale?: string, timeZ
tone: "danger",
value: "Unavailable",
detail: "No filter snapshot is published, so queries are not being filtered.",
link: { kind: "route", to: "/blocklists", label: "Blocklists" },
link: { kind: "route", to: "/configuration/protection", label: "Blocklist sources" },
};
}
if (protection.state === "paused") {
@@ -105,7 +105,7 @@ export function healthFacts(health: Health, locale?: string, timeZone?: string):
value: upstreams.state === "unavailable" ? "None reachable" : "Available",
detail: `${upstreams.available} of ${upstreams.total} enabled`,
...(upstreams.state === "unavailable"
? { link: { kind: "route", to: "/upstreams", label: "Upstreams" } as FactLink }
? { link: { kind: "route", to: "/configuration/resolution", label: "Upstreams" } as FactLink }
: {}),
},
queryHistoryFact(health.query_history, locale, timeZone),
@@ -1,135 +0,0 @@
import { fireEvent, render, screen, waitFor, within } from "@testing-library/react";
import { QueryClientProvider } from "@tanstack/react-query";
import { RouterProvider, createMemoryHistory } from "@tanstack/react-router";
import type { Mock } from "vitest";
import { AuthProvider } from "@/auth/store";
import { createQueryClient } from "@/lib/queryClient";
import { createAppRouter } from "@/routes";
const GROUPS = {
groups: [
{ id: 1, name: "default", safe_search: false },
{ id: 2, name: "kids", safe_search: true },
],
};
const BLOCKLISTS = {
blocklists: [
{
id: 1,
url: "https://example.com/ads.txt",
name: "Ads",
enabled: true,
is_suggested: false,
last_updated: null,
domain_count: 100,
wildcard_count: 0,
skipped_regex_count: 0,
checksum: null,
},
{
id: 2,
url: "https://example.com/malware.txt",
name: "Malware",
enabled: true,
is_suggested: false,
last_updated: null,
domain_count: 50,
wildcard_count: 0,
skipped_regex_count: 0,
checksum: null,
},
],
};
const VERSION = { version: "0.0.0-test", git_commit: "0000000", zig_version: "0.16.0", uptime_seconds: 1 };
const BASE = {
"GET /api/groups": GROUPS,
"GET /api/blocklists": BLOCKLISTS,
"GET /api/version": VERSION,
"GET /api/groups/2/sources": { source_ids: [1] },
"PUT /api/groups/2/sources": { source_ids: [1, 2] },
};
function stubFetch(map: Record<string, unknown>) {
vi.stubGlobal(
"fetch",
vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
const key = `${init?.method ?? "GET"} ${String(input)}`;
const payload = map[key];
if (payload === undefined) {
return new Response(JSON.stringify({ error: `not stubbed: ${key}` }), { status: 404 });
}
return new Response(JSON.stringify(payload), {
status: 200,
headers: { "content-type": "application/json" },
});
}),
);
}
async function renderGroupsPage(map: Record<string, unknown>) {
stubFetch(map);
const queryClient = createQueryClient();
const router = createAppRouter(createMemoryHistory({ initialEntries: ["/groups"] }), queryClient);
render(
<AuthProvider>
<QueryClientProvider client={queryClient}>
<RouterProvider router={router} />
</QueryClientProvider>
</AuthProvider>,
);
await screen.findByRole("heading", { name: "Groups" });
}
function groupRow(name: string): HTMLElement {
const row = screen.getByText(name).closest("li");
if (row === null) throw new Error(`no row for group ${name}`);
return row;
}
afterEach(() => {
vi.unstubAllGlobals();
});
test("lists groups; the default group blocks rename and delete client-side", async () => {
await renderGroupsPage(BASE);
const defaultRow = groupRow("default");
expect((within(defaultRow).getByRole("button", { name: "Rename" }) as HTMLButtonElement).disabled).toBe(true);
expect((within(defaultRow).getByRole("button", { name: "Delete" }) as HTMLButtonElement).disabled).toBe(true);
expect(within(defaultRow).getByText("The default group cannot be renamed or deleted.")).toBeTruthy();
const kidsRow = groupRow("kids");
expect((within(kidsRow).getByRole("button", { name: "Rename" }) as HTMLButtonElement).disabled).toBe(false);
expect((within(kidsRow).getByRole("button", { name: "Delete" }) as HTMLButtonElement).disabled).toBe(false);
expect((within(kidsRow).getByRole("checkbox", { name: "Safe search" }) as HTMLInputElement).checked).toBe(true);
});
test("expanding sources loads the set, toggling saves the full set via PUT", async () => {
await renderGroupsPage(BASE);
const kidsRow = groupRow("kids");
fireEvent.click(within(kidsRow).getByRole("button", { name: "Sources" }));
const ads = (await within(kidsRow).findByRole("checkbox", { name: "Ads" })) as HTMLInputElement;
const malware = within(kidsRow).getByRole("checkbox", { name: "Malware" }) as HTMLInputElement;
expect(ads.checked).toBe(true);
expect(malware.checked).toBe(false);
const save = within(kidsRow).getByRole("button", { name: "Save sources" }) as HTMLButtonElement;
expect(save.disabled).toBe(true);
fireEvent.click(malware);
expect(save.disabled).toBe(false);
fireEvent.click(save);
await waitFor(() => expect(save.disabled).toBe(true));
const calls = (fetch as unknown as Mock).mock.calls as [RequestInfo | URL, RequestInit | undefined][];
const put = calls.find(([, init]) => init?.method === "PUT");
expect(put).toBeTruthy();
expect(String(put![0])).toBe("/api/groups/2/sources");
expect(JSON.parse(String(put![1]?.body))).toEqual({ source_ids: [1, 2] });
expect(malware.checked).toBe(true);
});
-289
View File
@@ -1,289 +0,0 @@
import { useState } from "react";
import { useMutation, useQueryClient, useSuspenseQuery } from "@tanstack/react-query";
import * as stylex from "@stylexjs/stylex";
import {
blocklistsQuery,
groupCreateMutation,
groupDeleteMutation,
groupsQuery,
groupUpdateMutation,
} from "@/lib/queries";
import type { Blocklist, Group } from "@/lib/types";
import GroupSourcesEditor from "./GroupSourcesEditor";
import InlineError from "@/lib/InlineError";
import { styles as shared } from "@/ui/styles";
import { colors } from "@/ui/tokens.stylex";
import { DEFAULT_GROUP_ID } from "@/lib/defaultGroup";
import { READ_ONLY_HINT, useReadOnlyConfig } from "@/features/settings/authority";
const DEFAULT_GROUP_NOTE = "The default group cannot be renamed or deleted.";
const styles = stylex.create({
heading: {
fontSize: "1.5rem",
lineHeight: "2rem",
fontWeight: 600,
},
createForm: {
marginTop: "1rem",
display: "flex",
flexWrap: "wrap",
alignItems: "center",
gap: "0.5rem",
},
fieldLabel: {
fontSize: "0.875rem",
lineHeight: "1.25rem",
fontWeight: 500,
},
list: {
display: "flex",
flexDirection: "column",
gap: "1rem",
marginTop: "1.5rem",
},
row: {
borderRadius: "0.25rem",
borderWidth: 1,
borderStyle: "solid",
borderColor: colors.border,
padding: "1rem",
},
rowControls: {
display: "flex",
flexWrap: "wrap",
alignItems: "center",
gap: "0.75rem",
},
renameForm: {
display: "flex",
alignItems: "center",
gap: "0.5rem",
},
name: {
fontWeight: 500,
},
checkboxLabel: {
display: "inline-flex",
alignItems: "center",
gap: "0.5rem",
fontSize: "0.875rem",
lineHeight: "1.25rem",
},
actions: {
marginLeft: "auto",
display: "inline-flex",
flexWrap: "wrap",
alignItems: "center",
gap: "0.5rem",
},
groupButton: {
opacity: { default: 1, ":disabled": 0.5 },
},
destructive: {
color: colors.danger,
},
lockNote: {
marginTop: "0.5rem",
fontSize: "0.75rem",
lineHeight: "1rem",
color: colors.textMuted,
},
});
export default function GroupsPage() {
const { data: groups } = useSuspenseQuery(groupsQuery());
const { data: blocklists } = useSuspenseQuery(blocklistsQuery());
const queryClient = useQueryClient();
const createMutation = useMutation(groupCreateMutation(queryClient));
const [newName, setNewName] = useState("");
const readOnly = useReadOnlyConfig();
return (
<section>
<h1 {...stylex.props(styles.heading)}>Groups</h1>
<form
{...stylex.props(styles.createForm)}
onSubmit={(event) => {
event.preventDefault();
const name = newName.trim();
if (name === "") return;
createMutation.mutate({ name }, { onSuccess: () => setNewName("") });
}}
>
<label {...stylex.props(styles.fieldLabel)} htmlFor="new-group-name">
New group
</label>
<input
id="new-group-name"
type="text"
value={newName}
onChange={(event) => setNewName(event.target.value)}
disabled={readOnly}
{...stylex.props(shared.smallInput, shared.focusRing)}
/>
<button
type="submit"
disabled={createMutation.isPending || readOnly}
title={readOnly ? READ_ONLY_HINT : undefined}
{...stylex.props(shared.primaryButton, shared.focusRing)}
>
Create
</button>
</form>
<InlineError error={createMutation.error} />
<ul {...stylex.props(styles.list)}>
{groups.map((group) => (
<GroupRow key={group.id} group={group} blocklists={blocklists} />
))}
</ul>
</section>
);
}
function GroupRow({ group, blocklists }: { group: Group; blocklists: Blocklist[] }) {
const queryClient = useQueryClient();
const updateMutation = useMutation(groupUpdateMutation(queryClient));
const deleteMutation = useMutation(groupDeleteMutation(queryClient));
const [renaming, setRenaming] = useState(false);
const [name, setName] = useState(group.name);
const [confirming, setConfirming] = useState(false);
const [expanded, setExpanded] = useState(false);
const isDefault = group.id === DEFAULT_GROUP_ID;
const readOnly = useReadOnlyConfig();
const lockNote = isDefault ? DEFAULT_GROUP_NOTE : readOnly ? READ_ONLY_HINT : undefined;
return (
<li {...stylex.props(styles.row)}>
<div {...stylex.props(styles.rowControls)}>
{renaming ? (
<form
{...stylex.props(styles.renameForm)}
onSubmit={(event) => {
event.preventDefault();
const trimmed = name.trim();
if (trimmed === "") return;
updateMutation.mutate(
{ id: group.id, input: { name: trimmed, safe_search: group.safe_search } },
{ onSuccess: () => setRenaming(false) },
);
}}
>
<input
type="text"
aria-label={`New name for ${group.name}`}
value={name}
onChange={(event) => setName(event.target.value)}
{...stylex.props(shared.smallInput, shared.focusRing)}
autoFocus
/>
<button
type="submit"
disabled={updateMutation.isPending || readOnly}
title={readOnly ? READ_ONLY_HINT : undefined}
{...stylex.props(shared.smallButton, styles.groupButton, shared.focusRing)}
>
Save
</button>
<button
type="button"
onClick={() => {
setName(group.name);
setRenaming(false);
}}
{...stylex.props(shared.smallButton, styles.groupButton, shared.focusRing)}
>
Cancel
</button>
</form>
) : (
<span {...stylex.props(styles.name)}>{group.name}</span>
)}
<label {...stylex.props(styles.checkboxLabel)}>
<input
type="checkbox"
checked={group.safe_search}
disabled={updateMutation.isPending || readOnly}
title={readOnly ? READ_ONLY_HINT : undefined}
{...stylex.props(shared.focusRing)}
onChange={(event) =>
updateMutation.mutate({
id: group.id,
input: { name: group.name, safe_search: event.target.checked },
})
}
/>
Safe search
</label>
<span {...stylex.props(styles.actions)}>
<button
type="button"
aria-expanded={expanded}
onClick={() => setExpanded((open) => !open)}
{...stylex.props(shared.smallButton, styles.groupButton, shared.focusRing)}
>
Sources
</button>
{!renaming && (
<button
type="button"
disabled={isDefault || readOnly}
title={lockNote}
onClick={() => {
setName(group.name);
setRenaming(true);
}}
{...stylex.props(shared.smallButton, styles.groupButton, shared.focusRing)}
>
Rename
</button>
)}
{confirming ? (
<>
<button
type="button"
onClick={() => {
setConfirming(false);
deleteMutation.mutate(group.id);
}}
{...stylex.props(
shared.smallButton,
styles.groupButton,
styles.destructive,
shared.focusRing,
)}
>
Confirm delete
</button>
<button
type="button"
onClick={() => setConfirming(false)}
{...stylex.props(shared.smallButton, styles.groupButton, shared.focusRing)}
>
Cancel
</button>
</>
) : (
<button
type="button"
disabled={isDefault || readOnly}
title={lockNote}
onClick={() => setConfirming(true)}
{...stylex.props(
shared.smallButton,
styles.groupButton,
styles.destructive,
shared.focusRing,
)}
>
Delete
</button>
)}
</span>
</div>
{isDefault && <p {...stylex.props(styles.lockNote)}>{DEFAULT_GROUP_NOTE}</p>}
<InlineError error={updateMutation.error ?? deleteMutation.error} />
{expanded && <GroupSourcesEditor groupId={group.id} blocklists={blocklists} />}
</li>
);
}
@@ -1,170 +0,0 @@
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
import { QueryClientProvider } from "@tanstack/react-query";
import { RouterProvider, createMemoryHistory } from "@tanstack/react-router";
import { AuthProvider } from "@/auth/store";
import { createQueryClient } from "@/lib/queryClient";
import { createAppRouter } from "@/routes";
import type { LocalRecord, LocalRecordInput } from "@/lib/types";
let records: LocalRecord[];
let fetchMock: ReturnType<typeof createFetchMock>;
function json(payload: unknown, status = 200): Response {
return new Response(JSON.stringify(payload), { status, headers: { "content-type": "application/json" } });
}
function createFetchMock() {
return vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
const url = String(input);
const method = init?.method ?? "GET";
if (url === "/api/local-records" && method === "GET") return json({ local_records: records });
if (url === "/api/local-records" && method === "POST") {
const body = JSON.parse(String(init?.body)) as LocalRecordInput;
const created: LocalRecord = { id: 99, ttl: body.ttl ?? 300, ...body };
records = [...records, created];
return json(created, 201);
}
if (url.startsWith("/api/local-records/") && method === "DELETE") {
const id = Number(url.slice("/api/local-records/".length));
records = records.filter((record) => record.id !== id);
return new Response(null, { status: 204 });
}
if (url.startsWith("/api/forward-zones/") && method === "DELETE") return new Response(null, { status: 204 });
if (url === "/api/forward-zones" && method === "GET") {
return json({ forward_zones: [{ id: 7, zone: "lan.home", resolver: "udp://192.168.1.1:53" }] });
}
return json({ error: "not stubbed" }, 404);
});
}
beforeEach(() => {
records = [{ id: 1, name: "nas.lan.home", rtype: "A", value: "192.168.1.10", ttl: 300 }];
fetchMock = createFetchMock();
vi.stubGlobal("fetch", fetchMock);
});
afterEach(() => {
vi.unstubAllGlobals();
});
function renderPage() {
const queryClient = createQueryClient();
const router = createAppRouter(createMemoryHistory({ initialEntries: ["/local-dns"] }), queryClient);
render(
<AuthProvider>
<QueryClientProvider client={queryClient}>
<RouterProvider router={router} />
</QueryClientProvider>
</AuthProvider>,
);
}
test("renders the records table and switches to the forward zones tab", async () => {
renderPage();
await screen.findByRole("heading", { name: "Local DNS" });
await screen.findByText("nas.lan.home");
expect(screen.getByText("192.168.1.10")).toBeTruthy();
fireEvent.click(screen.getByRole("tab", { name: "Forward zones" }));
await screen.findByText("lan.home");
expect(screen.getByText("udp://192.168.1.1:53")).toBeTruthy();
});
test("the arrow keys move between tabs", async () => {
renderPage();
await screen.findByText("nas.lan.home");
const tablist = screen.getByRole("tablist", { name: "Local DNS" });
const records = screen.getByRole("tab", { name: "Records" });
expect(records.getAttribute("aria-selected")).toBe("true");
fireEvent.keyDown(tablist, { key: "ArrowRight" });
const zones = screen.getByRole("tab", { name: "Forward zones" });
expect(zones.getAttribute("aria-selected")).toBe("true");
expect(screen.getByRole("tab", { name: "Records" }).getAttribute("aria-selected")).toBe("false");
await screen.findByText("lan.home");
fireEvent.keyDown(tablist, { key: "ArrowLeft" });
expect(screen.getByRole("tab", { name: "Records" }).getAttribute("aria-selected")).toBe("true");
await screen.findByText("nas.lan.home");
});
test("creates a record: POST body per LocalRecordInput, list refreshes", async () => {
renderPage();
await screen.findByText("nas.lan.home");
fireEvent.click(screen.getByRole("button", { name: "Add record" }));
fireEvent.change(screen.getByLabelText("Name"), { target: { value: "printer.lan.home" } });
// The record type is a RAC Select now: open the listbox, then pick.
fireEvent.click(screen.getByRole("button", { name: /Type$/ }));
fireEvent.click(await screen.findByRole("option", { name: "AAAA" }));
fireEvent.change(screen.getByLabelText("Value"), { target: { value: "fd00::11" } });
fireEvent.click(screen.getByRole("button", { name: "Save" }));
await screen.findByText("printer.lan.home");
const post = fetchMock.mock.calls.find(
([input, init]) => init?.method === "POST" && String(input) === "/api/local-records",
);
expect(post).toBeTruthy();
expect(JSON.parse(String(post?.[1]?.body))).toEqual({ name: "printer.lan.home", rtype: "AAAA", value: "fd00::11" });
});
test("cancelling the record delete dialog sends no request", async () => {
renderPage();
await screen.findByText("nas.lan.home");
fireEvent.click(screen.getByRole("button", { name: "Delete" }));
const dialog = await screen.findByRole("alertdialog");
expect(dialog.textContent).toContain('Delete record "nas.lan.home"?');
fireEvent.click(screen.getByRole("button", { name: "Cancel" }));
await waitFor(() => expect(screen.queryByRole("alertdialog")).toBeNull());
expect(fetchMock.mock.calls.some(([, init]) => init?.method === "DELETE")).toBe(false);
expect(screen.getByText("nas.lan.home")).toBeTruthy();
});
test("confirming the record delete dialog issues the DELETE", async () => {
renderPage();
await screen.findByText("nas.lan.home");
fireEvent.click(screen.getByRole("button", { name: "Delete" }));
await screen.findByRole("alertdialog");
fireEvent.click(screen.getByRole("button", { name: "Delete" }));
await waitFor(() =>
expect(
fetchMock.mock.calls.some(
([input, init]) => init?.method === "DELETE" && String(input) === "/api/local-records/1",
),
).toBe(true),
);
await waitFor(() => expect(screen.queryByText("nas.lan.home")).toBeNull());
});
test("the forward zone delete dialog names the zone and confirms", async () => {
renderPage();
await screen.findByText("nas.lan.home");
fireEvent.click(screen.getByRole("tab", { name: "Forward zones" }));
await screen.findByText("lan.home");
fireEvent.click(screen.getByRole("button", { name: "Delete" }));
const dialog = await screen.findByRole("alertdialog");
expect(dialog.textContent).toContain('Delete forward zone "lan.home"?');
fireEvent.click(screen.getByRole("button", { name: "Cancel" }));
await waitFor(() => expect(screen.queryByRole("alertdialog")).toBeNull());
expect(fetchMock.mock.calls.some(([, init]) => init?.method === "DELETE")).toBe(false);
fireEvent.click(screen.getByRole("button", { name: "Delete" }));
await screen.findByRole("alertdialog");
fireEvent.click(screen.getByRole("button", { name: "Delete" }));
await waitFor(() =>
expect(
fetchMock.mock.calls.some(
([input, init]) => init?.method === "DELETE" && String(input) === "/api/forward-zones/7",
),
).toBe(true),
);
});
-27
View File
@@ -1,27 +0,0 @@
import * as stylex from "@stylexjs/stylex";
import RecordsTab from "@/features/local/RecordsTab";
import ZonesTab from "@/features/local/ZonesTab";
import Tabs from "@/ui/Tabs";
const styles = stylex.create({
heading: {
fontSize: "1.5rem",
lineHeight: "2rem",
fontWeight: 600,
},
});
export default function LocalDnsPage() {
return (
<section>
<h1 {...stylex.props(styles.heading)}>Local DNS</h1>
<Tabs
label="Local DNS"
tabs={[
{ id: "records", label: "Records", content: <RecordsTab /> },
{ id: "zones", label: "Forward zones", content: <ZonesTab /> },
]}
/>
</section>
);
}
@@ -0,0 +1,277 @@
import { fireEvent, render as renderBare, screen, within } from "@testing-library/react";
import { QueryClientProvider } from "@tanstack/react-query";
import { createQueryClient } from "@/lib/queryClient";
import { formatTime } from "@/lib/format";
import ClientChart, { type ClientChartData } from "./ClientChart";
import { OTHER_KEY, clientKey, seriesColor } from "./seriesColors";
const SINCE = 1_700_000_000;
const BUCKET = 1800;
function clients(named: { client: string; buckets: number[] }[], other: number[]): ClientChartData {
return { since: SINCE, bucket_seconds: BUCKET, clients: named, other };
}
const TWO_BUCKETS = clients(
[
{ client: "192.0.2.30", buckets: [10, 1] },
{ client: "192.0.2.31", buckets: [20, 1] },
],
[5, 1],
);
/**
* The chart looks a client's registered name up, so it needs a query client. No
* client is registered in these fixtures, which is what leaves the addresses on
* screen as the labels.
*/
function render(data: ClientChartData) {
const client = createQueryClient();
const tree = (next: ClientChartData) => (
<QueryClientProvider client={client}>
<ClientChart data={next} />
</QueryClientProvider>
);
const result = renderBare(tree(data));
return { ...result, rerender: (next: ClientChartData) => result.rerender(tree(next)) };
}
beforeEach(() => {
vi.stubGlobal(
"fetch",
vi.fn(async () =>
Promise.resolve(
new Response(JSON.stringify({ clients: [] }), {
status: 200,
headers: { "content-type": "application/json" },
}),
),
),
);
});
afterEach(() => vi.unstubAllGlobals());
function overlayRects(container: HTMLElement): SVGRectElement[] {
return Array.from(container.querySelectorAll<SVGRectElement>('rect[fill="transparent"]'));
}
test("the data table is the SVG's accessible equivalent", () => {
render(TWO_BUCKETS);
expect(screen.getByRole("img", { name: /client activity over time/i })).toBeTruthy();
const table = screen.getByRole("table", { name: "Queries per client per time bucket" });
expect(within(table).getAllByRole("row").length).toBe(3);
});
/**
* The x-axis is this response's own `since` plus one bucket width per column.
* The timeseries endpoint aligns its buckets with these, which is what lets the
* two charts stack above one another without either knowing about the other.
*/
test("the columns are timestamped from this response's own window", () => {
render(TWO_BUCKETS);
const rows = within(screen.getByRole("table")).getAllByRole("rowheader");
expect(rows.map((row) => row.textContent)).toEqual([formatTime(SINCE), formatTime(SINCE + BUCKET)]);
});
/**
* Every series here is a disjoint part of the whole, so the scale has to come
* from the tallest column's own sum. Taking it from the largest single value
* instead would run the tallest column off the top of the plot: the axis has to
* reach 35 here, not 20.
*/
test("the value scale covers the tallest column's total, not its largest series", () => {
const { container } = render(clients([{ client: "192.0.2.30", buckets: [20] }], [15]));
const labels = Array.from(container.querySelectorAll(".visx-axis-left text")).map((label) => label.textContent);
expect(labels[labels.length - 1]).toBe("35");
});
test("the series are drawn in the colour of the client's address, and Other in its own", () => {
const { container } = render(clients([{ client: "192.0.2.30", buckets: [10] }], [5]));
const fills = Array.from(container.querySelectorAll("rect"))
.map((rect) => rect.getAttribute("fill"))
.filter((fill) => fill !== "transparent");
expect(fills).toEqual([seriesColor(clientKey("192.0.2.30")), seriesColor(OTHER_KEY)]);
});
test("a window with no queries says so instead of drawing an empty grid", () => {
const { container } = render(clients([{ client: "192.0.2.30", buckets: [0, 0] }], [0, 0]));
expect(screen.getByText("No queries in this period.")).toBeTruthy();
expect(container.querySelector("svg")).toBeNull();
});
test("no bucket at all says the same thing", () => {
render(clients([], []));
expect(screen.getByText("No queries in this period.")).toBeTruthy();
});
test("hover text is the tooltip alone, never a bare SVG title", () => {
const { container } = render(TWO_BUCKETS);
expect(container.querySelectorAll("title")).toHaveLength(0);
});
test("each bucket's hit target spans the full plot height", () => {
const { container } = render(TWO_BUCKETS);
const rects = overlayRects(container);
expect(rects).toHaveLength(2);
for (const rect of rects) {
expect(rect.getAttribute("y")).toBe("8");
expect(rect.getAttribute("height")).toBe("210");
}
});
/**
* A band scale spends a gap after the last column as well as between them, so a
* full-step hit target on the last bucket would reach into the right margin.
*/
test("the last hit target stops at the plot's right edge", () => {
const { container } = render(TWO_BUCKETS);
const last = overlayRects(container).at(-1) as SVGRectElement;
const right = Number(last.getAttribute("x")) + Number(last.getAttribute("width"));
// 640 fallback width, less the 44px left and 8px right margins.
expect(right).toBeCloseTo(44 + 588, 6);
});
/**
* The window refreshes every half minute under an open tooltip. The tooltip
* holds a bucket index and reads the numbers out of the render it is drawing, so
* a refresh that keeps the same buckets updates it rather than leaving last
* minute's counts on screen.
*/
test("a refresh in the same window retells the hovered bucket with the new counts", () => {
const { container, rerender } = render(TWO_BUCKETS);
fireEvent.mouseOver(overlayRects(container)[0]);
expect(
Array.from((container.querySelector("dl") as HTMLElement).querySelectorAll("dd")).map((dd) => dd.textContent),
).toEqual(["35", "10", "20", "5"]);
rerender(
clients(
[
{ client: "192.0.2.30", buckets: [11, 1] },
{ client: "192.0.2.31", buckets: [22, 1] },
],
[6, 1],
),
);
expect(
Array.from((container.querySelector("dl") as HTMLElement).querySelectorAll("dd")).map((dd) => dd.textContent),
).toEqual(["39", "11", "22", "6"]);
});
/**
* A rolling window is the case a stored copy gets wrong: the bucket the pointer
* was over is gone, so index 0 now names a different span.
*/
test("a refresh that rolls the window takes the tooltip down instead of relabelling it", () => {
const { container, rerender } = render(TWO_BUCKETS);
fireEvent.mouseOver(overlayRects(container)[0]);
expect(container.querySelectorAll("dl")).toHaveLength(1);
rerender({ ...TWO_BUCKETS, since: SINCE + BUCKET });
expect(container.querySelectorAll("dl")).toHaveLength(0);
const stacks = Array.from(container.querySelectorAll("svg > g.visx-group[opacity]"));
expect(stacks.every((group) => group.getAttribute("opacity") === "1")).toBe(true);
});
/** The placement the hand-rolled tooltip had, restored over visx's 10px defaults. */
test("the tooltip is offset 8px from the chart top and from the bucket it names", () => {
const { container } = render(TWO_BUCKETS);
fireEvent.mouseOver(overlayRects(container)[0]);
const tooltip = container.querySelector(".visx-tooltip") as HTMLElement;
expect(tooltip.style.transform).toBe("translate(200px, 8px)");
});
/**
* `withBoundingRects` measures its node once, on mount, so the buckets must not
* share one. jsdom reports every rect as zero, so the mount is what this can
* observe, not the measurement itself.
*/
test("each bucket gets its own tooltip mount, so each is measured for itself", () => {
const { container } = render(TWO_BUCKETS);
const rects = overlayRects(container);
fireEvent.mouseOver(rects[0]);
const first = container.querySelector(".visx-tooltip");
fireEvent.mouseOver(rects[1]);
expect(first).not.toBeNull();
expect(container.querySelector(".visx-tooltip")).not.toBe(first);
});
test("pointing at a bucket names its total and every series, and dims the rest", () => {
const { container } = render(TWO_BUCKETS);
fireEvent.mouseOver(overlayRects(container)[0]);
const tooltip = container.querySelector("dl") as HTMLElement;
expect(tooltip.previousElementSibling?.textContent).toBe(formatTime(SINCE));
expect(Array.from(tooltip.querySelectorAll("dt")).map((dt) => dt.textContent)).toEqual([
"Queries",
"192.0.2.30",
"192.0.2.31",
"Other",
]);
expect(Array.from(tooltip.querySelectorAll("dd")).map((dd) => dd.textContent)).toEqual(["35", "10", "20", "5"]);
const swatches = Array.from(tooltip.querySelectorAll("dt span")).map((span) => span.getAttribute("style"));
expect(swatches[0]).toContain(seriesColor(clientKey("192.0.2.30")));
expect(swatches[2]).toContain(seriesColor(OTHER_KEY));
const stacks = Array.from(container.querySelectorAll("svg > g.visx-group[opacity]"));
expect(stacks.map((group) => group.getAttribute("opacity"))).toEqual(["1", "0.55"]);
});
test("leaving the chart takes the tooltip and the dimming with it", () => {
const { container } = render(TWO_BUCKETS);
fireEvent.mouseOver(overlayRects(container)[0]);
expect(container.querySelectorAll("dl")).toHaveLength(1);
fireEvent.mouseOut(container.querySelector("svg") as SVGSVGElement);
expect(container.querySelectorAll("dl")).toHaveLength(0);
const stacks = Array.from(container.querySelectorAll("svg > g.visx-group[opacity]"));
expect(stacks.every((group) => group.getAttribute("opacity") === "1")).toBe(true);
});
/**
* "Other" is everything outside the top eight clients. In a window where it
* counted nothing there is no eighth client to aggregate, and the entry would
* appear in the legend, the stack, the tooltip and the table saying only that it
* is empty. The named clients stay at zero: a client that went quiet is a fact.
*/
test("a window where Other counted nothing drops it from every surface", () => {
const { container } = render(clients([{ client: "192.0.2.30", buckets: [10, 4] }], [0, 0]));
expect(Array.from(container.querySelectorAll("ul li")).map((item) => item.textContent)).toEqual(["192.0.2.30"]);
expect(
within(screen.getByRole("table"))
.getAllByRole("columnheader")
.map((cell) => cell.textContent),
).toEqual(["Time", "192.0.2.30"]);
fireEvent.mouseOver(overlayRects(container)[0]);
const terms = Array.from((container.querySelector("dl") as HTMLElement).querySelectorAll("dt"));
expect(terms.map((term) => term.textContent)).toEqual(["Queries", "192.0.2.30"]);
});
test("one query outside the named clients is enough to keep Other", () => {
const { container } = render(clients([{ client: "192.0.2.30", buckets: [10, 4] }], [0, 1]));
expect(Array.from(container.querySelectorAll("ul li")).map((item) => item.textContent)).toEqual([
"192.0.2.30",
"Other",
]);
});
+135 -162
View File
@@ -2,56 +2,42 @@
* Client activity over the same window as the query-volume chart: one stacked
* series per named client, plus everything outside the top eight as "Other".
*
* The x-axis is the timeseries endpoint's own bucket alignment, so the two
* charts stack directly above one another and a spike in one is at the same
* horizontal position in the other. Colour keys on the client string, so a
* client that changes rank between polls keeps its colour.
* The x-axis is derived from this response's own `since` and `bucket_seconds`,
* which the API aligns with the timeseries endpoint's buckets, so the two charts
* stack directly above one another and a spike in one is at the same horizontal
* position in the other. Colour keys on the client string, so a client that
* changes rank between polls keeps its colour.
*/
import { useEffect, useRef, useState } from "react";
import * as stylex from "@stylexjs/stylex";
import { Group } from "@visx/group";
import { BarStack } from "@visx/shape";
import { formatTime } from "@/lib/format";
import type { StatsClients } from "@/lib/types";
import type { OverviewClientSeries } from "@/lib/types";
import { styles as shared } from "@/ui/styles";
import { colors } from "@/ui/tokens.stylex";
import { layoutStacked } from "./chartLayout";
import { clientLabel, useClientNames, type ClientNames } from "@/features/clients/clientNames";
import {
BucketOverlay,
CHART_HEIGHT,
ChartFrame,
ChartRoot,
ChartTooltip,
EmptyChart,
StackSegment,
bandScale,
labelTickValues,
plotArea,
slotCenter,
useActiveIndex,
useMeasuredWidth,
valueScale,
valueTicks,
type TooltipContent,
} from "./chartKit";
import { OTHER_KEY, clientKey, seriesColor } from "./seriesColors";
const CHART_HEIGHT = 240;
const FALLBACK_WIDTH = 640;
const styles = stylex.create({
empty: {
display: "flex",
alignItems: "center",
justifyContent: "center",
height: CHART_HEIGHT,
borderRadius: "0.25rem",
borderWidth: 1,
borderStyle: "dashed",
borderColor: colors.borderStrong,
fontSize: "0.875rem",
lineHeight: "1.25rem",
color: colors.textMuted,
},
root: {
position: "relative",
},
gridLine: {
stroke: colors.border,
},
axisLine: {
stroke: colors.borderStrong,
},
axisLabel: {
fill: colors.textMuted,
fontSize: "10px",
},
/** The hairline separating touching segments is the page ground, not a colour. */
segment: {
stroke: colors.surface,
},
legend: {
marginTop: "0.5rem",
display: "flex",
@@ -80,31 +66,6 @@ const styles = stylex.create({
swatchColor: (color: string) => ({ backgroundColor: color }),
});
function useContainerWidth(): [React.RefObject<HTMLDivElement | null>, number] {
const ref = useRef<HTMLDivElement>(null);
const [width, setWidth] = useState(0);
useEffect(() => {
const el = ref.current;
if (el === null) return;
setWidth(el.clientWidth);
if (typeof ResizeObserver === "undefined") return;
const observer = new ResizeObserver(() => setWidth(el.clientWidth));
observer.observe(el);
return () => observer.disconnect();
}, []);
return [ref, width];
}
const compact = new Intl.NumberFormat(undefined, { notation: "compact" });
function formatTick(ts: number, bucketSeconds: number): string {
const date = new Date(ts * 1000);
if (bucketSeconds >= 86_400) {
return new Intl.DateTimeFormat(undefined, { month: "short", day: "numeric" }).format(date);
}
return new Intl.DateTimeFormat(undefined, { hour: "numeric", minute: "2-digit" }).format(date);
}
interface Series {
key: string;
label: string;
@@ -115,12 +76,13 @@ interface Series {
}
/**
* "Other" last, so it sits at the top of every column rather than under a
* client, and always present: the response always carries the series, and a
* legend that dropped it on a quiet period would make the reader think the
* chart's clients were all of them.
* "Other" last, so it sits at the top of every column rather than under a client,
* and dropped entirely when it counted nothing across the window: an aggregation
* bucket that aggregated nothing is a legend entry, a stack key, a tooltip row
* and a table column all saying zero. The named clients stay at zero, because a
* client that went quiet is something the reader wants to see.
*/
function seriesOf(data: StatsClients, names: ClientNames): Series[] {
function seriesOf(data: ClientChartData, names: ClientNames): Series[] {
const named = data.clients.map((client) => ({
key: clientKey(client.client),
// The name if the client is registered under one, the address otherwise —
@@ -131,119 +93,130 @@ function seriesOf(data: StatsClients, names: ClientNames): Series[] {
color: seriesColor(clientKey(client.client)),
buckets: client.buckets,
}));
if (data.other.every((count) => count === 0)) return named;
return [
...named,
{ key: OTHER_KEY, label: "Other", address: null, color: seriesColor(OTHER_KEY), buckets: data.other },
];
}
export default function ClientChart({ data }: { data: StatsClients }) {
const [containerRef, measuredWidth] = useContainerWidth();
/**
* The slice of the Overview body this chart draws. Declared here rather than
* taken whole, so what the chart reads is stated where it is read.
*/
export interface ClientChartData {
since: number;
bucket_seconds: number;
clients: OverviewClientSeries[];
other: number[];
}
/** One column: the timestamp plus one entry per series, keyed by the series key. */
type Column = { ts: number } & Record<string, number>;
export default function ClientChart({ data }: { data: ClientChartData }) {
const [containerRef, width] = useMeasuredWidth();
// A hover survives a re-render only while it still names the same bucket at
// the same place: a poll that rolls the window, or a resize, retires it.
const hovered = useActiveIndex(`${data.since}:${data.bucket_seconds}:${data.other.length}:${width}`);
const names = useClientNames();
const width = measuredWidth > 0 ? measuredWidth : FALLBACK_WIDTH;
const series = seriesOf(data, names);
const bucketCount = data.other.length;
const columns: Column[] = Array.from({ length: bucketCount }, (_, i) => {
const column: Column = { ts: data.since + i * data.bucket_seconds };
for (const one of series) column[one.key] = one.buckets[i] ?? 0;
return column;
});
if (bucketCount === 0) {
return (
<div ref={containerRef} {...stylex.props(styles.empty)}>
No queries in this period.
</div>
);
if (bucketCount === 0 || columns.every((column) => series.every((one) => column[one.key] === 0))) {
return <EmptyChart containerRef={containerRef} />;
}
const columns = Array.from({ length: bucketCount }, (_, i) => ({
ts: data.since + i * data.bucket_seconds,
values: series.map((one) => one.buckets[i] ?? 0),
}));
if (columns.every((column) => column.values.every((value) => value === 0))) {
return (
<div ref={containerRef} {...stylex.props(styles.empty)}>
No queries in this period.
</div>
);
}
const timestamps = columns.map((column) => column.ts);
const totals = columns.map((column) => series.reduce((sum, one) => sum + column[one.key], 0));
const plot = plotArea(width);
const xScale = bandScale(timestamps, plot);
// Every series here is a disjoint part of the whole rather than a highlighted
// subset of a separately reported total, so the tallest column's own sum is
// the scale.
const yScale = valueScale(Math.max(...totals), [plot.bottom, plot.y]);
const yTicks = valueTicks(yScale);
const colorOf = new Map(series.map((one) => [one.key, one.color]));
const layout = layoutStacked(columns, width, CHART_HEIGHT);
const baseline = layout.plot.y + layout.plot.height;
function tooltipOf(index: number): TooltipContent {
return {
title: formatTime(columns[index].ts),
rows: [
{ key: "queries", label: "Queries", value: String(totals[index]) },
...series.map((one) => ({
key: one.key,
label: one.label,
color: one.color,
value: String(columns[index][one.key]),
})),
],
};
}
return (
<div ref={containerRef} {...stylex.props(styles.root)}>
<ChartRoot containerRef={containerRef}>
<svg
role="img"
aria-label={`Client activity over time, ${bucketCount} buckets, ${series.length} series`}
width="100%"
height={CHART_HEIGHT}
viewBox={`0 0 ${width} ${CHART_HEIGHT}`}
onMouseLeave={hovered.clear}
>
{layout.yTicks.map((tick) => (
<g key={tick.value}>
<line
x1={layout.plot.x}
x2={layout.plot.x + layout.plot.width}
y1={tick.y}
y2={tick.y}
{...stylex.props(styles.gridLine)}
/>
<text
x={layout.plot.x - 6}
y={tick.y}
textAnchor="end"
dominantBaseline="middle"
{...stylex.props(styles.axisLabel, shared.tabularNums)}
>
{compact.format(tick.value)}
</text>
</g>
))}
<line
x1={layout.plot.x}
x2={layout.plot.x + layout.plot.width}
y1={baseline}
y2={baseline}
{...stylex.props(styles.axisLine)}
<ChartFrame
plot={plot}
yScale={yScale}
yTicks={yTicks}
xScale={xScale}
xTickValues={labelTickValues(timestamps, plot.width)}
bucketSeconds={data.bucket_seconds}
/>
{layout.xTicks.map((tick) => (
<text
key={tick.ts}
x={tick.x}
y={baseline + 14}
textAnchor="middle"
{...stylex.props(styles.axisLabel)}
>
{formatTick(tick.ts, data.bucket_seconds)}
</text>
))}
{layout.columns.map((column) => (
<g key={column.ts}>
{column.segments.map((rect, index) =>
rect.height <= 0 ? null : (
<rect
key={series[index].key}
x={rect.x}
y={rect.y}
width={rect.width}
height={rect.height}
fill={series[index].color}
strokeWidth={rect.width > 3 ? 1 : 0}
{...stylex.props(styles.segment)}
/>
),
)}
<rect
x={column.slot.x}
y={column.slot.y}
width={column.slot.width}
height={column.slot.height}
fill="transparent"
>
<title>
{`${formatTime(column.ts)}: ${column.total} ${column.total === 1 ? "query" : "queries"}`}
</title>
</rect>
</g>
))}
<BarStack<Column, string>
data={columns}
keys={series.map((one) => one.key)}
x={(column) => column.ts}
xScale={xScale}
yScale={yScale}
color={(key) => colorOf.get(key) ?? seriesColor(key)}
>
{(stacks) =>
columns.map((column, index) => (
<Group
key={column.ts}
opacity={hovered.index === null || hovered.index === index ? 1 : 0.55}
>
{stacks.map((stack) => {
const bar = stack.bars[index];
return (
<StackSegment
key={stack.key}
x={bar.x}
y={bar.y}
width={bar.width}
height={bar.height}
fill={bar.color}
/>
);
})}
</Group>
))
}
</BarStack>
<BucketOverlay plot={plot} values={timestamps} xScale={xScale} onEnter={hovered.show} />
</svg>
{hovered.index !== null && (
<ChartTooltip
index={hovered.index}
content={tooltipOf(hovered.index)}
left={slotCenter(xScale, timestamps[hovered.index], plot)}
/>
)}
<ul {...stylex.props(styles.legend)}>
{series.map((one) => (
<li key={one.key} title={one.address ?? undefined} {...stylex.props(styles.legendItem)}>
@@ -269,14 +242,14 @@ export default function ClientChart({ data }: { data: StatsClients }) {
{columns.map((column) => (
<tr key={column.ts}>
<th scope="row">{formatTime(column.ts)}</th>
{column.values.map((value, index) => (
<td key={series[index].key}>{value}</td>
{series.map((one) => (
<td key={one.key}>{column[one.key]}</td>
))}
</tr>
))}
</tbody>
</table>
</div>
</div>
</ChartRoot>
);
}
+200
View File
@@ -0,0 +1,200 @@
import { fireEvent, render, screen, within } from "@testing-library/react";
import Donut, { type DonutSlice } from "./Donut";
function slice(key: string, value: number, color = "#000000"): DonutSlice {
return { key, label: key.toUpperCase(), value, color };
}
function ring(container: HTMLElement): SVGPathElement[] {
return Array.from(container.querySelectorAll("svg path"));
}
/** The x radius of every `A` command in a path, in the order they are drawn. */
function arcRadii(d: string): number[] {
return Array.from(d.matchAll(/A(-?[\d.]+),/g)).map((match) => Number(match[1]));
}
function draw(slices: DonutSlice[]) {
return render(<Donut slices={slices} caption="Queries by DNS type" unit="Queries" />);
}
test("a breakdown of nothing says so rather than dividing by zero", () => {
const { container } = draw([slice("a", 0), slice("b", 0)]);
expect(screen.getByText("No queries in this period.")).toBeTruthy();
expect(container.querySelector("svg")).toBeNull();
});
test("an empty breakdown says the same thing", () => {
draw([]);
expect(screen.getByText("No queries in this period.")).toBeTruthy();
});
/** A legend entry reading 0% is noise, and a zero slice has no arc to draw. */
test("zero-valued entries are dropped from the ring, the legend and the table", () => {
const { container } = draw([slice("a", 3), slice("z", 0), slice("b", 1)]);
expect(ring(container)).toHaveLength(2);
expect(screen.queryByText("Z")).toBeNull();
expect(
within(screen.getByRole("table"))
.getAllByRole("rowheader")
.map((row) => row.textContent),
).toEqual(["A", "B"]);
});
/**
* The caller has already ranked the slices, so the ring must not re-sort them:
* the first arc opens at twelve o'clock and each one starts where the last
* ended, running clockwise.
*
* The fixture runs 1 then 3 on purpose. d3's default pie sort is by value
* descending, so a fixture that happened to be given in descending order would
* pass with the sort left on and prove nothing.
*/
test("the ring starts at twelve o'clock and runs clockwise in the order given", () => {
const { container } = draw([slice("a", 1, "#112233"), slice("b", 3, "#445566")]);
const paths = ring(container);
// The small slice is drawn first because it was given first.
expect(paths[0].getAttribute("fill")).toBe("#112233");
expect(paths[0].getAttribute("d")?.startsWith("M0,-90")).toBe(true);
// A quarter turn clockwise from the top is three o'clock, where the second
// slice picks up.
expect(paths[1].getAttribute("fill")).toBe("#445566");
expect(paths[1].getAttribute("d")?.startsWith("M90,0")).toBe(true);
});
/**
* A whole-circle arc from a point back to itself draws nothing at all, so the
* one-entry case has to come out as a closed ring: two half arcs out and two
* back.
*/
test("a single entry is a closed ring, not a zero-length arc", () => {
const { container } = draw([slice("only", 7)]);
const paths = ring(container);
expect(paths).toHaveLength(1);
const d = paths[0].getAttribute("d") ?? "";
expect(d.match(/A/g)).toHaveLength(4);
// Two half arcs out at the outer radius and two back at the inner one: a
// 180px ring 36px thick.
expect(arcRadii(d)).toEqual([90, 90, 54, 54]);
});
test("shares are of the drawn total, in the legend and in the hidden table alike", () => {
draw([slice("a", 3), slice("b", 1)]);
expect(screen.getAllByText("75.0%")).toHaveLength(2);
expect(screen.getAllByText("25.0%")).toHaveLength(2);
});
/**
* The colour is the caller's, never recomputed from the key here: the page owns
* the identity-to-colour mapping and two donuts of one page must agree with it.
*/
test("each arc is filled with the colour its slice carries", () => {
const { container } = draw([slice("a", 3, "#112233"), slice("b", 1, "#445566")]);
expect(ring(container).map((path) => path.getAttribute("fill"))).toEqual(["#112233", "#445566"]);
});
/**
* Colour is a pure function of identity and so cannot rule out two slices of one
* panel sharing a hue. The stroke is what stops neighbours from merging into one
* shape.
*/
test("every arc is outlined in the panel's own surface colour", () => {
const { container } = draw([slice("a", 3), slice("b", 1)]);
for (const path of ring(container)) {
expect(path.getAttribute("stroke-width")).toBe("1");
expect(path.getAttribute("stroke")).toMatch(/^var\(--/);
}
});
test("the ring is decoration; the legend and the hidden table are the accessible surface", () => {
const { container } = draw([slice("a", 3), slice("b", 1)]);
const svg = container.querySelector("svg");
expect(svg?.getAttribute("aria-hidden")).toBe("true");
expect(svg?.getAttribute("focusable")).toBe("false");
expect(screen.getByRole("table", { name: "Queries by DNS type" })).toBeTruthy();
});
/**
* The ring gets the bar charts' hover treatment: the shared tooltip names the
* slice and repeats what the legend says about it, and the slices it is not
* naming dim out of the way. The ring stays `aria-hidden` the tooltip is a
* pointer affordance, and the legend beside it is still the readable copy.
*/
test("pointing at a slice names it and dims the rest", () => {
const { container } = draw([slice("a", 3, "#112233"), slice("b", 1, "#445566")]);
const paths = ring(container);
fireEvent.mouseOver(paths[0]);
const tooltip = container.querySelector("dl") as HTMLElement;
expect(tooltip.previousElementSibling?.textContent).toBe("A");
expect(Array.from(tooltip.querySelectorAll("dt")).map((term) => term.textContent)).toEqual(["Queries", "Share"]);
expect(Array.from(tooltip.querySelectorAll("dd")).map((value) => value.textContent)).toEqual(["3", "75.0%"]);
// The same share the legend and the hidden table already print for this slice.
expect(screen.getAllByText("75.0%")).toHaveLength(3);
expect(paths.map((path) => path.getAttribute("opacity"))).toEqual(["1", "0.55"]);
expect(container.querySelector("svg")?.getAttribute("aria-hidden")).toBe("true");
// The tooltip points at the middle of the arc, which the component computes
// from the slice values rather than from the drawn path. Slice A is three
// quarters of the ring, so its midpoint is at 135 degrees, on a circle of
// radius 72 — (140.9, 140.9) from the ring's top-left corner, plus the 8px
// the tooltip stands off by. Nothing else here would catch that arithmetic
// drifting away from the ring the Pie actually draws.
const tooltipBox = container.querySelector(".visx-tooltip") as HTMLElement;
expect(tooltipBox.style.transform).toBe("translate(149px, 149px)");
});
test("leaving the ring takes the tooltip and the dimming with it", () => {
const { container } = draw([slice("a", 3), slice("b", 1)]);
fireEvent.mouseOver(ring(container)[0]);
expect(container.querySelectorAll("dl")).toHaveLength(1);
fireEvent.mouseOut(container.querySelector("svg") as SVGSVGElement);
expect(container.querySelectorAll("dl")).toHaveLength(0);
expect(ring(container).map((path) => path.getAttribute("opacity"))).toEqual(["1", "1"]);
});
/**
* The same slice can change width between refreshes, so a mount measured at the
* old width would be placed at the wrong one. This is the donut's half of the
* remount the bar charts do.
*/
test("a refresh keeps the hovered slice current and remeasures it", () => {
const { container, rerender } = draw([slice("a", 3), slice("b", 1)]);
fireEvent.mouseOver(ring(container)[0]);
const first = container.querySelector(".visx-tooltip");
expect(Array.from(first?.querySelectorAll("dd") ?? []).map((value) => value.textContent)).toEqual(["3", "75.0%"]);
rerender(<Donut slices={[slice("a", 3000), slice("b", 1000)]} caption="Queries by DNS type" unit="Queries" />);
const second = container.querySelector(".visx-tooltip");
expect(Array.from(second?.querySelectorAll("dd") ?? []).map((value) => value.textContent)).toEqual([
"3,000",
"75.0%",
]);
expect(second).not.toBe(first);
});
/** A slice that is gone cannot be described, so the hover goes with it. */
test("a refresh that changes the slices takes the tooltip down", () => {
const { container, rerender } = draw([slice("a", 3), slice("b", 1)]);
fireEvent.mouseOver(ring(container)[0]);
expect(container.querySelectorAll("dl")).toHaveLength(1);
rerender(<Donut slices={[slice("c", 3), slice("b", 1)]} caption="Queries by DNS type" unit="Queries" />);
expect(container.querySelectorAll("dl")).toHaveLength(0);
});
+130 -45
View File
@@ -13,12 +13,26 @@
*/
import * as stylex from "@stylexjs/stylex";
import { Group } from "@visx/group";
import { Pie } from "@visx/shape";
import { styles as shared } from "@/ui/styles";
import { colors } from "@/ui/tokens.stylex";
import { layoutDonut, type DonutSlice } from "./donutLayout";
import { ChartTooltip, useActiveIndex, type TooltipContent } from "./chartKit";
export interface DonutSlice {
/** Semantic identity: the React key, the colour key and the legend's identity. */
key: string;
label: string;
/** Disambiguates entries whose labels collide — two "Unknown"s, one name on two route kinds. */
secondary?: string;
value: number;
color: string;
}
const SIZE = 180;
const THICKNESS = 36;
const OUTER_RADIUS = SIZE / 2;
const INNER_RADIUS = OUTER_RADIUS - THICKNESS;
const numberFormat = new Intl.NumberFormat();
@@ -54,8 +68,12 @@ const styles = stylex.create({
justifyContent: { default: "center", [TWO_COLUMN]: "flex-start" },
gap: "1.25rem",
},
/** The tooltip is placed against the ring's own box, so slice coordinates can
* be used unchanged rather than measured against the whole panel. */
ring: {
position: "relative",
flexShrink: 0,
lineHeight: 0,
},
/**
* Capped and left-anchored. Without the cap the row justifies across whatever
@@ -115,6 +133,21 @@ function sharePercent(share: number): string {
return `${(share * 100).toFixed(1)}%`;
}
/**
* Where a slice's tooltip points: the middle of its arc, in the ring box's own
* coordinates. This restates the `Pie` configuration below clockwise from
* twelve o'clock, caller order, no pad angle and the two must agree.
*/
function sliceAnchor(drawn: DonutSlice[], index: number, total: number): { left: number; top: number } {
const before = drawn.slice(0, index).reduce((sum, slice) => sum + slice.value, 0);
const middle = (2 * Math.PI * (before + drawn[index].value / 2)) / total;
const radius = (OUTER_RADIUS + INNER_RADIUS) / 2;
return {
left: OUTER_RADIUS + Math.sin(middle) * radius,
top: OUTER_RADIUS - Math.cos(middle) * radius,
};
}
export default function Donut({
slices,
caption,
@@ -126,56 +159,108 @@ export default function Donut({
/** The column header for the counted thing, e.g. "Queries". */
unit: string;
}) {
const layout = layoutDonut(slices, SIZE, THICKNESS);
// Zero-valued entries have no arc to draw and a legend entry reading 0 is
// noise, so they are dropped before anything is measured or drawn.
const drawn = slices.filter((slice) => slice.value > 0);
const total = drawn.reduce((sum, slice) => sum + slice.value, 0);
// A hover names a slice by position, so it survives only while the ring is
// still made of the same slices in the same order.
const hovered = useActiveIndex(drawn.map((slice) => slice.key).join(","));
if (layout.total === 0) {
function tooltipOf(index: number): TooltipContent {
const slice = drawn[index];
return {
title: slice.secondary === undefined ? slice.label : `${slice.label} (${slice.secondary})`,
rows: [
{ key: "value", label: unit, color: slice.color, value: numberFormat.format(slice.value) },
{ key: "share", label: "Share", value: sharePercent(slice.value / total) },
],
};
}
if (total === 0) {
return <div {...stylex.props(styles.empty)}>No queries in this period.</div>;
}
return (
<div {...stylex.props(styles.body)}>
<svg
aria-hidden="true"
focusable="false"
width={SIZE}
height={SIZE}
viewBox={`0 0 ${SIZE} ${SIZE}`}
{...stylex.props(styles.ring)}
>
{layout.arcs.map((arc) => (
// The stroke is what keeps a shared hue from lying. Colour is a pure
// function of identity, so two neighbouring slices can come out the
// same; outlined in the panel's own colour they still read as two
// shapes rather than merging into one. Attributes rather than a
// class, as the client chart's segments are, so the separation is
// visible to a test and not only to a stylesheet.
<path
key={arc.slice.key}
d={arc.d}
fill={arc.slice.color}
fillRule="evenodd"
stroke={colors.surfaceRaised}
strokeWidth={1}
<div {...stylex.props(styles.ring)}>
{/* The ring stays out of the accessibility tree even though it is now
a pointer target: the tooltip repeats what the legend beside it
already says in text, so nothing here is the only copy. */}
<svg
aria-hidden="true"
focusable="false"
width={SIZE}
height={SIZE}
viewBox={`0 0 ${SIZE} ${SIZE}`}
onMouseLeave={hovered.clear}
>
{/* Arc paths are generated around the origin, and `Pie`'s own
`top`/`left` group is skipped when it is given a render prop, so
the ring is centred here instead. */}
<Group top={OUTER_RADIUS} left={OUTER_RADIUS}>
<Pie
data={drawn}
pieValue={(slice) => slice.value}
// The caller has already ranked the slices, so d3's own sort is off
// in both of its forms and the ring runs clockwise from twelve
// o'clock in the order given. @visx/shape 4.0.0 already disables
// it by default — but that default exists because d3-shape v3
// changed sortValues to descending under it, so saying it here is
// what keeps a future bump from silently re-ranking the ring.
pieSort={null}
pieSortValues={null}
outerRadius={OUTER_RADIUS}
innerRadius={INNER_RADIUS}
>
{({ arcs, path }) =>
arcs.map((arc, index) => (
// The stroke is what keeps a shared hue from lying. Colour is a
// pure function of identity, so two neighbouring slices can come
// out the same; outlined in the panel's own colour they still
// read as two shapes rather than merging into one. Attributes
// rather than a class, as the client chart's segments are, so
// the separation is visible to a test and not only to a
// stylesheet.
<path
key={arc.data.key}
d={path(arc) ?? ""}
fill={arc.data.color}
stroke={colors.surfaceRaised}
strokeWidth={1}
opacity={hovered.index === null || hovered.index === index ? 1 : 0.55}
onMouseEnter={() => hovered.show(index)}
/>
))
}
</Pie>
</Group>
</svg>
{hovered.index !== null && (
<ChartTooltip
index={hovered.index}
content={tooltipOf(hovered.index)}
{...sliceAnchor(drawn, hovered.index, total)}
/>
))}
</svg>
)}
</div>
<ul {...stylex.props(styles.legend)}>
{layout.arcs.map((arc) => (
<li key={arc.slice.key} {...stylex.props(styles.legendItem)}>
<span
aria-hidden="true"
{...stylex.props(styles.swatch, styles.swatchColor(arc.slice.color))}
/>
{drawn.map((slice) => (
<li key={slice.key} {...stylex.props(styles.legendItem)}>
<span aria-hidden="true" {...stylex.props(styles.swatch, styles.swatchColor(slice.color))} />
<span {...stylex.props(styles.label)}>
{arc.slice.label}
{arc.slice.secondary !== undefined && (
<span {...stylex.props(styles.secondary)}>{arc.slice.secondary}</span>
{slice.label}
{slice.secondary !== undefined && (
<span {...stylex.props(styles.secondary)}>{slice.secondary}</span>
)}
</span>
<span {...stylex.props(styles.count, shared.tabularNums)}>
{numberFormat.format(arc.slice.value)}
{numberFormat.format(slice.value)}
</span>
<span {...stylex.props(styles.share, shared.tabularNums)}>
{sharePercent(slice.value / total)}
</span>
<span {...stylex.props(styles.share, shared.tabularNums)}>{sharePercent(arc.share)}</span>
</li>
))}
</ul>
@@ -190,15 +275,15 @@ export default function Donut({
</tr>
</thead>
<tbody>
{layout.arcs.map((arc) => (
<tr key={arc.slice.key}>
{drawn.map((slice) => (
<tr key={slice.key}>
<th scope="row">
{arc.slice.secondary === undefined
? arc.slice.label
: `${arc.slice.label} (${arc.slice.secondary})`}
{slice.secondary === undefined
? slice.label
: `${slice.label} (${slice.secondary})`}
</th>
<td>{arc.slice.value}</td>
<td>{sharePercent(arc.share)}</td>
<td>{slice.value}</td>
<td>{sharePercent(slice.value / total)}</td>
</tr>
))}
</tbody>
@@ -0,0 +1,133 @@
/**
* The part of Overview that does not wait for anything: the heading, the period
* picker, and the pulsing body the page shows while the window is in flight.
*
* It lives apart from `OverviewPage` so the route's pending component can render
* the identical surface while the page chunk loads. Importing the page itself
* would pull the charts into the main bundle, and a second hand-written copy of
* the frame would drift. Nothing here imports a chart.
*/
import * as stylex from "@stylexjs/stylex";
import { useNavigate, useSearch } from "@tanstack/react-router";
import type { Period } from "@/lib/types";
import { styles as shared } from "@/ui/styles";
import { colors } from "@/ui/tokens.stylex";
import { DEFAULT_PERIOD, PERIODS } from "./period";
const styles = stylex.create({
page: {
display: "flex",
flexDirection: "column",
gap: "1rem",
},
headingRow: {
display: "flex",
flexWrap: "wrap",
alignItems: "center",
justifyContent: "space-between",
gap: "0.75rem",
},
heading: {
fontSize: "1.5rem",
lineHeight: "2rem",
fontWeight: 600,
},
periodGroup: {
display: "flex",
gap: "0.25rem",
},
period: {
borderStyle: "none",
borderRadius: "0.25rem",
paddingInline: "0.625rem",
paddingBlock: "0.25rem",
fontSize: "0.875rem",
lineHeight: "1.25rem",
},
/** The pressed fill is heavier than `surfaceHover`, so a hover cannot mimic it. */
periodSelected: {
backgroundColor: {
default: "oklch(92% 0.004 286.32)",
"@media (prefers-color-scheme: dark)": "oklch(37% 0.013 285.805)",
},
color: colors.text,
fontWeight: 500,
},
periodIdle: {
backgroundColor: { default: "transparent", ":hover": colors.surfaceHover },
color: colors.textSecondary,
},
loading: {
fontSize: "0.875rem",
lineHeight: "1.25rem",
color: colors.textMuted,
},
});
export function PeriodPicker({ period, onChange }: { period: Period; onChange: (period: Period) => void }) {
return (
<div role="group" aria-label="Period" {...stylex.props(styles.periodGroup)}>
{PERIODS.map((option) => (
<button
key={option}
type="button"
aria-pressed={option === period}
onClick={() => onChange(option)}
{...stylex.props(
styles.period,
option === period ? styles.periodSelected : styles.periodIdle,
shared.focusRing,
)}
>
{option}
</button>
))}
</div>
);
}
export function OverviewLoading() {
return (
<p role="status" {...stylex.props(styles.loading, shared.pulse)}>
Loading
</p>
);
}
export function OverviewFrame({
period,
onChange,
children,
}: {
period: Period;
onChange: (period: Period) => void;
children: React.ReactNode;
}) {
return (
<div {...stylex.props(styles.page)}>
<div {...stylex.props(styles.headingRow)}>
<h1 {...stylex.props(styles.heading)}>Overview</h1>
<PeriodPicker period={period} onChange={onChange} />
</div>
{children}
</div>
);
}
/**
* The route's pending surface. The picker stays live because it only writes the
* search parameter, which the route already re-reads on its own.
*/
export function OverviewPending() {
const period = useSearch({ from: "/shell/overview" }).period ?? DEFAULT_PERIOD;
const navigate = useNavigate({ from: "/overview" });
return (
<OverviewFrame
period={period}
onChange={(next) => void navigate({ search: (prev) => ({ ...prev, period: next }) })}
>
<OverviewLoading />
</OverviewFrame>
);
}
@@ -14,66 +14,34 @@ import { RouterProvider, createMemoryHistory } from "@tanstack/react-router";
import { AuthProvider } from "@/auth/store";
import { createQueryClient } from "@/lib/queryClient";
import { createAppRouter } from "@/routes";
import { clientKey, seriesColor } from "./seriesColors";
import { clientKey, qtypeKey, seriesColor } from "./seriesColors";
import { health } from "@/lib/healthFixture";
import type { Health, StatsClients, StatsRoutes, StatsTimeseries, StatsTotals, StatsTypes } from "@/lib/types";
import type { Health, Overview } from "@/lib/types";
const SINCE = Date.UTC(2026, 0, 1, 0, 0) / 1000;
const UNTIL = Date.UTC(2026, 0, 2, 0, 0) / 1000;
const COVERAGE = { complete: true, available_since: SINCE };
const TOTALS: StatsTotals = {
period: "24h",
since: SINCE,
until: UNTIL,
queries: 1000,
blocked: 250,
clients: 7,
avg_response_time_us: 2345,
coverage: COVERAGE,
};
const SERIES: StatsTimeseries = {
const OVERVIEW: Overview = {
period: "24h",
since: SINCE,
until: UNTIL,
bucket_seconds: 1800,
totals: { queries: 1000, blocked: 250, clients: 7, avg_response_time_us: 2345 },
buckets: [
{ ts: SINCE, queries: 60, blocked: 20, cached: 10 },
{ ts: SINCE + 1800, queries: 40, blocked: 0, cached: 0 },
],
coverage: COVERAGE,
};
const CLIENTS: StatsClients = {
period: "24h",
since: SINCE,
until: UNTIL,
bucket_seconds: 1800,
clients: [
{ client: "192.0.2.30", buckets: [40, 20] },
{ client: "192.0.2.31", buckets: [20, 20] },
],
other: [0, 0],
coverage: COVERAGE,
};
const TYPES: StatsTypes = {
period: "24h",
since: SINCE,
until: UNTIL,
types: [
{ qtype: 1, count: 600 },
{ qtype: 28, count: 300 },
{ qtype: null, count: 100 },
],
coverage: COVERAGE,
};
const ROUTES: StatsRoutes = {
period: "24h",
since: SINCE,
until: UNTIL,
routes: [
{ route: "upstream", source: "https://dns.example/dns-query", count: 500 },
{ route: "blocked", source: null, count: 250 },
@@ -83,22 +51,27 @@ const ROUTES: StatsRoutes = {
coverage: COVERAGE,
};
/** The same shapes an hour wide, so a period change is observable in every panel. */
const HOUR = {
totals: { ...TOTALS, period: "1h", since: UNTIL - 3600, queries: 12, blocked: 3, clients: 2 } as StatsTotals,
timeseries: { ...SERIES, period: "1h", since: UNTIL - 3600, bucket_seconds: 60, buckets: [] } as StatsTimeseries,
clients: { ...CLIENTS, period: "1h", since: UNTIL - 3600, clients: [], other: [] } as StatsClients,
types: { ...TYPES, period: "1h", since: UNTIL - 3600, types: [] } as StatsTypes,
routes: { ...ROUTES, period: "1h", since: UNTIL - 3600, routes: [] } as StatsRoutes,
/** The same shape an hour wide and empty, so a period change is observable. */
const HOUR: Overview = {
...OVERVIEW,
period: "1h",
since: UNTIL - 3600,
bucket_seconds: 60,
totals: { queries: 12, blocked: 3, clients: 2, avg_response_time_us: 2345 },
buckets: [],
clients: [],
other: [],
types: [],
routes: [],
};
let healthBody: Health;
let failing: Set<string>;
let failing: boolean;
/** The registered clients, as `/api/clients` answers them. */
let registered: { ip: string; name: string; learned_name: string }[];
let coverageComplete: boolean;
/** Paths held in flight, so a test can look at the page while one is pending. */
let delayed: Map<string, Promise<void>>;
/** Held in flight, so a test can look at the page while the request is pending. */
let delayed: Promise<void> | null;
function json(payload: unknown, status = 200): Response {
return new Response(JSON.stringify(payload), { status, headers: { "content-type": "application/json" } });
@@ -110,27 +83,18 @@ function withCoverage<T extends { coverage: typeof COVERAGE }>(body: T): T {
beforeEach(() => {
healthBody = health();
failing = new Set();
failing = false;
registered = [];
coverageComplete = true;
delayed = new Map();
delayed = null;
vi.stubGlobal(
"fetch",
vi.fn(async (input: RequestInfo | URL) => {
const url = String(input);
const hour = url.includes("period=1h");
for (const [path, body] of [
["/api/stats/timeseries", hour ? HOUR.timeseries : SERIES],
["/api/stats/clients", hour ? HOUR.clients : CLIENTS],
["/api/stats/types", hour ? HOUR.types : TYPES],
["/api/stats/routes", hour ? HOUR.routes : ROUTES],
["/api/stats", hour ? HOUR.totals : TOTALS],
] as const) {
if (!url.startsWith(path)) continue;
if (failing.has(path)) return json({ error: "endpoint unavailable" }, 400);
const held = delayed.get(path);
if (held !== undefined) await held;
return json(withCoverage(body));
if (url.startsWith("/api/overview")) {
if (failing) return json({ error: "endpoint unavailable" }, 400);
if (delayed !== null) await delayed;
return json(withCoverage(url.includes("period=1h") ? HOUR : OVERVIEW));
}
if (url === "/api/clients") {
return json({
@@ -203,25 +167,39 @@ test("every donut arc is outlined, so two slices of one hue still read as two",
}
});
test("a slow endpoint does not hold the page back: the panels that answered render beside it", async () => {
// Through the real route, which is the point: the loader starts the five
// requests and awaits none of them. If it awaited, the router would hold the
// whole page until the slowest answered and this would time out on the tiles.
test("the page builds a donut slice's colour from the entry's identity", async () => {
// `Donut` renders the colour it is handed and never recomputes one, so the
// mapping from identity to hue is the page's job and is pinned here.
renderApp();
await screen.findByText("1,000");
await waitFor(() => expect(within(panel("Query types")).getAllByText("A")).toHaveLength(2));
const item = within(panel("Query types")).getAllByText("A")[0].closest("li") as HTMLElement;
const swatch = item.querySelector("span[aria-hidden]") as HTMLElement;
expect(swatch.getAttribute("style")).toContain(seriesColor(qtypeKey(1)));
});
test("a request in flight leaves the heading and the picker usable behind one loading surface", async () => {
// Through the real route, which is the point: the loader starts the request
// and awaits it nowhere. If it awaited, the router would hold the whole page —
// heading and period picker included — until the response landed.
let release = () => {};
delayed.set("/api/stats/routes", new Promise<void>((resolve) => (release = resolve)));
delayed = new Promise<void>((resolve) => (release = resolve));
renderApp();
// The tiles and both charts are readable while the routes request is still
// in flight, and the panel waiting on it says so for itself.
await screen.findByText("1,000");
expect(within(panel("Queries over time")).getAllByText("Blocked").length).toBeGreaterThan(0);
expect(within(panel("Client activity over time")).getAllByText("192.0.2.30")).toHaveLength(2);
expect(within(panel("Query types")).getAllByText("A")).toHaveLength(2);
expect(within(panel("Upstream servers")).getByRole("status").textContent).toBe("Loading…");
await screen.findByRole("heading", { name: "Overview", level: 1 });
expect(screen.getByRole("button", { name: "1h" })).toBeTruthy();
// One loading state for the whole page, not one per panel.
const loading = await screen.findByText("Loading…");
expect(loading.getAttribute("role")).toBe("status");
expect(screen.getAllByText("Loading…")).toHaveLength(1);
expect(screen.queryByRole("heading", { name: "Query types" })).toBeNull();
release();
await waitFor(() => expect(within(panel("Upstream servers")).queryByRole("status")).toBeNull());
delayed = null;
await screen.findByText("1,000");
expect(screen.queryByText("Loading…")).toBeNull();
});
test("a registered client is named in the chart, an unregistered one keeps its address", async () => {
@@ -259,9 +237,10 @@ test("naming a client does not recolour its series", async () => {
expect(swatch.getAttribute("style")).toContain(seriesColor(clientKey("192.0.2.30")));
});
test("the client chart names Other even in a period where it counted nothing", async () => {
// The fixture's other series is all zeroes. Dropping it from the legend there
// would tell the reader the two named clients were every client.
test("the client chart drops Other in a period where it counted nothing", async () => {
// The fixture's other series is all zeroes. An aggregation bucket that
// aggregated nothing is a legend entry and a table column that say only that
// they are empty; the named clients stay, because a quiet client is a fact.
renderApp();
await screen.findByRole("heading", { name: "Client activity over time" });
@@ -269,8 +248,8 @@ test("the client chart names Other even in a period where it counted nothing", a
expect(chart).toBeTruthy();
// Twice each: the legend swatch and the column header of the table a screen
// reader gets instead of the graphic.
await waitFor(() => expect(within(chart as HTMLElement).getAllByText("Other")).toHaveLength(2));
expect(within(chart as HTMLElement).getAllByText("192.0.2.30")).toHaveLength(2);
await waitFor(() => expect(within(chart as HTMLElement).getAllByText("192.0.2.30")).toHaveLength(2));
expect(within(chart as HTMLElement).queryAllByText("Other")).toHaveLength(0);
});
test("the page is four tiles, two charts and two donuts — no status or issues sections", async () => {
@@ -379,17 +358,24 @@ test("the picker rescopes every panel and writes the period into the url", async
expect(screen.queryByText("1,000")).toBeNull();
});
test("one failing panel keeps its own error and leaves the rest of the page standing", async () => {
failing.add("/api/stats/routes");
test("a failed request is one error for the whole page, stated once and retryable", async () => {
failing = true;
renderApp();
await screen.findByText("1,000");
await waitFor(() => expect(within(panel("Upstream servers")).getByText("endpoint unavailable")).toBeTruthy());
expect(within(panel("Upstream servers")).getByRole("button", { name: "Retry" })).toBeTruthy();
// A failed donut never blanks the charts.
expect(screen.getByRole("img", { name: /queries over time/i })).toBeTruthy();
expect(screen.getByRole("img", { name: /client activity over time/i })).toBeTruthy();
await screen.findByText("endpoint unavailable");
// One statement of the failure, not one per panel: there is a single request
// behind every panel, so a second copy would only repeat this sentence.
expect(screen.getAllByText("endpoint unavailable")).toHaveLength(1);
expect(screen.getAllByRole("button", { name: "Retry" })).toHaveLength(1);
// The heading and the picker survive it, so the reader can rescope or retry.
expect(screen.getByRole("heading", { name: "Overview", level: 1 })).toBeTruthy();
expect(screen.getByRole("button", { name: "1h" })).toBeTruthy();
expect(screen.queryByText("Something went wrong")).toBeNull();
failing = false;
fireEvent.click(screen.getByRole("button", { name: "Retry" }));
await screen.findByText("1,000");
expect(screen.getByRole("img", { name: /queries over time/i })).toBeTruthy();
});
test("an incomplete window states its watermark once for the whole page", async () => {
+61 -142
View File
@@ -8,26 +8,26 @@
* The period is URL state, so a view is a link: `/overview?period=1h` opens
* exactly what the sender was reading.
*
* Every panel reads the same window (`overviewWindow.ts`) and renders on its
* own. A donut whose request failed shows its own error while the charts keep
* their data, and no two panels ever describe different spans.
* One request feeds every panel (`overviewWindow.ts`), so the page has one
* loading state and one error state rather than six: there is no longer a
* partial answer to render, and nothing left for a panel to disagree about.
*/
import * as stylex from "@stylexjs/stylex";
import { useNavigate, useSearch } from "@tanstack/react-router";
import CoverageNotice from "@/lib/CoverageNotice";
import InlineError from "@/lib/InlineError";
import { qtypeName } from "@/features/queries/qtype";
import type { Period, StatsRoutes, StatsTypes } from "@/lib/types";
import { styles as shared } from "@/ui/styles";
import { qtypeName } from "@/features/provenance/qtype";
import type { Overview, OverviewRouteRow, OverviewTypeRow } from "@/lib/types";
import { colors } from "@/ui/tokens.stylex";
import ClientChart from "./ClientChart";
import Donut from "./Donut";
import StatTiles from "./StatTiles";
import TimeseriesChart from "./TimeseriesChart";
import type { DonutSlice } from "./donutLayout";
import type { DonutSlice } from "./Donut";
import { OverviewFrame, OverviewLoading } from "./OverviewFrame";
import { useOverviewWindow, type Panel } from "./overviewWindow";
import { DEFAULT_PERIOD, PERIODS } from "./period";
import { DEFAULT_PERIOD } from "./period";
import { qtypeKey, routeKey, seriesColor } from "./seriesColors";
/**
@@ -48,48 +48,6 @@ const ROUTE_LABELS = {
} as const;
const styles = stylex.create({
page: {
display: "flex",
flexDirection: "column",
gap: "1rem",
},
headingRow: {
display: "flex",
flexWrap: "wrap",
alignItems: "center",
justifyContent: "space-between",
gap: "0.75rem",
},
heading: {
fontSize: "1.5rem",
lineHeight: "2rem",
fontWeight: 600,
},
periodGroup: {
display: "flex",
gap: "0.25rem",
},
period: {
borderStyle: "none",
borderRadius: "0.25rem",
paddingInline: "0.625rem",
paddingBlock: "0.25rem",
fontSize: "0.875rem",
lineHeight: "1.25rem",
},
/** The pressed fill is heavier than `surfaceHover`, so a hover cannot mimic it. */
periodSelected: {
backgroundColor: {
default: "oklch(92% 0.004 286.32)",
"@media (prefers-color-scheme: dark)": "oklch(37% 0.013 285.805)",
},
color: colors.text,
fontWeight: 500,
},
periodIdle: {
backgroundColor: { default: "transparent", ":hover": colors.surfaceHover },
color: colors.textSecondary,
},
panel: {
borderRadius: "0.25rem",
borderWidth: 1,
@@ -110,54 +68,20 @@ const styles = stylex.create({
gap: "1rem",
gridTemplateColumns: { default: "minmax(0, 1fr)", [TWO_COLUMN]: "repeat(2, minmax(0, 1fr))" },
},
loading: {
fontSize: "0.875rem",
lineHeight: "1.25rem",
color: colors.textMuted,
},
});
function PeriodPicker({ period, onChange }: { period: Period; onChange: (period: Period) => void }) {
return (
<div role="group" aria-label="Period" {...stylex.props(styles.periodGroup)}>
{PERIODS.map((option) => (
<button
key={option}
type="button"
aria-pressed={option === period}
onClick={() => onChange(option)}
{...stylex.props(
styles.period,
option === period ? styles.periodSelected : styles.periodIdle,
shared.focusRing,
)}
>
{option}
</button>
))}
</div>
);
}
/**
* One panel's three states. Loading and error are the panel's own: a failure
* here never reaches past this box, which is what keeps a failed donut from
* blanking the charts beside it.
* The page's three states. The heading and the period picker stay put through
* all three, so the reader can rescope or retry without waiting for anything.
*/
function PanelBody<T>({ panel, children }: { panel: Panel<T>; children: (data: T) => React.ReactNode }) {
function PageBody({ panel, children }: { panel: Panel<Overview>; children: (data: Overview) => React.ReactNode }) {
if (panel.status === "error") return <InlineError error={panel.error} onRetry={panel.retry} />;
if (panel.status === "loading") {
return (
<p role="status" {...stylex.props(styles.loading, shared.pulse)}>
Loading
</p>
);
}
if (panel.status === "loading") return <OverviewLoading />;
return <>{children(panel.data)}</>;
}
function typeSlices(data: StatsTypes): DonutSlice[] {
return data.types.map((row) => ({
function typeSlices(types: OverviewTypeRow[]): DonutSlice[] {
return types.map((row) => ({
key: qtypeKey(row.qtype),
label: row.qtype === null ? "Unknown" : qtypeName(row.qtype),
value: row.count,
@@ -171,8 +95,8 @@ function typeSlices(data: StatsTypes): DonutSlice[] {
* appear under two kinds and two rows can both be "Unknown". The four
* source-less kinds are their own label and need no qualifier.
*/
function routeSlices(data: StatsRoutes): DonutSlice[] {
return data.routes.map((row) => {
function routeSlices(routes: OverviewRouteRow[]): DonutSlice[] {
return routes.map((row) => {
const named = row.route === "upstream" || row.route === "forward_zone";
return {
key: routeKey(row.route, row.source),
@@ -190,59 +114,54 @@ export default function OverviewPage() {
const overview = useOverviewWindow(period);
return (
<div {...stylex.props(styles.page)}>
<div {...stylex.props(styles.headingRow)}>
<h1 {...stylex.props(styles.heading)}>Overview</h1>
<PeriodPicker
period={period}
onChange={(next) => void navigate({ search: (prev) => ({ ...prev, period: next }) })}
/>
</div>
<OverviewFrame
period={period}
onChange={(next) => void navigate({ search: (prev) => ({ ...prev, period: next }) })}
>
<PageBody panel={overview}>
{(data) => (
<>
<StatTiles stats={{ since: data.since, until: data.until, ...data.totals }} />
<PanelBody panel={overview.totals}>{(totals) => <StatTiles stats={totals} />}</PanelBody>
{/* One notice for the page: every panel came out of this one
response, so a second copy would only repeat this sentence. */}
<CoverageNotice coverage={data.coverage} />
{/* One notice for the page: every panel is judged against the same window,
so a second copy would only repeat this sentence. */}
{overview.coverage !== null && <CoverageNotice coverage={overview.coverage} />}
<section aria-labelledby="overview-queries" {...stylex.props(styles.panel)}>
<h2 id="overview-queries" {...stylex.props(styles.panelHeading)}>
Queries over time
</h2>
<TimeseriesChart data={data} />
</section>
<section aria-labelledby="overview-queries" {...stylex.props(styles.panel)}>
<h2 id="overview-queries" {...stylex.props(styles.panelHeading)}>
Queries over time
</h2>
<PanelBody panel={overview.timeseries}>{(data) => <TimeseriesChart data={data} />}</PanelBody>
</section>
<section aria-labelledby="overview-clients" {...stylex.props(styles.panel)}>
<h2 id="overview-clients" {...stylex.props(styles.panelHeading)}>
Client activity over time
</h2>
<ClientChart data={data} />
</section>
<section aria-labelledby="overview-clients" {...stylex.props(styles.panel)}>
<h2 id="overview-clients" {...stylex.props(styles.panelHeading)}>
Client activity over time
</h2>
<PanelBody panel={overview.clients}>{(data) => <ClientChart data={data} />}</PanelBody>
</section>
<div {...stylex.props(styles.donutRow)}>
<section aria-labelledby="overview-types" {...stylex.props(styles.panel)}>
<h2 id="overview-types" {...stylex.props(styles.panelHeading)}>
Query types
</h2>
<PanelBody panel={overview.types}>
{(data) => <Donut slices={typeSlices(data)} caption="Queries by DNS type" unit="Queries" />}
</PanelBody>
</section>
<section aria-labelledby="overview-routes" {...stylex.props(styles.panel)}>
<h2 id="overview-routes" {...stylex.props(styles.panelHeading)}>
Upstream servers
</h2>
<PanelBody panel={overview.routes}>
{(data) => (
<Donut
slices={routeSlices(data)}
caption="Queries by how they were answered"
unit="Queries"
/>
)}
</PanelBody>
</section>
</div>
</div>
<div {...stylex.props(styles.donutRow)}>
<section aria-labelledby="overview-types" {...stylex.props(styles.panel)}>
<h2 id="overview-types" {...stylex.props(styles.panelHeading)}>
Query types
</h2>
<Donut slices={typeSlices(data.types)} caption="Queries by DNS type" unit="Queries" />
</section>
<section aria-labelledby="overview-routes" {...stylex.props(styles.panel)}>
<h2 id="overview-routes" {...stylex.props(styles.panelHeading)}>
Upstream servers
</h2>
<Donut
slices={routeSlices(data.routes)}
caption="Queries by how they were answered"
unit="Queries"
/>
</section>
</div>
</>
)}
</PageBody>
</OverviewFrame>
);
}
+9 -3
View File
@@ -5,7 +5,7 @@
* typographic, so the eye ranks the figures rather than the panels, and a tile
* never implies a state it is not reporting.
*
* The Activity links carry the bounds the **stats response** returned, not
* The Activity links carry the bounds the **overview response** returned, not
* bounds computed here a client-computed window would send the reader to a
* slightly different span than the one they were just reading.
*/
@@ -13,7 +13,7 @@
import * as stylex from "@stylexjs/stylex";
import { Link } from "@tanstack/react-router";
import { formatMicros } from "@/lib/format";
import type { StatsTotals } from "@/lib/types";
import type { OverviewTotals } from "@/lib/types";
import { styles as shared } from "@/ui/styles";
import { colors } from "@/ui/tokens.stylex";
@@ -101,7 +101,13 @@ function Tile({
);
}
export default function StatTiles({ stats }: { stats: StatsTotals }) {
/** The window's totals with the bounds they were measured over. */
export interface StatTilesData extends OverviewTotals {
since: number;
until: number;
}
export default function StatTiles({ stats }: { stats: StatTilesData }) {
const window = {
mode: "history" as const,
since: stats.since,
@@ -1,25 +1,25 @@
import { render, screen, within } from "@testing-library/react";
import { fireEvent, render, screen, within } from "@testing-library/react";
import * as stylex from "@stylexjs/stylex";
import type { StatsTimeseries } from "@/lib/types";
import { formatTime } from "@/lib/format";
import type { Bucket } from "@/lib/types";
import { styles as shared } from "@/ui/styles";
import TimeseriesChart from "./TimeseriesChart";
import TimeseriesChart, { type TimeseriesData } from "./TimeseriesChart";
const SINCE = 1_700_000_000;
function timeseries(bucketCount: number): StatsTimeseries {
return {
period: "24h",
since: SINCE,
until: SINCE + bucketCount * 1800,
bucket_seconds: 1800,
coverage: { complete: true, available_since: SINCE },
buckets: Array.from({ length: bucketCount }, (_, i) => ({
function timeseries(buckets: Bucket[]): TimeseriesData {
return { since: SINCE, bucket_seconds: 1800, buckets };
}
function counting(bucketCount: number): TimeseriesData {
return timeseries(
Array.from({ length: bucketCount }, (_, i) => ({
ts: SINCE + i * 1800,
queries: i + 1,
blocked: 1,
cached: 1,
})),
};
);
}
/** The element wearing the shared hidden style, found by its compiled classes. */
@@ -29,8 +29,13 @@ function hiddenElement(container: HTMLElement): Element | null {
return container.querySelector(classes.map((name) => `.${name}`).join(""));
}
/** The transparent per-bucket hit targets, in bucket order. */
function overlayRects(container: HTMLElement): SVGRectElement[] {
return Array.from(container.querySelectorAll<SVGRectElement>('rect[fill="transparent"]'));
}
test("the data table is the SVG's accessible equivalent", () => {
render(<TimeseriesChart data={timeseries(3)} />);
render(<TimeseriesChart data={counting(3)} />);
expect(screen.getByRole("img", { name: /queries over time/i })).toBeTruthy();
const table = screen.getByRole("table", { name: "Queries per time bucket" });
@@ -44,9 +49,339 @@ test("the data table is the SVG's accessible equivalent", () => {
* push the document's scroll height a screen past the app shell.
*/
test("the hidden data table is clipped by a block wrapper, not by the table itself", () => {
const { container } = render(<TimeseriesChart data={timeseries(48)} />);
const { container } = render(<TimeseriesChart data={counting(48)} />);
const hidden = hiddenElement(container);
expect(hidden?.tagName).toBe("DIV");
expect(hidden?.querySelector("table")).not.toBeNull();
});
/**
* "Allowed" is what the reported total leaves over, and the three counts come
* from separate columns that a partial write can leave inconsistent. A negative
* remainder would draw a segment upside down.
*/
test("allowed is the remainder of the reported total, clamped at zero", () => {
const { container } = render(
<TimeseriesChart data={timeseries([{ ts: SINCE, queries: 10, blocked: 8, cached: 5 }])} />,
);
const row = within(screen.getByRole("table")).getAllByRole("row")[1];
expect(
within(row)
.getAllByRole("cell")
.map((cell) => cell.textContent),
).toEqual(["10", "8", "5", "0"]);
// Blocked and cached are drawn; the empty "allowed" segment is not.
expect(container.querySelectorAll('rect[fill="#3b82f6"]')).toHaveLength(0);
// The scale comes from the reported total, not from the stack's own sum.
// Scaling to the sum would reach 13 here and leave the bar four fifths of the
// way up a plot whose own numbers say it is full.
const ticks = Array.from(container.querySelectorAll(".visx-axis-left text")).map((tick) => tick.textContent);
expect(ticks[ticks.length - 1]).toBe("10");
});
test("a window with no queries says so instead of drawing an empty grid", () => {
const { container } = render(
<TimeseriesChart
data={timeseries([
{ ts: SINCE, queries: 0, blocked: 0, cached: 0 },
{ ts: SINCE + 1800, queries: 0, blocked: 0, cached: 0 },
])}
/>,
);
expect(screen.getByText("No queries in this period.")).toBeTruthy();
expect(container.querySelector("svg")).toBeNull();
});
test("no bucket at all says the same thing", () => {
render(<TimeseriesChart data={timeseries([])} />);
expect(screen.getByText("No queries in this period.")).toBeTruthy();
});
/**
* The three category colours are fixed constants of this chart rather than
* anything derived from `seriesColors`, which would paint "other" grey.
*/
test("the segments are drawn in this chart's own category colours", () => {
const { container } = render(
<TimeseriesChart data={timeseries([{ ts: SINCE, queries: 100, blocked: 40, cached: 10 }])} />,
);
const fills = Array.from(container.querySelectorAll("rect"))
.map((rect) => rect.getAttribute("fill"))
.filter((fill) => fill !== "transparent");
expect(fills).toEqual(["#ef4444", "#059669", "#3b82f6"]);
});
/**
* The graphic carries no `<title>`: it duplicated the tooltip, the browser
* showed it after its own delay and out of the app's styling, and the hidden
* table is already the accessible equivalent.
*/
test("hover text is the tooltip alone, never a bare SVG title", () => {
const { container } = render(<TimeseriesChart data={counting(3)} />);
expect(container.querySelectorAll("title")).toHaveLength(0);
});
/** The hit target is the whole column slot, including the space above a short stack. */
test("each bucket's hit target spans the full plot height", () => {
const { container } = render(<TimeseriesChart data={counting(3)} />);
const rects = overlayRects(container);
expect(rects).toHaveLength(3);
for (const rect of rects) {
expect(rect.getAttribute("y")).toBe("8");
expect(rect.getAttribute("height")).toBe("210");
}
});
/**
* A band scale spends a gap after the last column as well as between them, so a
* full-step hit target on the last bucket would reach into the right margin and
* catch pointers that are past the plot entirely.
*/
test("the last hit target stops at the plot's right edge", () => {
const { container } = render(<TimeseriesChart data={counting(3)} />);
const last = overlayRects(container).at(-1) as SVGRectElement;
const right = Number(last.getAttribute("x")) + Number(last.getAttribute("width"));
// 640 fallback width, less the 44px left and 8px right margins.
expect(right).toBeCloseTo(44 + 588, 6);
});
test("pointing at a bucket names its total and every series, and dims the rest", () => {
const { container } = render(
<TimeseriesChart
data={timeseries([
{ ts: SINCE, queries: 100, blocked: 40, cached: 10 },
{ ts: SINCE + 1800, queries: 50, blocked: 5, cached: 5 },
])}
/>,
);
fireEvent.mouseOver(overlayRects(container)[0]);
const tooltip = container.querySelector("dl") as HTMLElement;
expect(tooltip.previousElementSibling?.textContent).toBe(formatTime(SINCE));
const values = Array.from(tooltip.querySelectorAll("dd")).map((dd) => dd.textContent);
expect(values).toEqual(["100", "40", "10", "50"]);
const terms = Array.from(tooltip.querySelectorAll("dt")).map((dt) => dt.textContent);
expect(terms).toEqual(["Queries", "Blocked", "Cached", "Allowed"]);
// One swatch per series, in the colour the segment is drawn in.
const swatches = Array.from(tooltip.querySelectorAll("dt span")).map((span) => span.getAttribute("style"));
expect(swatches[0]).toContain("#ef4444");
expect(swatches[1]).toContain("#059669");
expect(swatches[2]).toContain("#3b82f6");
const stacks = Array.from(container.querySelectorAll("svg > g.visx-group[opacity]"));
expect(stacks.map((group) => group.getAttribute("opacity"))).toEqual(["1", "0.55"]);
});
/**
* The tooltip sits 8px down from the chart's top edge and 8px to the side of the
* slot it names the placement the hand-rolled tooltip had, restored over
* visx's own 10px defaults.
*/
test("the tooltip is offset 8px from the chart top and from the bucket it names", () => {
const { container } = render(<TimeseriesChart data={counting(2)} />);
fireEvent.mouseOver(overlayRects(container)[0]);
// The first slot spans 44 to 44 + step, so its centre is 191.5 and the
// tooltip sits 8px right of it. visx rounds the placement to whole pixels.
const tooltip = container.querySelector(".visx-tooltip") as HTMLElement;
expect(tooltip.style.transform).toBe("translate(200px, 8px)");
});
/**
* `withBoundingRects` measures its node once, on mount. Sharing one mount across
* buckets would place a wide bucket's tooltip with a narrow bucket's measured
* width, which flips or clips it at the right-hand edge of the plot. Remounting
* per bucket is what forces a fresh measurement; jsdom reports every rect as
* zero, so the mount is what this can observe, not the measurement itself.
*/
test("each bucket gets its own tooltip mount, so each is measured for itself", () => {
const { container } = render(<TimeseriesChart data={counting(2)} />);
const rects = overlayRects(container);
fireEvent.mouseOver(rects[0]);
const first = container.querySelector(".visx-tooltip");
fireEvent.mouseOver(rects[1]);
const second = container.querySelector(".visx-tooltip");
expect(first).not.toBeNull();
expect(second).not.toBe(first);
});
/**
* The window refreshes every half minute under an open tooltip. The tooltip
* holds a bucket index and reads the numbers out of the render it is drawing, so
* a refresh that keeps the same buckets updates it rather than leaving last
* minute's counts on screen.
*/
test("a refresh in the same window retells the hovered bucket with the new counts", () => {
const before = timeseries([
{ ts: SINCE, queries: 100, blocked: 40, cached: 10 },
{ ts: SINCE + 1800, queries: 50, blocked: 5, cached: 5 },
]);
const { container, rerender } = render(<TimeseriesChart data={before} />);
fireEvent.mouseOver(overlayRects(container)[0]);
expect(
Array.from((container.querySelector("dl") as HTMLElement).querySelectorAll("dd")).map((dd) => dd.textContent),
).toEqual(["100", "40", "10", "50"]);
rerender(
<TimeseriesChart
data={timeseries([
{ ts: SINCE, queries: 120, blocked: 60, cached: 10 },
{ ts: SINCE + 1800, queries: 50, blocked: 5, cached: 5 },
])}
/>,
);
const values = Array.from((container.querySelector("dl") as HTMLElement).querySelectorAll("dd")).map(
(dd) => dd.textContent,
);
expect(values).toEqual(["120", "60", "10", "50"]);
});
/**
* A rolling window is the case a stored copy gets wrong: the bucket the pointer
* was over is gone, so index 0 now names a different span. The tooltip goes away
* rather than describing a bucket that is no longer drawn, and nothing stays
* dimmed behind it. Rolling back to the earlier window must not bring it back
* either: the selection is deleted when the window moves, not held aside.
*/
test("a refresh that rolls the window takes the tooltip down instead of relabelling it", () => {
const { container, rerender } = render(
<TimeseriesChart
data={timeseries([
{ ts: SINCE, queries: 100, blocked: 40, cached: 10 },
{ ts: SINCE + 1800, queries: 50, blocked: 5, cached: 5 },
])}
/>,
);
fireEvent.mouseOver(overlayRects(container)[0]);
expect(container.querySelectorAll("dl")).toHaveLength(1);
rerender(
<TimeseriesChart
data={{
...timeseries([
{ ts: SINCE + 1800, queries: 50, blocked: 5, cached: 5 },
{ ts: SINCE + 3600, queries: 70, blocked: 7, cached: 7 },
]),
since: SINCE + 1800,
}}
/>,
);
expect(container.querySelectorAll("dl")).toHaveLength(0);
const stacks = Array.from(container.querySelectorAll("svg > g.visx-group[opacity]"));
expect(stacks.every((group) => group.getAttribute("opacity") === "1")).toBe(true);
rerender(
<TimeseriesChart
data={timeseries([
{ ts: SINCE, queries: 100, blocked: 40, cached: 10 },
{ ts: SINCE + 1800, queries: 50, blocked: 5, cached: 5 },
])}
/>,
);
expect(container.querySelectorAll("dl")).toHaveLength(0);
});
/**
* The same bucket can change width between refreshes a count crossing a digit
* boundary, a client name arriving and a mount measured at the old width is
* placed at the wrong one. A content change therefore remounts the tooltip, the
* same way moving between buckets does.
*/
test("a bucket whose numbers change is remounted, so it is measured again", () => {
const { container, rerender } = render(
<TimeseriesChart data={timeseries([{ ts: SINCE, queries: 9, blocked: 4, cached: 1 }])} />,
);
fireEvent.mouseOver(overlayRects(container)[0]);
const first = container.querySelector(".visx-tooltip");
rerender(<TimeseriesChart data={timeseries([{ ts: SINCE, queries: 1000, blocked: 4, cached: 1 }])} />);
const second = container.querySelector(".visx-tooltip");
expect(first).not.toBeNull();
expect(second).not.toBeNull();
expect(second).not.toBe(first);
});
test("leaving the chart takes the tooltip and the dimming with it", () => {
const { container } = render(<TimeseriesChart data={counting(3)} />);
fireEvent.mouseOver(overlayRects(container)[0]);
expect(container.querySelectorAll("dl")).toHaveLength(1);
fireEvent.mouseOut(container.querySelector("svg") as SVGSVGElement);
expect(container.querySelectorAll("dl")).toHaveLength(0);
const stacks = Array.from(container.querySelectorAll("svg > g.visx-group[opacity]"));
expect(stacks.every((group) => group.getAttribute("opacity") === "1")).toBe(true);
});
/**
* The third series is every query neither blocked nor served from cache. It was
* called "Other", which named the arithmetic rather than the thing.
*/
test("the remainder series is called Allowed everywhere it surfaces", () => {
const { container } = render(
<TimeseriesChart data={timeseries([{ ts: SINCE, queries: 10, blocked: 2, cached: 3 }])} />,
);
const legend = Array.from(container.querySelectorAll("ul li")).map((item) => item.textContent);
expect(legend).toEqual(["Blocked", "Cached", "Allowed"]);
expect(
within(screen.getByRole("table"))
.getAllByRole("columnheader")
.map((cell) => cell.textContent),
).toEqual(["Time", "Queries", "Blocked", "Cached", "Allowed"]);
fireEvent.mouseOver(overlayRects(container)[0]);
const terms = Array.from((container.querySelector("dl") as HTMLElement).querySelectorAll("dt"));
expect(terms.map((term) => term.textContent)).toEqual(["Queries", "Blocked", "Cached", "Allowed"]);
expect(screen.queryByText("Other")).toBeNull();
});
/**
* A window where everything was blocked or served from cache has no allowed
* queries, and that is worth reading rather than hiding: an absent series would
* say the same thing as a series nobody looked at. The three categories are all
* real answers a query can get, so none of them is dropped for counting zero.
* The client chart's "Other" is dropped at zero, but that one aggregates clients
* beyond the top eight rather than naming a kind of answer.
*/
test("a window with nothing allowed keeps the series at zero", () => {
const { container } = render(
<TimeseriesChart
data={timeseries([
{ ts: SINCE, queries: 4, blocked: 4, cached: 0 },
{ ts: SINCE + 1800, queries: 6, blocked: 6, cached: 0 },
])}
/>,
);
const legend = Array.from(container.querySelectorAll("ul li")).map((item) => item.textContent);
expect(legend).toEqual(["Blocked", "Cached", "Allowed"]);
fireEvent.mouseOver(overlayRects(container)[0]);
const tooltip = container.querySelector("dl") as HTMLElement;
expect(Array.from(tooltip.querySelectorAll("dt")).map((term) => term.textContent)).toEqual([
"Queries",
"Blocked",
"Cached",
"Allowed",
]);
expect(Array.from(tooltip.querySelectorAll("dd")).map((value) => value.textContent)).toEqual(["4", "4", "0", "0"]);
});
+154 -246
View File
@@ -1,107 +1,49 @@
import { useEffect, useRef, useState } from "react";
import * as stylex from "@stylexjs/stylex";
import { Group } from "@visx/group";
import { BarStack } from "@visx/shape";
import { formatTime } from "@/lib/format";
import type { StatsTimeseries } from "@/lib/types";
import type { Bucket } from "@/lib/types";
import { styles as shared } from "@/ui/styles";
import { colors } from "@/ui/tokens.stylex";
import { isEmptyTimeseries, layoutTimeseries, type BarLayout } from "./chartLayout";
import {
BucketOverlay,
CHART_HEIGHT,
ChartFrame,
ChartRoot,
ChartTooltip,
EmptyChart,
StackSegment,
bandScale,
labelTickValues,
plotArea,
slotCenter,
useActiveIndex,
useMeasuredWidth,
valueScale,
valueTicks,
type TooltipContent,
} from "./chartKit";
// Series colors validated for CVD separation and 3:1 surface contrast in both
// modes (Tailwind red-500 / blue-500 / emerald-600; same hex light and dark).
// The third key stays `other` — it is the colour key and the response field, and
// renaming it would repaint the series. Only what the reader sees is "Allowed".
const SERIES = [
{ key: "blocked", label: "Blocked", color: "#ef4444" },
{ key: "cached", label: "Cached", color: "#059669" },
{ key: "other", label: "Other", color: "#3b82f6" },
{ key: "other", label: "Allowed", color: "#3b82f6" },
] as const;
const CHART_HEIGHT = 240;
const FALLBACK_WIDTH = 640;
type Series = (typeof SERIES)[number];
type SeriesKey = Series["key"];
const SERIES_COLOR: Record<SeriesKey, string> = {
blocked: SERIES[0].color,
cached: SERIES[1].color,
other: SERIES[2].color,
};
const styles = stylex.create({
empty: {
display: "flex",
alignItems: "center",
justifyContent: "center",
height: CHART_HEIGHT,
borderRadius: "0.25rem",
borderWidth: 1,
borderStyle: "dashed",
borderColor: colors.borderStrong,
fontSize: "0.875rem",
lineHeight: "1.25rem",
color: colors.textMuted,
},
chartRoot: {
position: "relative",
},
tooltip: {
pointerEvents: "none",
position: "absolute",
top: "0.5rem",
zIndex: 10,
borderRadius: "0.25rem",
borderWidth: 1,
borderStyle: "solid",
borderColor: colors.borderStrong,
backgroundColor: colors.surfaceRaised,
paddingInline: "0.75rem",
paddingBlock: "0.5rem",
fontSize: "0.75rem",
lineHeight: "1rem",
boxShadow: "0 1px 3px 0 rgb(0 0 0 / 0.1), 0 1px 2px -1px rgb(0 0 0 / 0.1)",
},
/** Dynamic: the tooltip flips to whichever side of the bar has room. */
tooltipLeft: (left: number) => ({ left, right: null }),
tooltipRight: (right: number) => ({ left: null, right }),
tooltipTitle: {
fontWeight: 500,
},
tooltipList: {
display: "flex",
flexDirection: "column",
gap: "0.125rem",
marginTop: "0.25rem",
},
tooltipRow: {
display: "flex",
alignItems: "center",
justifyContent: "space-between",
gap: "1rem",
},
tooltipTerm: {
display: "flex",
alignItems: "center",
gap: "0.375rem",
color: colors.textMuted,
},
swatch: {
display: "inline-block",
borderRadius: "0.125rem",
},
/** Dynamic: the swatch takes the series colour the SVG bars are drawn in. */
swatchColor: (color: string) => ({ backgroundColor: color }),
swatchSmall: {
width: "0.5rem",
height: "0.5rem",
},
swatchLarge: {
width: "0.625rem",
height: "0.625rem",
},
gridLine: {
stroke: colors.border,
},
axisLine: {
stroke: colors.borderStrong,
},
axisLabel: {
fill: colors.textMuted,
fontSize: "10px",
},
/** The hairline separating touching segments is the page ground, not a colour. */
segment: {
stroke: colors.surface,
},
legend: {
marginTop: "0.5rem",
display: "flex",
@@ -117,177 +59,141 @@ const styles = stylex.create({
alignItems: "center",
gap: "0.375rem",
},
swatch: {
display: "inline-block",
width: "0.625rem",
height: "0.625rem",
borderRadius: "0.125rem",
},
/** Dynamic: the swatch takes the series colour the SVG bars are drawn in. */
swatchColor: (color: string) => ({ backgroundColor: color }),
});
function useContainerWidth(): [React.RefObject<HTMLDivElement | null>, number] {
const ref = useRef<HTMLDivElement>(null);
const [width, setWidth] = useState(0);
useEffect(() => {
const el = ref.current;
if (el === null) return;
setWidth(el.clientWidth);
if (typeof ResizeObserver === "undefined") return;
const observer = new ResizeObserver(() => setWidth(el.clientWidth));
observer.observe(el);
return () => observer.disconnect();
}, []);
return [ref, width];
interface Column {
ts: number;
queries: number;
blocked: number;
cached: number;
/** queries - blocked - cached, clamped at 0. */
other: number;
}
const compact = new Intl.NumberFormat(undefined, { notation: "compact" });
function formatTick(ts: number, bucketSeconds: number): string {
const date = new Date(ts * 1000);
if (bucketSeconds >= 86_400) {
return new Intl.DateTimeFormat(undefined, { month: "short", day: "numeric" }).format(date);
}
return new Intl.DateTimeFormat(undefined, { hour: "numeric", minute: "2-digit" }).format(date);
function columnsOf(buckets: Bucket[]): Column[] {
return buckets.map((bucket) => ({
ts: bucket.ts,
queries: bucket.queries,
blocked: bucket.blocked,
cached: bucket.cached,
other: Math.max(0, bucket.queries - bucket.blocked - bucket.cached),
}));
}
function barSummary(bar: BarLayout): string {
return `${formatTime(bar.bucket.ts)}: ${bar.bucket.queries} queries, ${bar.bucket.blocked} blocked, ${bar.bucket.cached} cached`;
function tooltipOf(column: Column): TooltipContent {
return {
title: formatTime(column.ts),
rows: [
{ key: "queries", label: "Queries", value: String(column.queries) },
...SERIES.map((series) => ({
key: series.key,
label: series.label,
color: series.color,
value: String(column[series.key]),
})),
],
};
}
function Tooltip({ bar, chartWidth }: { bar: BarLayout; chartWidth: number }) {
const centerX = bar.slot.x + bar.slot.width / 2;
const leftHalf = centerX < chartWidth / 2;
const side = leftHalf
? styles.tooltipLeft(Math.min(centerX + 8, chartWidth - 160))
: styles.tooltipRight(chartWidth - centerX + 8);
return (
<div {...stylex.props(styles.tooltip, side)}>
<div {...stylex.props(styles.tooltipTitle)}>{formatTime(bar.bucket.ts)}</div>
<dl {...stylex.props(styles.tooltipList)}>
<div {...stylex.props(styles.tooltipRow)}>
<dt {...stylex.props(styles.tooltipTerm)}>Queries</dt>
<dd {...stylex.props(shared.tabularNums)}>{bar.bucket.queries}</dd>
</div>
{SERIES.map((series) => (
<div key={series.key} {...stylex.props(styles.tooltipRow)}>
<dt {...stylex.props(styles.tooltipTerm)}>
<span
aria-hidden="true"
{...stylex.props(styles.swatch, styles.swatchSmall, styles.swatchColor(series.color))}
/>
{series.label}
</dt>
<dd {...stylex.props(shared.tabularNums)}>
{series.key === "other" ? bar.other : bar.bucket[series.key]}
</dd>
</div>
))}
</dl>
</div>
);
/**
* The slice of the Overview body this chart draws. Declared here rather than
* taken whole, so what the chart reads is stated where it is read.
*/
export interface TimeseriesData {
since: number;
bucket_seconds: number;
buckets: Bucket[];
}
export default function TimeseriesChart({ data }: { data: StatsTimeseries }) {
const [containerRef, measuredWidth] = useContainerWidth();
const [hovered, setHovered] = useState<number | null>(null);
const width = measuredWidth > 0 ? measuredWidth : FALLBACK_WIDTH;
export default function TimeseriesChart({ data }: { data: TimeseriesData }) {
const [containerRef, width] = useMeasuredWidth();
// A hover survives a re-render only while it still names the same bucket at
// the same place: a poll that rolls the window, or a resize, retires it.
const hovered = useActiveIndex(`${data.since}:${data.bucket_seconds}:${data.buckets.length}:${width}`);
if (data.buckets.length === 0 || isEmptyTimeseries(data.buckets)) {
return (
<div ref={containerRef} {...stylex.props(styles.empty)}>
No queries in this period.
</div>
);
if (data.buckets.length === 0 || data.buckets.every((bucket) => bucket.queries === 0)) {
return <EmptyChart containerRef={containerRef} />;
}
const layout = layoutTimeseries(data.buckets, width, CHART_HEIGHT);
const baseline = layout.plot.y + layout.plot.height;
const hoveredBar = hovered !== null ? layout.bars[hovered] : undefined;
const columns = columnsOf(data.buckets);
const timestamps = columns.map((column) => column.ts);
const plot = plotArea(width);
const xScale = bandScale(timestamps, plot);
// The scale is the reported total rather than the stack's own sum: blocked
// and cached are parts of `queries`, which a clamped `other` can undercount.
const yScale = valueScale(Math.max(...columns.map((column) => column.queries)), [plot.bottom, plot.y]);
const yTicks = valueTicks(yScale);
return (
<div ref={containerRef} {...stylex.props(styles.chartRoot)}>
<ChartRoot containerRef={containerRef}>
<svg
role="img"
aria-label={`Queries over time, ${data.buckets.length} buckets: blocked, cached and other queries per bucket`}
aria-label={`Queries over time, ${data.buckets.length} buckets: ${SERIES.map((series) => series.label.toLowerCase()).join(", ")} queries per bucket`}
width="100%"
height={CHART_HEIGHT}
viewBox={`0 0 ${width} ${CHART_HEIGHT}`}
onMouseLeave={() => setHovered(null)}
onMouseLeave={hovered.clear}
>
{layout.yTicks.map((tick) => (
<g key={tick.value}>
<line
x1={layout.plot.x}
x2={layout.plot.x + layout.plot.width}
y1={tick.y}
y2={tick.y}
{...stylex.props(styles.gridLine)}
/>
<text
x={layout.plot.x - 6}
y={tick.y}
textAnchor="end"
dominantBaseline="middle"
{...stylex.props(styles.axisLabel, shared.tabularNums)}
>
{compact.format(tick.value)}
</text>
</g>
))}
<line
x1={layout.plot.x}
x2={layout.plot.x + layout.plot.width}
y1={baseline}
y2={baseline}
{...stylex.props(styles.axisLine)}
<ChartFrame
plot={plot}
yScale={yScale}
yTicks={yTicks}
xScale={xScale}
xTickValues={labelTickValues(timestamps, plot.width)}
bucketSeconds={data.bucket_seconds}
/>
{layout.xTicks.map((tick) => (
<text
key={tick.ts}
x={tick.x}
y={baseline + 14}
textAnchor="middle"
{...stylex.props(styles.axisLabel)}
>
{formatTick(tick.ts, data.bucket_seconds)}
</text>
))}
{layout.bars.map((bar, i) => (
<g key={bar.bucket.ts} opacity={hovered === null || hovered === i ? 1 : 0.55}>
{SERIES.map((series) => {
const rect = bar.segments[series.key];
if (rect.height <= 0) return null;
return (
<rect
key={series.key}
x={rect.x}
y={rect.y}
width={rect.width}
height={rect.height}
fill={series.color}
strokeWidth={rect.width > 3 ? 1 : 0}
{...stylex.props(styles.segment)}
/>
);
})}
</g>
))}
{layout.bars.map((bar, i) => (
<rect
key={bar.bucket.ts}
x={bar.slot.x}
y={bar.slot.y}
width={bar.slot.width}
height={bar.slot.height}
fill="transparent"
onMouseEnter={() => setHovered(i)}
>
<title>{barSummary(bar)}</title>
</rect>
))}
<BarStack<Column, SeriesKey>
data={columns}
keys={SERIES.map((series) => series.key)}
x={(column) => column.ts}
xScale={xScale}
yScale={yScale}
color={(key) => SERIES_COLOR[key]}
>
{(stacks) =>
columns.map((column, index) => (
<Group
key={column.ts}
opacity={hovered.index === null || hovered.index === index ? 1 : 0.55}
>
{stacks.map((stack) => {
const bar = stack.bars[index];
return (
<StackSegment
key={stack.key}
x={bar.x}
y={bar.y}
width={bar.width}
height={bar.height}
fill={bar.color}
/>
);
})}
</Group>
))
}
</BarStack>
<BucketOverlay plot={plot} values={timestamps} xScale={xScale} onEnter={hovered.show} />
</svg>
{hoveredBar !== undefined && <Tooltip bar={hoveredBar} chartWidth={width} />}
{hovered.index !== null && (
<ChartTooltip
index={hovered.index}
content={tooltipOf(columns[hovered.index])}
left={slotCenter(xScale, timestamps[hovered.index], plot)}
/>
)}
<ul {...stylex.props(styles.legend)}>
{SERIES.map((series) => (
<li key={series.key} {...stylex.props(styles.legendItem)}>
<span
aria-hidden="true"
{...stylex.props(styles.swatch, styles.swatchLarge, styles.swatchColor(series.color))}
/>
<span aria-hidden="true" {...stylex.props(styles.swatch, styles.swatchColor(series.color))} />
{series.label}
</li>
))}
@@ -299,24 +205,26 @@ export default function TimeseriesChart({ data }: { data: StatsTimeseries }) {
<tr>
<th scope="col">Time</th>
<th scope="col">Queries</th>
<th scope="col">Blocked</th>
<th scope="col">Cached</th>
<th scope="col">Other</th>
{SERIES.map((series) => (
<th key={series.key} scope="col">
{series.label}
</th>
))}
</tr>
</thead>
<tbody>
{layout.bars.map((bar) => (
<tr key={bar.bucket.ts}>
<th scope="row">{formatTime(bar.bucket.ts)}</th>
<td>{bar.bucket.queries}</td>
<td>{bar.bucket.blocked}</td>
<td>{bar.bucket.cached}</td>
<td>{bar.other}</td>
{columns.map((column) => (
<tr key={column.ts}>
<th scope="row">{formatTime(column.ts)}</th>
<td>{column.queries}</td>
{SERIES.map((series) => (
<td key={series.key}>{column[series.key]}</td>
))}
</tr>
))}
</tbody>
</table>
</div>
</div>
</ChartRoot>
);
}
@@ -0,0 +1,149 @@
import { render } from "@testing-library/react";
import {
CHART_HEIGHT,
ChartFrame,
bandPaddingInner,
bandScale,
labelTickValues,
plotArea,
useMeasuredWidth,
valueScale,
valueTicks,
} from "./chartKit";
describe("useMeasuredWidth", () => {
/**
* jsdom lays nothing out, so `clientWidth` is 0 there and a chart scaled to it
* would draw a zero-width plot. Every chart test depends on this fallback.
*/
test("an unmeasurable container falls back to 640", () => {
function Probe() {
const [ref, width] = useMeasuredWidth();
return <div ref={ref} data-testid="probe" data-width={width} />;
}
const { getByTestId } = render(<Probe />);
expect(getByTestId("probe").getAttribute("data-width")).toBe("640");
});
});
describe("valueScale", () => {
test("the data maximum is nicened outward and the ticks land on round numbers", () => {
const scale = valueScale(1780, [240, 0]);
expect(scale.domain()).toEqual([0, 1800]);
expect(scale.ticks(5)).toEqual([0, 500, 1000, 1500]);
expect(valueTicks(scale)).toEqual([0, 500, 1000, 1500]);
});
});
describe("bandPaddingInner", () => {
/**
* The gap is a constant number of pixels, so the fraction it takes of one slot
* has to fall as the slots get wider. 24 hourly columns in a 1388px plot is
* the 24h window on a full-width panel.
*/
test("the fraction is two pixels per column of the plot's width", () => {
expect(bandPaddingInner(24, 1388)).toBeCloseTo((2 * 24) / 1388, 12);
expect(bandPaddingInner(24, 1388)).toBeCloseTo(0.034582, 6);
});
/**
* Past the cap the gap would be most of the slot and the columns would vanish
* into slivers, so it stops at half the slot and the bars stay visible.
*/
test("the gap never takes more than half a slot", () => {
expect(bandPaddingInner(1000, 100)).toBe(0.5);
});
test("no columns and no width mean no gap to compute", () => {
expect(bandPaddingInner(0, 640)).toBe(0);
expect(bandPaddingInner(24, 0)).toBe(0);
});
});
describe("labelTickValues", () => {
/** A week of hourly buckets in a panel the width of a laptop window. */
test("labels thin out to one every 21 buckets at 748px of plot", () => {
const timestamps = Array.from({ length: 168 }, (_, i) => i * 3600);
expect(labelTickValues(timestamps, 748)).toEqual([0, 75600, 151200, 226800, 302400, 378000, 453600, 529200]);
});
test("every bucket is labelled when they all fit", () => {
expect(labelTickValues([0, 3600, 7200], 748)).toEqual([0, 3600, 7200]);
});
});
/** The frame on its own, at the width the charts draw at in jsdom. */
function renderFrame() {
const plot = plotArea(640);
const timestamps = [0, 3600, 7200];
const yScale = valueScale(100, [plot.bottom, plot.y]);
const yTicks = valueTicks(yScale);
const { container } = render(
<svg width={640} height={CHART_HEIGHT}>
<ChartFrame
plot={plot}
yScale={yScale}
yTicks={yTicks}
xScale={bandScale(timestamps, plot)}
xTickValues={timestamps}
bucketSeconds={3600}
/>
</svg>,
);
return { container, plot, yTicks };
}
describe("ChartFrame", () => {
test("the value axis is bare: no axis line, no tick marks, labels 6px left of the plot", () => {
const { container, plot, yTicks } = renderFrame();
const axis = container.querySelector(".visx-axis-left") as SVGGElement;
expect(axis.getAttribute("transform")).toBe(`translate(${plot.x}, 0)`);
expect(axis.querySelector("line")).toBeNull();
const labels = Array.from(axis.querySelectorAll("text"));
expect(labels.map((label) => label.textContent)).toEqual(yTicks.map(String));
for (const label of labels) {
expect(label.getAttribute("x")).toBe("0");
expect(label.getAttribute("dx")).toBe("-6px");
expect(label.getAttribute("text-anchor")).toBe("end");
// The label sits on the tick, centred: visx's own 0.25em nudge is
// cancelled so it does not double up with the middle baseline.
expect(label.getAttribute("dy")).toBe("0");
expect(label.getAttribute("dominant-baseline")).toBe("middle");
}
});
/**
* The time axis keeps its baseline and drops its tick marks, and the labels
* are placed by the group transform plus `dy` rather than by the font-size
* guess visx would otherwise make.
*/
test("the time axis keeps only its baseline, and its labels sit 16px below it", () => {
const { container, plot } = renderFrame();
const axis = container.querySelector(".visx-axis-bottom") as SVGGElement;
expect(axis.getAttribute("transform")).toBe(`translate(0, ${plot.bottom})`);
const lines = Array.from(axis.querySelectorAll("line"));
expect(lines).toHaveLength(1);
expect(lines[0].getAttribute("class")).toContain("visx-axis-line");
for (const label of Array.from(axis.querySelectorAll("text"))) {
expect(label.getAttribute("y")).toBe("0");
expect(label.getAttribute("dy")).toBe("16px");
expect(label.getAttribute("text-anchor")).toBe("middle");
}
});
test("every grid line has a labelled tick on it and no tick floats without a line", () => {
const { container } = renderFrame();
const gridY = Array.from(container.querySelectorAll(".visx-rows line")).map((line) => line.getAttribute("y1"));
const labelY = Array.from(container.querySelectorAll(".visx-axis-left text")).map((label) =>
label.getAttribute("y"),
);
expect(gridY.length).toBeGreaterThan(0);
expect(gridY).toEqual(labelY);
});
});
+498
View File
@@ -0,0 +1,498 @@
/**
* The plumbing the two bar charts on Overview share: the width measurement, the
* scales, the axis and grid chrome, the segment separator, the per-bucket hit
* target and the tooltip.
*
* Geometry is visx's; the chrome is ours. visx's own axis defaults draw tick
* marks, an axis line on both axes and Arial 10px in #222, none of which this
* app wants, so every wrapper here turns those off and dresses the result in
* StyleX tokens instead.
*/
import { useEffect, useRef, useState } from "react";
import * as stylex from "@stylexjs/stylex";
import { AxisBottom, AxisLeft, type TickRendererProps } from "@visx/axis";
import { GridRows } from "@visx/grid";
import { scaleBand, scaleLinear } from "@visx/scale";
import { TooltipWithBounds } from "@visx/tooltip";
import { styles as shared } from "@/ui/styles";
import { colors } from "@/ui/tokens.stylex";
export const CHART_HEIGHT = 240;
export const MARGIN = { top: 8, right: 8, bottom: 22, left: 44 } as const;
/** The width a chart draws at before a measurement exists — jsdom, and the first paint. */
const FALLBACK_WIDTH = 640;
/** How many pixels one x-axis label needs to itself before the labels thin out. */
const MIN_X_LABEL_PX = 90;
/** The gap between two touching columns, in pixels of the drawn plot. */
const BAR_GAP_PX = 2;
const Y_TICK_COUNT = 5;
export interface Plot {
x: number;
y: number;
width: number;
height: number;
/** The y of the baseline: the bottom edge of the plot. */
bottom: number;
}
export function plotArea(width: number): Plot {
const height = Math.max(0, CHART_HEIGHT - MARGIN.top - MARGIN.bottom);
return {
x: MARGIN.left,
y: MARGIN.top,
width: Math.max(0, width - MARGIN.left - MARGIN.right),
height,
bottom: MARGIN.top + height,
};
}
/**
* The container's width, measured on mount and on every resize. Deliberately
* `useEffect` rather than `useLayoutEffect`: the first paint draws at the
* fallback width and the measured width lands a frame later, which is the
* timing the charts have always had.
*/
export function useMeasuredWidth(): [React.RefObject<HTMLDivElement | null>, number] {
const ref = useRef<HTMLDivElement>(null);
const [width, setWidth] = useState(0);
useEffect(() => {
const el = ref.current;
if (el === null) return;
setWidth(el.clientWidth);
if (typeof ResizeObserver === "undefined") return;
const observer = new ResizeObserver(() => setWidth(el.clientWidth));
observer.observe(el);
return () => observer.disconnect();
}, []);
return [ref, width > 0 ? width : FALLBACK_WIDTH];
}
/**
* The value axis. `nice: true` rounds the domain outward, so the `max` passed
* here is the data's own maximum and not a pre-rounded one.
*/
export function valueScale(max: number, range: [number, number]) {
return scaleLinear<number>({ domain: [0, max], range, nice: true });
}
export type ValueScale = ReturnType<typeof valueScale>;
/** The tick values the grid and the value axis both draw. */
export function valueTicks(scale: ValueScale): number[] {
return scale.ticks(Y_TICK_COUNT);
}
/**
* How wide the gap between two columns is, as a fraction of one column's slot.
* A constant would make the gap grow with the column: 30 daily columns and 60
* minute columns are drawn at the same pixel gap, so the fraction has to be
* computed from how many columns share the plot.
*/
export function bandPaddingInner(bucketCount: number, plotWidth: number): number {
if (bucketCount === 0 || plotWidth <= 0) return 0;
return Math.min(0.5, (BAR_GAP_PX * bucketCount) / plotWidth);
}
/** The time axis: one band per bucket, in the order the buckets were given. */
export function bandScale(values: number[], plot: Plot) {
return scaleBand<number>({
domain: values,
range: [plot.x, plot.x + plot.width],
paddingInner: bandPaddingInner(values.length, plot.width),
});
}
export type BandScale = ReturnType<typeof bandScale>;
/**
* The subset of bucket timestamps that get an x-axis label. A 30-day window is
* 30 columns and a 1-hour window is 60, so at narrow widths the labels have to
* thin out rather than overprint each other.
*/
export function labelTickValues(values: number[], plotWidth: number): number[] {
if (values.length === 0 || plotWidth <= 0) return values.slice(0, 1);
const step = Math.max(1, Math.ceil((values.length * MIN_X_LABEL_PX) / plotWidth));
return values.filter((_, i) => i % step === 0);
}
const compact = new Intl.NumberFormat(undefined, { notation: "compact" });
export function formatBucketTime(ts: number, bucketSeconds: number): string {
const date = new Date(ts * 1000);
if (bucketSeconds >= 86_400) {
return new Intl.DateTimeFormat(undefined, { month: "short", day: "numeric" }).format(date);
}
return new Intl.DateTimeFormat(undefined, { hour: "numeric", minute: "2-digit" }).format(date);
}
const styles = stylex.create({
empty: {
display: "flex",
alignItems: "center",
justifyContent: "center",
height: CHART_HEIGHT,
borderRadius: "0.25rem",
borderWidth: 1,
borderStyle: "dashed",
borderColor: colors.borderStrong,
fontSize: "0.875rem",
lineHeight: "1.25rem",
color: colors.textMuted,
},
root: {
position: "relative",
},
axisLabel: {
fill: colors.textMuted,
fontSize: "10px",
},
/** The hairline separating touching segments is the page ground, not a colour. */
segment: {
stroke: colors.surface,
},
tooltip: {
pointerEvents: "none",
position: "absolute",
zIndex: 10,
borderRadius: "0.25rem",
borderWidth: 1,
borderStyle: "solid",
borderColor: colors.borderStrong,
backgroundColor: colors.surfaceRaised,
paddingInline: "0.75rem",
paddingBlock: "0.5rem",
fontSize: "0.75rem",
lineHeight: "1rem",
boxShadow: "0 1px 3px 0 rgb(0 0 0 / 0.1), 0 1px 2px -1px rgb(0 0 0 / 0.1)",
},
tooltipTitle: {
fontWeight: 500,
},
tooltipList: {
display: "flex",
flexDirection: "column",
gap: "0.125rem",
marginTop: "0.25rem",
},
tooltipRow: {
display: "flex",
alignItems: "center",
justifyContent: "space-between",
gap: "1rem",
},
tooltipTerm: {
display: "flex",
alignItems: "center",
gap: "0.375rem",
color: colors.textMuted,
},
swatch: {
display: "inline-block",
width: "0.5rem",
height: "0.5rem",
borderRadius: "0.125rem",
},
/** Dynamic: the swatch takes the series colour the SVG bars are drawn in. */
swatchColor: (color: string) => ({ backgroundColor: color }),
});
/** Both charts' "nothing here" state, which is also where the ref to measure lives. */
export function EmptyChart({ containerRef }: { containerRef: React.RefObject<HTMLDivElement | null> }) {
return (
<div ref={containerRef} {...stylex.props(styles.empty)}>
No queries in this period.
</div>
);
}
export function ChartRoot({
containerRef,
children,
}: {
containerRef: React.RefObject<HTMLDivElement | null>;
children: React.ReactNode;
}) {
return (
<div ref={containerRef} {...stylex.props(styles.root)}>
{children}
</div>
);
}
/**
* visx's `Ticks` derives a label's `y` from a guessed font size, which is wrong
* here because the size comes from a stylesheet it cannot read. The label is
* therefore placed by the axis group's own transform plus the `dy` the caller
* passes, and the guessed `y` is dropped.
*/
function TickLabel({ x, dx, dy, textAnchor, dominantBaseline, formattedValue }: TickRendererProps) {
return (
<text
x={x}
y={0}
dx={dx}
dy={dy}
textAnchor={textAnchor}
dominantBaseline={dominantBaseline}
{...stylex.props(styles.axisLabel)}
>
{formattedValue}
</text>
);
}
/** As `TickLabel`, but keeping the scaled tick position the vertical axis puts in `y`. */
function ValueTickLabel({ x, y, dx, dy, textAnchor, dominantBaseline, formattedValue }: TickRendererProps) {
return (
<text
x={x}
y={y}
dx={dx}
dy={dy}
textAnchor={textAnchor}
dominantBaseline={dominantBaseline}
{...stylex.props(styles.axisLabel, shared.tabularNums)}
>
{formattedValue}
</text>
);
}
/**
* The grid and the two axes. The grid lines and the value labels are computed
* from one tick array, so every drawn line has a number beside it and no number
* floats without one.
*/
export function ChartFrame({
plot,
yScale,
yTicks,
xScale,
xTickValues,
bucketSeconds,
}: {
plot: Plot;
yScale: ValueScale;
yTicks: number[];
xScale: BandScale;
xTickValues: number[];
bucketSeconds: number;
}) {
return (
<>
<GridRows scale={yScale} tickValues={yTicks} left={plot.x} width={plot.width} stroke={colors.border} />
<AxisLeft
scale={yScale}
left={plot.x}
tickValues={yTicks}
numTicks={Y_TICK_COUNT}
hideAxisLine
hideTicks
tickLength={0}
tickFormat={(value) => compact.format(Number(value))}
// `dy` overrides AxisLeft's own 0.25em nudge, which would double up
// with the middle baseline this app centres its value labels on.
tickLabelProps={{ dx: "-6px", dy: 0, textAnchor: "end", dominantBaseline: "middle" }}
tickComponent={ValueTickLabel}
/>
<AxisBottom
scale={xScale}
top={plot.bottom}
tickValues={xTickValues}
hideTicks
tickLength={0}
stroke={colors.borderStrong}
tickFormat={(value) => formatBucketTime(Number(value), bucketSeconds)}
tickLabelProps={{ dy: "16px", textAnchor: "middle" }}
tickComponent={TickLabel}
/>
</>
);
}
/**
* One segment of a stacked column. The separator is drawn only once the column
* is wide enough for two neighbouring segments to read as two shapes; below
* that it would be most of the bar.
*/
export function StackSegment({
x,
y,
width,
height,
fill,
}: {
x: number;
y: number;
width: number;
height: number;
fill: string;
}) {
if (height <= 0) return null;
return (
<rect
x={x}
y={y}
width={width}
height={height}
fill={fill}
strokeWidth={width > 3 ? 1 : 0}
{...stylex.props(styles.segment)}
/>
);
}
/**
* The transparent hit targets: one per bucket, spanning the whole plot height so
* that pointing at the empty space above a short column still selects it.
*
* A slot is a whole band step, gap included, so that no pixel between two
* columns belongs to neither. The last slot is clipped to the plot's right edge:
* the band scale spends the trailing gap on nothing, and a full-step rect there
* would reach into the right margin.
*/
export function BucketOverlay({
plot,
values,
xScale,
onEnter,
}: {
plot: Plot;
values: number[];
xScale: BandScale;
onEnter: (index: number) => void;
}) {
const step = xScale.step();
const right = plot.x + plot.width;
return (
<>
{values.map((value, index) => {
const x = xScale(value) ?? plot.x;
return (
<rect
key={value}
x={x}
y={plot.y}
width={Math.max(0, Math.min(step, right - x))}
height={plot.height}
fill="transparent"
onMouseEnter={() => onEnter(index)}
/>
);
})}
</>
);
}
/** The x a bucket's tooltip points at: the centre of its slot, not of its narrower bar. */
export function slotCenter(xScale: BandScale, value: number, plot: Plot): number {
return (xScale(value) ?? plot.x) + xScale.step() / 2;
}
/**
* Which item the pointer is on, and nothing else a bucket in the bar charts, a
* slice in the donuts.
*
* Deliberately not `useTooltip`: holding the hovered item's numbers and screen
* position in state decouples them from the data. The window refreshes every
* half minute and the container can be resized under an open tooltip, and either
* one leaves a stored copy describing an item that has moved or changed. Only
* the index is kept, so the caller reads the values and the coordinates out of
* the render it is currently drawing.
*
* `windowKey` is what makes a changing set safe: when the items themselves
* change, index `i` no longer names the one the pointer was over, so the
* selection made against the old key is dropped and the tooltip goes away.
*/
export function useActiveIndex(windowKey: string) {
const [selection, setSelection] = useState<{ index: number; key: string } | null>(null);
// A selection belongs to the window it was made in. Deleting it as soon as the
// key moves on is what stops a returning key — a resize back to a previous
// width, a poll that restores a bucket count — from reviving a hover the
// pointer never made.
if (selection !== null && selection.key !== windowKey) setSelection(null);
return {
index: selection !== null && selection.key === windowKey ? selection.index : null,
show: (index: number) => setSelection({ index, key: windowKey }),
clear: () => setSelection(null),
};
}
export interface TooltipRow {
key: string;
label: string;
/** Omitted for a row that names no drawn shape, such as a bucket's total. */
color?: string;
value: string;
}
/** What a tooltip says, whichever chart opened it: a heading and its rows. */
export interface TooltipContent {
title: string;
rows: TooltipRow[];
}
/**
* `TooltipWithBounds` positions itself with an inline transform and drops it
* when `unstyled` is set, so the default look is replaced by handing it an empty
* style object rather than by turning styling off.
*/
const NO_INLINE_STYLE = {};
/** The gap the tooltip keeps from its anchor point. */
const TOOLTIP_OFFSET = 8;
export function ChartTooltip({
content,
index,
left,
top = 0,
}: {
content: TooltipContent;
/** Which item the tooltip names; part of what forces a fresh measurement. */
index: number;
left: number;
top?: number;
}) {
// `withBoundingRects` measures once, in `componentDidMount`, and never again,
// so every content change needs its own mount to be measured at its own size.
// The index alone is not enough: a refresh can widen the same item's text past
// a digit boundary, or resolve a client's name, and the stale width would place
// it wrongly at the right edge.
const measureKey = [index, content.title, ...content.rows.map((row) => `${row.label}=${row.value}`)].join("|");
return (
<TooltipWithBounds
key={measureKey}
left={left}
top={top}
offsetLeft={TOOLTIP_OFFSET}
offsetTop={TOOLTIP_OFFSET}
style={NO_INLINE_STYLE}
className={stylex.props(styles.tooltip).className}
>
<div {...stylex.props(styles.tooltipTitle)}>{content.title}</div>
<dl {...stylex.props(styles.tooltipList)}>
{content.rows.map((row) => (
<div key={row.key} {...stylex.props(styles.tooltipRow)}>
<dt {...stylex.props(styles.tooltipTerm)}>
{row.color !== undefined && (
<span
aria-hidden="true"
{...stylex.props(styles.swatch, styles.swatchColor(row.color))}
/>
)}
{row.label}
</dt>
<dd {...stylex.props(shared.tabularNums)}>{row.value}</dd>
</div>
))}
</dl>
</TooltipWithBounds>
);
}
@@ -1,93 +0,0 @@
import type { Bucket } from "@/lib/types";
import { MARGIN, isEmptyTimeseries, layoutTimeseries, niceTicks } from "./chartLayout";
function bucket(ts: number, queries: number, blocked = 0, cached = 0): Bucket {
return { ts, queries, blocked, cached };
}
describe("niceTicks", () => {
test("zero max yields a single zero tick", () => {
expect(niceTicks(0)).toEqual([0]);
});
test("picks a 1/2/5 step and extends past max", () => {
expect(niceTicks(7)).toEqual([0, 2, 4, 6, 8]);
expect(niceTicks(100)).toEqual([0, 50, 100]);
expect(niceTicks(1234)).toEqual([0, 500, 1000, 1500]);
});
});
describe("isEmptyTimeseries", () => {
test("true for no buckets and for all-zero buckets", () => {
expect(isEmptyTimeseries([])).toBe(true);
expect(isEmptyTimeseries([bucket(0, 0), bucket(60, 0)])).toBe(true);
});
test("false when any bucket has queries", () => {
expect(isEmptyTimeseries([bucket(0, 0), bucket(60, 3)])).toBe(false);
});
});
describe("layoutTimeseries", () => {
test("segment heights are proportional and stack to the queries total", () => {
const layout = layoutTimeseries([bucket(0, 100, 40, 10), bucket(60, 50, 0, 0)], 480, 240);
const plotHeight = 240 - MARGIN.top - MARGIN.bottom;
const baseline = MARGIN.top + plotHeight;
const [first, second] = layout.bars;
expect(layout.scaleMax).toBe(100);
expect(first.other).toBe(50);
expect(first.segments.blocked.height).toBeCloseTo(plotHeight * 0.4);
expect(first.segments.cached.height).toBeCloseTo(plotHeight * 0.1);
expect(first.segments.other.height).toBeCloseTo(plotHeight * 0.5);
expect(first.segments.blocked.y + first.segments.blocked.height).toBeCloseTo(baseline);
expect(first.segments.cached.y + first.segments.cached.height).toBeCloseTo(first.segments.blocked.y);
expect(first.segments.other.y + first.segments.other.height).toBeCloseTo(first.segments.cached.y);
expect(first.segments.other.y).toBeCloseTo(MARGIN.top);
expect(second.segments.other.height).toBeCloseTo(plotHeight * 0.5);
});
test("clamps other at zero when blocked + cached exceed queries", () => {
const layout = layoutTimeseries([bucket(0, 10, 8, 5)], 480, 240);
expect(layout.bars[0].other).toBe(0);
expect(layout.bars[0].segments.other.height).toBe(0);
});
test("zero data still lays out zero-height bars on a unit scale", () => {
const layout = layoutTimeseries([bucket(0, 0), bucket(60, 0)], 480, 240);
expect(layout.scaleMax).toBe(1);
expect(layout.bars).toHaveLength(2);
for (const bar of layout.bars) {
expect(bar.segments.blocked.height).toBe(0);
expect(bar.segments.cached.height).toBe(0);
expect(bar.segments.other.height).toBe(0);
}
expect(layout.yTicks).toEqual([{ value: 0, y: MARGIN.top + (240 - MARGIN.top - MARGIN.bottom) }]);
});
test("single bucket fills the plot width minus the gap", () => {
const layout = layoutTimeseries([bucket(0, 5, 1, 1)], 480, 240);
const plotWidth = 480 - MARGIN.left - MARGIN.right;
const bar = layout.bars[0];
expect(bar.slot.width).toBeCloseTo(plotWidth);
expect(bar.segments.blocked.width).toBeCloseTo(plotWidth - 2);
expect(bar.segments.blocked.x).toBeCloseTo(MARGIN.left + 1);
expect(layout.xTicks).toEqual([{ ts: 0, x: MARGIN.left + plotWidth / 2 }]);
});
test("x ticks thin out when buckets outnumber the label budget", () => {
const buckets = Array.from({ length: 168 }, (_, i) => bucket(i * 3600, i));
const layout = layoutTimeseries(buckets, 800, 240);
expect(layout.xTicks.length).toBeLessThan(buckets.length / 10);
expect(layout.xTicks[0].ts).toBe(0);
const xs = layout.xTicks.map((tick) => tick.x);
expect([...xs].sort((a, b) => a - b)).toEqual(xs);
});
test("empty bucket list yields no bars and no x ticks", () => {
const layout = layoutTimeseries([], 480, 240);
expect(layout.bars).toEqual([]);
expect(layout.xTicks).toEqual([]);
expect(layout.scaleMax).toBe(1);
});
});
-182
View File
@@ -1,182 +0,0 @@
import type { Bucket } from "@/lib/types";
export interface Rect {
x: number;
y: number;
width: number;
height: number;
}
export interface BarLayout {
bucket: Bucket;
/** queries - blocked - cached, clamped at 0. */
other: number;
slot: Rect;
segments: {
blocked: Rect;
cached: Rect;
other: Rect;
};
}
export interface ChartLayout {
width: number;
height: number;
plot: Rect;
scaleMax: number;
bars: BarLayout[];
yTicks: { value: number; y: number }[];
xTicks: { ts: number; x: number }[];
}
export const MARGIN = { top: 8, right: 8, bottom: 22, left: 44 } as const;
const BAR_GAP = 2;
const MIN_X_LABEL_PX = 90;
/** Tick values from 0 upward in a 1/2/5 step, extended until the last tick covers `max`. */
export function niceTicks(max: number, targetCount = 4): number[] {
if (max <= 0) return [0];
const rawStep = max / targetCount;
const magnitude = Math.pow(10, Math.floor(Math.log10(rawStep)));
const normalized = rawStep / magnitude;
const step = (normalized <= 1 ? 1 : normalized <= 2 ? 2 : normalized <= 5 ? 5 : 10) * magnitude;
const ticks: number[] = [];
for (let value = 0; ; value += step) {
ticks.push(value);
if (value >= max) break;
}
return ticks;
}
export function isEmptyTimeseries(buckets: Bucket[]): boolean {
return buckets.every((bucket) => bucket.queries === 0);
}
function plotRect(width: number, height: number): Rect {
return {
x: MARGIN.left,
y: MARGIN.top,
width: Math.max(0, width - MARGIN.left - MARGIN.right),
height: Math.max(0, height - MARGIN.top - MARGIN.bottom),
};
}
/**
* How many columns share one x-axis label. A 30-day window is 30 columns and a
* 1-hour window is 60, so at narrow widths the labels have to thin out rather
* than overprint each other.
*/
function labelStepFor(count: number, plotWidth: number): number {
if (count === 0 || plotWidth <= 0) return 1;
return Math.max(1, Math.ceil((count * MIN_X_LABEL_PX) / plotWidth));
}
/** One stacked column: the series values in the order the caller stacks them. */
export interface StackedColumn {
ts: number;
total: number;
slot: Rect;
segments: Rect[];
}
export interface StackedLayout {
width: number;
height: number;
plot: Rect;
scaleMax: number;
columns: StackedColumn[];
yTicks: { value: number; y: number }[];
xTicks: { ts: number; x: number }[];
}
/**
* The same geometry as the query-volume chart, for an arbitrary number of
* series. The scale comes from the tallest column's own total, because every
* series here is a disjoint part of the whole rather than a highlighted subset
* of a separately reported total.
*/
export function layoutStacked(
columns: { ts: number; values: number[] }[],
width: number,
height: number,
): StackedLayout {
const plot = plotRect(width, height);
const totals = columns.map((column) => column.values.reduce((sum, value) => sum + value, 0));
const tickValues = niceTicks(Math.max(0, ...totals));
const scaleMax = Math.max(tickValues[tickValues.length - 1], 1);
const baseline = plot.y + plot.height;
const toHeight = (value: number) => (value / scaleMax) * plot.height;
const slotWidth = columns.length > 0 ? plot.width / columns.length : 0;
const barWidth = Math.max(1, slotWidth - BAR_GAP);
const laidOut: StackedColumn[] = columns.map((column, i) => {
const slotX = plot.x + i * slotWidth;
const barX = slotX + (slotWidth - barWidth) / 2;
let top = baseline;
const segments = column.values.map((value) => {
const segmentHeight = toHeight(value);
top -= segmentHeight;
return { x: barX, y: top, width: barWidth, height: segmentHeight };
});
return {
ts: column.ts,
total: totals[i],
slot: { x: slotX, y: plot.y, width: slotWidth, height: plot.height },
segments,
};
});
const step = labelStepFor(columns.length, plot.width);
return {
width,
height,
plot,
scaleMax,
columns: laidOut,
yTicks: tickValues.map((value) => ({ value, y: baseline - toHeight(value) })),
xTicks: laidOut
.filter((_, i) => i % step === 0)
.map((column) => ({ ts: column.ts, x: column.slot.x + column.slot.width / 2 })),
};
}
export function layoutTimeseries(buckets: Bucket[], width: number, height: number): ChartLayout {
const plot = plotRect(width, height);
const maxQueries = buckets.reduce((max, bucket) => Math.max(max, bucket.queries), 0);
const tickValues = niceTicks(maxQueries);
const scaleMax = Math.max(tickValues[tickValues.length - 1], 1);
const baseline = plot.y + plot.height;
const toHeight = (value: number) => (value / scaleMax) * plot.height;
const slotWidth = buckets.length > 0 ? plot.width / buckets.length : 0;
const barWidth = Math.max(1, slotWidth - BAR_GAP);
const bars: BarLayout[] = buckets.map((bucket, i) => {
const slotX = plot.x + i * slotWidth;
const barX = slotX + (slotWidth - barWidth) / 2;
const other = Math.max(0, bucket.queries - bucket.blocked - bucket.cached);
const blockedH = toHeight(bucket.blocked);
const cachedH = toHeight(bucket.cached);
const otherH = toHeight(other);
return {
bucket,
other,
slot: { x: slotX, y: plot.y, width: slotWidth, height: plot.height },
segments: {
blocked: { x: barX, y: baseline - blockedH, width: barWidth, height: blockedH },
cached: { x: barX, y: baseline - blockedH - cachedH, width: barWidth, height: cachedH },
other: { x: barX, y: baseline - blockedH - cachedH - otherH, width: barWidth, height: otherH },
},
};
});
const yTicks = tickValues.map((value) => ({ value, y: baseline - toHeight(value) }));
const labelStep = labelStepFor(buckets.length, plot.width);
const xTicks = bars
.filter((_, i) => i % labelStep === 0)
.map((bar) => ({ ts: bar.bucket.ts, x: bar.slot.x + bar.slot.width / 2 }));
return { width, height, plot, scaleMax, bars, yTicks, xTicks };
}
@@ -1,47 +0,0 @@
import { layoutDonut, type DonutSlice } from "./donutLayout";
function slice(key: string, value: number): DonutSlice {
return { key, label: key, value, color: "#000000" };
}
test("an empty breakdown has no total and no arcs to draw", () => {
expect(layoutDonut([], 100, 20)).toEqual({ size: 100, total: 0, arcs: [] });
});
test("a breakdown of nothing but zeroes is empty, not a division by zero", () => {
const layout = layoutDonut([slice("a", 0), slice("b", 0)], 100, 20);
expect(layout.total).toBe(0);
expect(layout.arcs).toEqual([]);
});
test("zero-valued entries are dropped rather than legended at 0%", () => {
const layout = layoutDonut([slice("a", 3), slice("b", 0), slice("c", 1)], 100, 20);
expect(layout.arcs.map((arc) => arc.slice.key)).toEqual(["a", "c"]);
expect(layout.total).toBe(4);
});
test("shares are of the drawn total and add up to one", () => {
const layout = layoutDonut([slice("a", 3), slice("b", 1)], 100, 20);
expect(layout.arcs.map((arc) => arc.share)).toEqual([0.75, 0.25]);
});
test("slices keep the order they were ranked in, starting at twelve o'clock", () => {
const layout = layoutDonut([slice("a", 1), slice("b", 1)], 100, 20);
expect(layout.arcs[0].d.startsWith("M 50.000 0.000")).toBe(true);
// The second slice begins where the first ended, half a turn round.
expect(layout.arcs[1].d.startsWith("M 50.000 100.000")).toBe(true);
});
test("a slice over half the ring takes the large-arc flag", () => {
const layout = layoutDonut([slice("a", 9), slice("b", 1)], 100, 20);
expect(layout.arcs[0].d).toContain("A 50 50 0 1 1");
expect(layout.arcs[1].d).toContain("A 50 50 0 0 1");
});
test("a single entry is a closed ring, not a zero-length arc that draws nothing", () => {
const layout = layoutDonut([slice("only", 7)], 100, 20);
expect(layout.arcs).toHaveLength(1);
expect(layout.arcs[0].share).toBe(1);
// Two half arcs out and two back: a lone `A` from a point to itself is a no-op.
expect(layout.arcs[0].d.match(/A /g)).toHaveLength(4);
});
@@ -1,95 +0,0 @@
/**
* Annulus geometry for the two breakdown donuts. Pure, so the arithmetic that
* decides whether a slice closes correctly is testable without a DOM.
*/
export interface DonutSlice {
/** Semantic identity: the React key, the colour key and the legend's identity. */
key: string;
label: string;
/** Disambiguates entries whose labels collide — two "Unknown"s, one name on two route kinds. */
secondary?: string;
value: number;
color: string;
}
export interface DonutArc {
slice: DonutSlice;
/** Of the whole, 0 to 1. */
share: number;
d: string;
}
export interface DonutLayout {
size: number;
total: number;
arcs: DonutArc[];
}
const START_ANGLE = -Math.PI / 2;
function point(center: number, radius: number, angle: number): string {
return `${(center + radius * Math.cos(angle)).toFixed(3)} ${(center + radius * Math.sin(angle)).toFixed(3)}`;
}
/**
* A whole-circle slice cannot be drawn as one arc start and end coincide, and
* the renderer draws nothing at all so the ring is two half arcs.
*/
function fullRing(center: number, outer: number, inner: number): string {
const top = `${center} ${center - outer}`;
const bottom = `${center} ${center + outer}`;
const innerTop = `${center} ${center - inner}`;
const innerBottom = `${center} ${center + inner}`;
return [
`M ${top}`,
`A ${outer} ${outer} 0 0 1 ${bottom}`,
`A ${outer} ${outer} 0 0 1 ${top}`,
`M ${innerTop}`,
`A ${inner} ${inner} 0 0 0 ${innerBottom}`,
`A ${inner} ${inner} 0 0 0 ${innerTop}`,
"Z",
].join(" ");
}
/**
* Slices in the order given the caller has already ranked them starting at
* twelve o'clock and running clockwise. Zero-valued slices are dropped: they
* have no arc to draw, and a legend entry reading 0 is noise.
*/
export function layoutDonut(slices: DonutSlice[], size: number, thickness: number): DonutLayout {
const drawn = slices.filter((slice) => slice.value > 0);
const total = drawn.reduce((sum, slice) => sum + slice.value, 0);
if (total <= 0) return { size, total: 0, arcs: [] };
const center = size / 2;
const outer = center;
const inner = Math.max(0, center - thickness);
if (drawn.length === 1) {
return {
size,
total,
arcs: [{ slice: drawn[0], share: 1, d: fullRing(center, outer, inner) }],
};
}
let angle = START_ANGLE;
const arcs = drawn.map((slice) => {
const share = slice.value / total;
const sweep = share * Math.PI * 2;
const end = angle + sweep;
const large = sweep > Math.PI ? 1 : 0;
const d = [
`M ${point(center, outer, angle)}`,
`A ${outer} ${outer} 0 ${large} 1 ${point(center, outer, end)}`,
`L ${point(center, inner, end)}`,
`A ${inner} ${inner} 0 ${large} 0 ${point(center, inner, angle)}`,
"Z",
].join(" ");
angle = end;
return { slice, share, d };
});
return { size, total, arcs };
}
@@ -1,74 +1,41 @@
/**
* Window coherence across the five Overview requests, migrated from the
* two-request `activityWindow` this replaces. Every behaviour that hook pinned
* is pinned here the identity, the one retry per mismatch episode, the
* terminal error, the discarded previous-period pair and the stale completion
* that must not speak now over five endpoints and with the watermark in the
* identity, plus the per-panel isolation the layout added.
* The hook over the single `/api/overview` request.
*
* The five-endpoint build reconciled five window identities here the retry per
* mismatch episode, the terminal "different window" error, the orphaned stale
* completion. One request cannot disagree with itself, so those behaviours have
* no subject left and are gone rather than ported. What survived the collapse is
* pinned below: the three states, and the one rule a single request still does
* not settle that a `keepPreviousData` body from the period the reader left
* must never render under the new period's label.
*/
import { render, screen, waitFor } from "@testing-library/react";
import { QueryClientProvider } from "@tanstack/react-query";
import { createQueryClient } from "@/lib/queryClient";
import type { Coverage, Period } from "@/lib/types";
import {
newerWindow,
sameWindow,
useOverviewWindow,
windowIdOf,
OVERVIEW_ENDPOINTS,
type OverviewEndpoint,
} from "./overviewWindow";
import type { Period } from "@/lib/types";
import { useOverviewWindow } from "./overviewWindow";
const SINCE = Date.UTC(2026, 0, 1, 0, 0) / 1000;
const UNTIL = Date.UTC(2026, 0, 2, 0, 0) / 1000;
const COVERAGE: Coverage = { complete: true, available_since: SINCE };
/** Where each endpoint's body currently ends, and what watermark it admits. */
interface Bounds {
until: number;
availableSince: number;
}
let failing: boolean;
let calls: number;
const PATHS: Record<OverviewEndpoint, string> = {
totals: "/api/stats?period=",
timeseries: "/api/stats/timeseries?period=",
clients: "/api/stats/clients?period=",
types: "/api/stats/types?period=",
routes: "/api/stats/routes?period=",
};
let bounds: Record<OverviewEndpoint, Bounds>;
let failing: Set<OverviewEndpoint>;
let calls: Record<OverviewEndpoint, number>;
/** Endpoints that answer for the page's window from their second call onward. */
let catchUp: Set<OverviewEndpoint>;
/** Held to keep one answer in flight while the test moves the page on. */
let hold: { promise: Promise<void>; release: () => void } | null;
function endpointOf(url: string): OverviewEndpoint | null {
// Longest prefix first: `/api/stats?` and `/api/stats/…` share a stem.
for (const endpoint of ["timeseries", "clients", "types", "routes", "totals"] as const) {
if (url.startsWith(PATHS[endpoint])) return endpoint;
}
return null;
}
function body(endpoint: OverviewEndpoint, period: Period): unknown {
const { until, availableSince } = bounds[endpoint];
const shared = { period, since: SINCE, until, coverage: { ...COVERAGE, available_since: availableSince } };
switch (endpoint) {
case "totals":
return { ...shared, queries: 10, blocked: 2, clients: 1, avg_response_time_us: 1000 };
case "timeseries":
return { ...shared, bucket_seconds: 3600, buckets: [] };
case "clients":
return { ...shared, bucket_seconds: 3600, clients: [], other: [] };
case "types":
return { ...shared, types: [] };
case "routes":
return { ...shared, routes: [] };
}
function body(period: Period): unknown {
return {
period,
since: SINCE,
until: UNTIL,
bucket_seconds: 1800,
totals: { queries: 10, blocked: 2, clients: 1, avg_response_time_us: 1000 },
buckets: [],
clients: [],
other: [],
types: [],
routes: [],
coverage: { complete: true, available_since: SINCE },
};
}
function json(payload: unknown, status = 200): Response {
@@ -76,55 +43,36 @@ function json(payload: unknown, status = 200): Response {
}
beforeEach(() => {
bounds = {
totals: { until: UNTIL, availableSince: SINCE },
timeseries: { until: UNTIL, availableSince: SINCE },
clients: { until: UNTIL, availableSince: SINCE },
types: { until: UNTIL, availableSince: SINCE },
routes: { until: UNTIL, availableSince: SINCE },
};
failing = new Set();
catchUp = new Set();
hold = null;
calls = { totals: 0, timeseries: 0, clients: 0, types: 0, routes: 0 };
failing = false;
calls = 0;
vi.stubGlobal(
"fetch",
vi.fn(async (input: RequestInfo | URL) => {
const url = String(input);
const endpoint = endpointOf(url);
if (endpoint === null) return json({ error: "not stubbed" }, 404);
calls[endpoint] += 1;
if (failing.has(endpoint)) return json({ error: "endpoint unavailable" }, 400);
if (catchUp.has(endpoint) && calls[endpoint] >= 2)
bounds[endpoint] = { until: UNTIL, availableSince: SINCE };
if (!url.startsWith("/api/overview")) return json({ error: "not stubbed" }, 404);
calls += 1;
if (failing) return json({ error: "endpoint unavailable" }, 400);
const period = (new URLSearchParams(url.split("?")[1]).get("period") ?? "24h") as Period;
// Built before the wait, so a held answer carries what its own request
// would have returned rather than what the page has moved on to.
const payload = json(body(endpoint, period));
if (hold !== null && endpoint === "routes" && calls.routes === 2) await hold.promise;
return payload;
return json(body(period));
}),
);
});
afterEach(() => vi.unstubAllGlobals());
/** The last retry the hook handed out, so a test can spend it. */
let lastRetry: () => void;
function Probe({ period }: { period: Period }) {
const overview = useOverviewWindow(period);
return (
<ul>
{OVERVIEW_ENDPOINTS.map((endpoint) => {
const panel = overview[endpoint];
const detail =
panel.status === "ready"
? `${panel.data.period}@${panel.data.until}/${panel.data.coverage.available_since}`
: panel.status === "error"
? (panel.error as Error).message
: "";
return <li key={endpoint}>{`${endpoint}:${panel.status}:${detail}`}</li>;
})}
</ul>
);
const panel = useOverviewWindow(period);
if (panel.status === "error") lastRetry = panel.retry;
const detail =
panel.status === "ready"
? `${panel.data.period}@${panel.data.until}`
: panel.status === "error"
? (panel.error as Error).message
: "";
return <p>{`${panel.status}:${detail}`}</p>;
}
function renderProbe(period: Period = "24h") {
@@ -144,149 +92,36 @@ function renderProbe(period: Period = "24h") {
};
}
function line(endpoint: OverviewEndpoint): string {
const item = screen.getAllByRole("listitem").find((element) => element.textContent?.startsWith(`${endpoint}:`));
if (item === undefined) throw new Error(`no probe line for ${endpoint}`);
return item.textContent ?? "";
function line(): string {
return screen.getByRole("paragraph").textContent ?? "";
}
test("the window identity is the period, both bounds and the watermark together", () => {
const base = { period: "24h" as const, since: SINCE, until: UNTIL, availableSince: SINCE };
expect(sameWindow(base, { ...base })).toBe(true);
expect(sameWindow(base, { ...base, period: "1h" })).toBe(false);
expect(sameWindow(base, { ...base, since: SINCE - 1 })).toBe(false);
expect(sameWindow(base, { ...base, until: UNTIL + 1 })).toBe(false);
// The bounds agree and the answers still describe different windows: a prune
// between the two requests moved what the same span can be answered for.
expect(sameWindow(base, { ...base, availableSince: SINCE + 60 })).toBe(false);
});
test("the newer until wins, and for equal bounds the later watermark does", () => {
const base = { period: "24h" as const, since: SINCE, until: UNTIL, availableSince: SINCE };
expect(newerWindow(base, { ...base, until: UNTIL + 60 }).until).toBe(UNTIL + 60);
expect(newerWindow({ ...base, until: UNTIL + 60 }, base).until).toBe(UNTIL + 60);
expect(newerWindow(base, { ...base, availableSince: SINCE + 60 }).availableSince).toBe(SINCE + 60);
// A newer watermark does not outrank an older window's later bound.
expect(newerWindow({ ...base, until: UNTIL + 60 }, { ...base, availableSince: SINCE + 60 }).until).toBe(UNTIL + 60);
});
test("windowIdOf reads the four fields off any of the five bodies", () => {
expect(windowIdOf({ period: "7d", since: 1, until: 2, coverage: { complete: false, available_since: 3 } })).toEqual(
{
period: "7d",
since: 1,
until: 2,
availableSince: 3,
},
);
});
test("five responses for one window render as five ready panels", async () => {
test("the page is loading until the body for the selected period arrives", async () => {
renderProbe();
await waitFor(() => expect(line("totals")).toContain("ready"));
for (const endpoint of OVERVIEW_ENDPOINTS) {
expect(line(endpoint)).toBe(`${endpoint}:ready:24h@${UNTIL}/${SINCE}`);
}
expect(line()).toBe("loading:");
await waitFor(() => expect(line()).toBe(`ready:24h@${UNTIL}`));
});
test("one endpoint behind a bucket boundary is refetched once and then agrees", async () => {
// Behind on its first answer, caught up by the time the hook asks again.
bounds.routes = { until: UNTIL - 3600, availableSince: SINCE };
catchUp.add("routes");
test("a failed request is one error for the whole page, with a retry that refetches", async () => {
failing = true;
renderProbe();
await waitFor(() => expect(line("routes")).toContain("ready"));
expect(calls.routes).toBe(2);
expect(calls.totals).toBe(1);
});
await waitFor(() => expect(line()).toBe("error:endpoint unavailable"));
const spent = calls;
test("a laggard that stays behind fails its own panel and leaves the rest rendering", async () => {
bounds.types = { until: UNTIL - 3600, availableSince: SINCE };
renderProbe();
await waitFor(() => expect(line("types")).toContain("error"));
expect(line("types")).toContain("different window");
// One retry, not a loop.
expect(calls.types).toBe(2);
for (const endpoint of ["totals", "timeseries", "clients", "routes"] as const) {
expect(line(endpoint)).toContain("ready");
}
});
test("a failed request degrades its own panel; the charts keep the window", async () => {
failing.add("routes");
renderProbe();
await waitFor(() => expect(line("routes")).toContain("error"));
expect(line("routes")).toContain("endpoint unavailable");
expect(line("timeseries")).toContain("ready");
expect(line("totals")).toContain("ready");
});
test("a watermark that advanced mid-page is a mismatch, not a mixed window", async () => {
// Same bounds, later watermark: retention pruned between the two responses.
bounds.clients = { until: UNTIL, availableSince: SINCE + 600 };
renderProbe();
await waitFor(() => expect(line("clients")).toContain(`/${SINCE + 600}`));
// The page adopts the later watermark, so the four older answers are the
// laggards and each gets its one retry rather than rendering beside it.
await waitFor(() => expect(calls.totals).toBe(2));
expect(line("clients")).toContain("ready");
failing = false;
lastRetry();
await waitFor(() => expect(line()).toBe(`ready:24h@${UNTIL}`));
expect(calls).toBeGreaterThan(spent);
});
test("a retained previous-period body never renders under the new period's label", async () => {
const { rerenderWith } = renderProbe("24h");
await waitFor(() => expect(line("totals")).toBe(`totals:ready:24h@${UNTIL}/${SINCE}`));
await waitFor(() => expect(line()).toBe(`ready:24h@${UNTIL}`));
rerenderWith("1h");
// Whatever `keepPreviousData` is holding, no panel may claim it answers 1h.
await waitFor(() => expect(line("totals")).toBe(`totals:ready:1h@${UNTIL}/${SINCE}`));
for (const endpoint of OVERVIEW_ENDPOINTS) expect(line(endpoint)).toContain("1h@");
});
test("a period change buys the new window its own retry", async () => {
bounds.routes = { until: UNTIL - 3600, availableSince: SINCE };
const { rerenderWith } = renderProbe("24h");
await waitFor(() => expect(line("routes")).toContain("error"));
const spent = calls.routes;
rerenderWith("1h");
// The mismatch persists under the new period, and the episode key changed
// with it: the retry the abandoned period spent is not the new one's.
await waitFor(() => expect(calls.routes).toBeGreaterThan(spent));
await waitFor(() => expect(line("routes")).toContain("error"));
});
test("a retry in flight when the period changes cannot spend the window's retry later", async () => {
// The stale completion the tokens exist to orphan: routes lags under 24h, the
// hook issues its one retry, and the reader picks 1h before that retry lands.
bounds.routes = { until: UNTIL - 3600, availableSince: SINCE };
let release = () => {};
hold = { promise: new Promise<void>((resolve) => (release = resolve)), release: () => release() };
const { rerenderWith } = renderProbe("24h");
await waitFor(() => expect(calls.routes).toBe(2));
bounds.routes = { until: UNTIL, availableSince: SINCE };
rerenderWith("1h");
await waitFor(() => expect(line("routes")).toContain("1h@"));
// The abandoned retry lands now, under a period it was never asked for.
hold.release();
hold = null;
await waitFor(() => expect(line("routes")).toContain("ready"));
// Back to the window it was issued for, still lagging. The stale completion
// must not have marked this episode spent: the panel gets a real retry before
// it is allowed to reach the terminal error.
bounds.routes = { until: UNTIL - 3600, availableSince: SINCE };
rerenderWith("24h");
// The cached lagging body is there to render immediately, and the panel must
// not state the terminal error off it: that error means "retried and still
// behind", and this visit has not retried anything yet. An abandoned
// completion recording the episode as spent is what would produce it here.
expect(line("routes")).toContain("loading");
await waitFor(() => expect(line("routes")).toContain("different window"));
// `keepPreviousData` is holding the 24h body. It is a complete answer and
// still the wrong one to draw under "1h", so the page waits.
expect(line()).toBe("loading:");
await waitFor(() => expect(line()).toBe(`ready:1h@${UNTIL}`));
});
+24 -239
View File
@@ -1,249 +1,34 @@
/**
* One period, five requests, one window.
* One period, one request, one window.
*
* Totals, the timeline, the per-client series and the two breakdowns are
* separate calls, so a refresh that straddles a bucket boundary or a retention
* pass that advances the watermark mid-page can answer them for different
* windows. Rendering them side by side anyway would put a headline count above
* charts of a different span, a mixed page that looks exactly like a real one.
* The five per-panel endpoints this replaces could each answer for a different
* span, so the page had to reconcile five window identities, retry the laggards
* and fail the ones that stayed behind. `GET /api/overview` answers every panel
* out of a single read transaction: the totals, both timelines and both
* breakdowns describe the same span and the same database state by construction,
* and none of that reconciliation has anything left to reconcile.
*
* This is **window** coherence, not data-snapshot coherence: matching bounds
* cannot prove a common database state, and live inserts between requests may
* still shift counts slightly between panels. What it does guarantee is that no
* two panels ever describe different spans.
*
* Rendering is per panel. A panel whose request is still in flight shows its own
* loading state and a panel whose request failed shows its own error, while the
* panels that match the window keep rendering a failed donut never blanks the
* charts.
* What remains is the one rule a single request does not settle by itself.
* `keepPreviousData` holds the body of the period the reader just left a
* complete, self-consistent answer, and still the wrong one to draw under the
* new label so a body is a member of this window only while its own `period`
* is the selected one. Until then the page is loading.
*/
import { useCallback, useEffect, useRef, useState } from "react";
import { keepPreviousData, useQuery, type UseQueryResult } from "@tanstack/react-query";
import { statsClientsQuery, statsQuery, statsRoutesQuery, statsTypesQuery, timeseriesQuery } from "@/lib/queries";
import type {
Coverage,
Period,
StatsClients,
StatsRoutes,
StatsTimeseries,
StatsTotals,
StatsTypes,
} from "@/lib/types";
export const OVERVIEW_ENDPOINTS = ["totals", "timeseries", "clients", "types", "routes"] as const;
export type OverviewEndpoint = (typeof OVERVIEW_ENDPOINTS)[number];
interface EndpointBodies {
totals: StatsTotals;
timeseries: StatsTimeseries;
clients: StatsClients;
types: StatsTypes;
routes: StatsRoutes;
}
/**
* What makes two responses the same window. `available_since` joins the bounds
* because retention advancing between requests changes what the same `[since,
* until)` can answer for, and mixing a pre-prune answer with a post-prune one is
* the failure the bounds alone would not catch.
*/
export interface WindowId {
period: Period;
since: number;
until: number;
availableSince: number;
}
/** The four fields every window-bounded stats body carries. */
interface Bounded {
period: Period;
since: number;
until: number;
coverage: Coverage;
}
export function windowIdOf(body: Bounded): WindowId {
return {
period: body.period,
since: body.since,
until: body.until,
availableSince: body.coverage.available_since,
};
}
export function sameWindow(a: WindowId, b: WindowId): boolean {
return a.period === b.period && a.since === b.since && a.until === b.until && a.availableSince === b.availableSince;
}
/**
* Which of two candidate windows the page adopts: the one that reaches further
* forward in time, and for identical bounds the one that admits the later
* watermark. Both rules pick the answer a laggard has to catch up to.
*/
export function newerWindow(a: WindowId, b: WindowId): WindowId {
if (b.until !== a.until) return b.until > a.until ? b : a;
return b.availableSince > a.availableSince ? b : a;
}
function keyOf(id: WindowId): string {
return `${id.period}|${id.since}|${id.until}|${id.availableSince}`;
}
import { useCallback } from "react";
import { keepPreviousData, useQuery } from "@tanstack/react-query";
import { overviewQuery } from "@/lib/queries";
import type { Overview, Period } from "@/lib/types";
export type Panel<T> =
{ status: "loading" } | { status: "error"; error: unknown; retry: () => void } | { status: "ready"; data: T };
export interface OverviewWindow {
/** Null until one response for the selected period has arrived. */
window: WindowId | null;
/** The adopted window's watermark, for the page's single coverage notice. */
coverage: Coverage | null;
totals: Panel<StatsTotals>;
timeseries: Panel<StatsTimeseries>;
clients: Panel<StatsClients>;
types: Panel<StatsTypes>;
routes: Panel<StatsRoutes>;
}
/**
* A laggard that stayed behind after its one retry. Not an `ApiError`: nothing
* failed, the endpoint simply never caught up, and `InlineError` renders the
* message verbatim.
*/
export const MISMATCH = new Error("This panel is for a different window than the rest of the page. Try again.");
export function useOverviewWindow(period: Period): OverviewWindow {
const queries: { [K in OverviewEndpoint]: UseQueryResult<EndpointBodies[K]> } = {
totals: useQuery({ ...statsQuery(period), placeholderData: keepPreviousData }),
timeseries: useQuery({ ...timeseriesQuery(period), placeholderData: keepPreviousData }),
clients: useQuery({ ...statsClientsQuery(period), placeholderData: keepPreviousData }),
types: useQuery({ ...statsTypesQuery(period), placeholderData: keepPreviousData }),
routes: useQuery({ ...statsRoutesQuery(period), placeholderData: keepPreviousData }),
};
// A `keepPreviousData` placeholder for the period just left is a complete,
// self-consistent body — and still the wrong one to show under the new label,
// so it is neither a candidate for the window nor a member of it.
const answers = new Map<OverviewEndpoint, WindowId>();
for (const endpoint of OVERVIEW_ENDPOINTS) {
const data = queries[endpoint].data;
if (data !== undefined && data.period === period) answers.set(endpoint, windowIdOf(data));
}
let window: WindowId | null = null;
for (const id of answers.values()) window = window === null ? id : newerWindow(window, id);
// The effect below runs on what the responses say, not on how many times they
// arrived: a poll that returns byte-identical data must not restart the retry
// bookkeeping. The refetchers ride a ref for the same reason — TanStack hands
// back a fresh function identity on some renders, and depending on it would
// re-enter the effect with nothing changed.
const answersKey = OVERVIEW_ENDPOINTS.map((endpoint) => {
const id = answers.get(endpoint);
return id === undefined ? "" : keyOf(id);
}).join("~");
const latest = useRef({ answers, refetch: queries });
latest.current = { answers, refetch: queries };
// Which mismatch episode each endpoint has already spent its retry on, keyed
// by endpoint and window identity so a new window buys a new attempt.
const retriedFor = useRef(new Map<OverviewEndpoint, string>());
// Which retry each endpoint is waiting on. Per endpoint, because one shared
// counter would let a second endpoint's retry silence the first's completion;
// bumped on every retry issued, so a completion from a window or a period the
// page has left can neither clear an error the current one reached nor spend
// the current window's one retry.
const tokens = useRef(new Map<OverviewEndpoint, number>());
// State, not a ref: a retry that returns byte-identical data changes nothing
// else a render could see, and the panel still has to reach its error.
const [landedFor, setLandedFor] = useState(new Map<OverviewEndpoint, string>());
// Leaving a period ends every episode it opened. A retry issued for the old
// period can still be in flight, and without this its completion would land
// under the new one holding a token the map still honours: it would record an
// episode as spent, so a return to that window would reach the terminal error
// without the retry that error is supposed to follow. Bumping the tokens
// orphans those answers, and the cleared maps let the new window start clean.
const [lastPeriod, setLastPeriod] = useState(period);
if (lastPeriod !== period) {
setLastPeriod(period);
for (const endpoint of OVERVIEW_ENDPOINTS) {
tokens.current.set(endpoint, (tokens.current.get(endpoint) ?? 0) + 1);
}
retriedFor.current.clear();
setLandedFor(new Map());
}
const windowKey = window === null ? null : keyOf(window);
useEffect(() => {
if (windowKey === null) return;
for (const [endpoint, identity] of latest.current.answers) {
if (keyOf(identity) === windowKey) {
retriedFor.current.delete(endpoint);
continue;
}
const episode = `${endpoint}|${windowKey}`;
if (retriedFor.current.get(endpoint) === episode) continue;
retriedFor.current.set(endpoint, episode);
const token = (tokens.current.get(endpoint) ?? 0) + 1;
tokens.current.set(endpoint, token);
const landed = () => {
if (tokens.current.get(endpoint) !== token) return;
setLandedFor((previous) => new Map(previous).set(endpoint, episode));
};
void latest.current.refetch[endpoint].refetch().then(landed, landed);
}
}, [answersKey, windowKey]);
const retry = useCallback((endpoint: OverviewEndpoint) => {
retriedFor.current.delete(endpoint);
tokens.current.set(endpoint, (tokens.current.get(endpoint) ?? 0) + 1);
setLandedFor((previous) => {
const next = new Map(previous);
next.delete(endpoint);
return next;
});
void latest.current.refetch[endpoint].refetch();
}, []);
function panelOf<K extends OverviewEndpoint>(endpoint: K): Panel<EndpointBodies[K]> {
const query = queries[endpoint];
const onRetry = () => retry(endpoint);
if (query.isError) return { status: "error", error: query.error, retry: onRetry };
const data = query.data;
if (
data !== undefined &&
windowKey !== null &&
data.period === period &&
keyOf(windowIdOf(data)) === windowKey
) {
return { status: "ready", data };
}
if (windowKey !== null && landedFor.get(endpoint) === `${endpoint}|${windowKey}`) {
return { status: "error", error: MISMATCH, retry: onRetry };
}
return { status: "loading" };
}
const panels = {
totals: panelOf("totals"),
timeseries: panelOf("timeseries"),
clients: panelOf("clients"),
types: panelOf("types"),
routes: panelOf("routes"),
};
// The notice describes the window, so any member of it can supply the
// watermark: whichever panel arrived says the same thing about coverage.
let coverage: Coverage | null = null;
for (const endpoint of OVERVIEW_ENDPOINTS) {
const panel = panels[endpoint];
if (panel.status === "ready") {
coverage = panel.data.coverage;
break;
}
}
return { window, coverage, ...panels };
export function useOverviewWindow(period: Period): Panel<Overview> {
const query = useQuery({ ...overviewQuery(period), placeholderData: keepPreviousData });
const { refetch } = query;
const retry = useCallback(() => void refetch(), [refetch]);
if (query.isError) return { status: "error", error: query.error, retry };
if (query.data !== undefined && query.data.period === period) return { status: "ready", data: query.data };
return { status: "loading" };
}

Some files were not shown because too many files have changed in this diff Show More