Make the API response contract a test; fix what it found
The console's TypeScript types are hand-written and apiFetch ends in
`JSON.parse(text) as T`, so nothing in the toolchain compared them with the
Go structs. A field that lost its json tag, or a response a struct never had,
showed up as an empty table in a browser and nowhere else: the Go suite was
green and the console was wrong. internal/app/contract_test.go now asserts the
exact JSON key set of every admin endpoint, driven through the real router
with the real hook implementations, plus a test that drives the two write
endpoints with the exact payload web/src builds.
The drift it found, all four fixed here:
blocklist.Source and SourceMeta had no json tags at all, so GET /api/blocklists
sent Go field names ("URL"/"Format") where the console expects snake_case: the
Sources table rendered blank rows and its per-row toggle posted
`name: undefined`. Tagged to match ParseStats.
acl.GroupSummary was flat where the console reads a nested `match` object — the
same shape config.Group has — so every group card read "matches nothing". The
four match fields are nested now, under a new acl.Match.
PUT /api/clients answered 400 `json: unknown field "ptr_suffixes"` to the
console's payload, because config.Group and config.Match carried yaml tags only
and the decoder runs with DisallowUnknownFields. Both structs have json tags
now; the same applies to config.UpstreamServer and UpstreamBootstrap.
PUT /api/upstreams answered 400 `json: unknown field "health"`, because the
console round-trips the whole server object it read, runtime health fields
included. They are accepted and ignored, because the server owns them, and they
are `yaml:"-"` so settings.yaml does not gain runtime state.
Also fixed, each with a test:
A duration on the wire was a nanosecond count. config.Duration had a
MarshalYAML but no MarshalJSON, so bootstraps[].refresh arrived as 30000000000
while the console typed the field as a string, and healthcheck_interval was a
float of seconds in one place and a string in another. Durations on the wire
are duration strings everywhere now — the same spelling config.yaml uses — and a
bare JSON number is still accepted and means seconds, not nanoseconds.
TestDurationJSONForm used to pin the old behaviour and now pins the new one,
saying in its comment that the old behaviour was the bug.
A log row's key set depended on the row. api.LogEntry was omitempty on
client_group, response, upstream and list, so a query with no ACL group
arrived without the key and the console rendered "undefined" where the column
should be empty. The contract test can only pin one shape if the server emits
one, so nothing on that struct is omitempty any more.
A dead peer stayed in the cluster peer list forever. Cluster.seen was only ever
added to and deleted from on an explicit `bye`, so a node that crashed — or
whose Valkey connection died — was reported as a live peer for the life of the
process, and its stale blocklist digest was flagged as divergence forever.
Peers() now reaps peers unheard for peer_ttl*4 and stamps each state with the
receiver's own clock, so clock skew between two machines can neither reap a
healthy peer nor keep a dead one. Discover() ages out the same way on the
publisher's own last_seen stamp, because the keyed Valkey record outlives a
crash: a live node keeps refreshing the key's TTL, so a dead node's field stayed
readable for the life of the fleet.
peer_ttl: 0 would have crashed the process. time.NewTicker(PeerTTL/2) panics on
a non-positive period and `EXPIRE key 0` deletes the heartbeat key, so a config
that left peer_ttl unset would have taken the process down at Start, or made
every instance believe it is alone in the fleet. Both go through peerTTL() and
peerDeadline(), which fall back to the default.
Two cluster tests raced on the wire, not on the product, and one was
environment-dependent rather than wrong. A node that joined after another's
heartbeat was in flight hears about it on the next tick, so "b does not see a"
read immediately after "a sees b" is a coin flip; the divergence test waited for
a digest on the wrong node's view of the fleet; and 127.0.0.1:1 is only
unbindable outside a container that sets
net.ipv4.ip_unprivileged_port_start=0, where it binds and the partial-bind test
fails with both transports up. That test now occupies a port with a live
listener in the test process, which is a deterministic EADDRINUSE on every
machine and every uid.
internal/server/counters_test.go covers the counter-key layer that no other
test touched: the "<transport>.<field>" keyspace, that the aggregate folds only
the known fields, and that the snapshot is safe while counters move.
Two pinned behaviours changed on purpose, each with a test that says so:
An RPZ record did not cover the name it names. rpzRule gave a bare owner name
the subdomain form (*.name), so analytics.example.org. in a policy zone blocked
cdn.analytics.example.org. and left analytics.example.org. resolving normally —
and an rpz-passthru. record did not allowlist its own domain either. RPZ
semantics say the record applies to the domain and everything under it, so a
bare owner now takes the apex form **.name; an owner written with an explicit *.
is still strict, so a zone that wants subdomain-only behaviour can still ask for
it. This changes which queries get blocked for an existing policy zone, which is
why it wanted a decision. TestExampleRPZZoneCoversTheApexItNames pins both
halves and the example zone now says which half it relies on.
metrics.OutcomeLocal had no producer. The engine reported a local-zone answer as
qlog.ActionAllow, which outcomeFor mapped to OutcomeUpstream, so every locally
answered query was counted as an upstream one and the outcome="local" series was
never published — the dashboard's local column was permanently empty.
Response.Local is now set on the local-zone path and outcomeFor consults it
first. That moves published counters, so the README's metrics section says so
too.
This commit is contained in:
1 parent
e8c5b414d9
commit
9881d2a095
23 files changed
+1302
-242
No files matched your search
@@ -0,0 +1,209 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"sync"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// TestBumpAndLoadKeySemantics is a table over the counter keyspace. The keys
|
||||
// are the only thing that binds a counter to a transport, and two callers can
|
||||
// disagree about the spelling of a transport: bump() deliberately normalises
|
||||
// an empty transport to "udp" (the pre-transport default) while load() does
|
||||
// not normalise at all, so a caller that asks for the wrong spelling silently
|
||||
// reads 0 rather than failing. Pinning both directions here is what stops that
|
||||
// from turning into a counter that is written but never shown.
|
||||
func TestBumpAndLoadKeySemantics(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
transport string
|
||||
field string
|
||||
wantKey string
|
||||
}{
|
||||
{name: "udp queries", transport: "udp", field: "queries", wantKey: "udp.queries"},
|
||||
{name: "tcp sent", transport: "tcp", field: "sent", wantKey: "tcp.sent"},
|
||||
{name: "dot truncated", transport: "dot", field: "truncated", wantKey: "dot.truncated"},
|
||||
{name: "doh dropped", transport: "doh", field: "dropped", wantKey: "doh.dropped"},
|
||||
// An empty transport is the historical spelling of "the default
|
||||
// transport", and classify()/servePacket() predate the per-transport
|
||||
// split, so an empty one must not create a ".queries" key that
|
||||
// ByTransport can never find.
|
||||
{name: "empty transport falls back to udp", transport: "", field: "queries", wantKey: "udp.queries"},
|
||||
{name: "unknown transport is kept verbatim", transport: "quic", field: "queries", wantKey: "quic.queries"},
|
||||
{name: "unknown field is kept verbatim", transport: "udp", field: "nonsense", wantKey: "udp.nonsense"},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
s := new(Server)
|
||||
s.bump(tc.transport, tc.field)
|
||||
|
||||
// The key is the whole lookup path, so assert on what was
|
||||
// actually stored rather than inferring it from a read.
|
||||
if _, ok := s.counters.Load(tc.wantKey); !ok {
|
||||
keys := make([]string, 0, 4)
|
||||
s.counters.Range(func(k, _ any) bool {
|
||||
keys = append(keys, k.(string))
|
||||
return true
|
||||
})
|
||||
t.Fatalf("bump(%q, %q) stored %v, want key %q", tc.transport, tc.field, keys, tc.wantKey)
|
||||
}
|
||||
// The normalised key is what a reader of the default transport
|
||||
// sees. load() does not normalise, which is deliberate: it is
|
||||
// always called with a literal transport from the four-transport
|
||||
// list, so a caller that invented a spelling reads 0 rather than
|
||||
// silently getting another transport's numbers.
|
||||
if got := s.load(tc.wantKey[:len(tc.wantKey)-len(tc.field)-1], tc.field); got != 1 {
|
||||
t.Errorf("load(key transport, %q) = %d, want 1", tc.field, got)
|
||||
}
|
||||
// Counters accumulate, they do not reset.
|
||||
s.bump(tc.transport, tc.field)
|
||||
if got := s.load(tc.wantKey[:len(tc.wantKey)-len(tc.field)-1], tc.field); got != 2 {
|
||||
t.Errorf("after two bumps load(%q) = %d, want 2", tc.field, got)
|
||||
}
|
||||
// A field nobody wrote reads 0 instead of aliasing a sibling.
|
||||
if got := s.load(tc.wantKey[:len(tc.wantKey)-len(tc.field)-1], tc.field+"x"); got != 0 {
|
||||
t.Errorf("load(%q) = %d, want 0", tc.field+"x", got)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestStatsAggregatesOnlyKnownFields is the other half of the key contract: a
|
||||
// key whose suffix is not a HandlerStats field (sent, truncated, or garbage)
|
||||
// must be ignored by the aggregate instead of being miscounted into it.
|
||||
func TestStatsAggregatesOnlyKnownFields(t *testing.T) {
|
||||
cases := []struct {
|
||||
field string
|
||||
weight func(*HandlerStats) uint64
|
||||
}{
|
||||
{field: "queries", weight: func(s *HandlerStats) uint64 { return s.Queries }},
|
||||
{field: "blocked", weight: func(s *HandlerStats) uint64 { return s.Blocked }},
|
||||
{field: "cached", weight: func(s *HandlerStats) uint64 { return s.Cached }},
|
||||
{field: "errors", weight: func(s *HandlerStats) uint64 { return s.Errors }},
|
||||
{field: "dropped", weight: func(s *HandlerStats) uint64 { return s.Dropped }},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.field, func(t *testing.T) {
|
||||
s := new(Server)
|
||||
s.bump("tcp", tc.field)
|
||||
s.bump("tcp", tc.field)
|
||||
got := s.Stats()
|
||||
if v := tc.weight(&got); v != 2 {
|
||||
t.Errorf("Stats().%s = %d, want 2", tc.field, v)
|
||||
}
|
||||
// The per-transport view is the transport-scoped mirror of the
|
||||
// same bumps and must agree.
|
||||
ts := s.ByTransport()["tcp"]
|
||||
switch tc.field {
|
||||
case "queries":
|
||||
if ts.Queries != 2 {
|
||||
t.Errorf("ByTransport tcp.Queries = %d, want 2", ts.Queries)
|
||||
}
|
||||
case "blocked":
|
||||
if ts.Blocked != 2 {
|
||||
t.Errorf("ByTransport tcp.Blocked = %d, want 2", ts.Blocked)
|
||||
}
|
||||
case "cached":
|
||||
if ts.Cached != 2 {
|
||||
t.Errorf("ByTransport tcp.Cached = %d, want 2", ts.Cached)
|
||||
}
|
||||
case "errors":
|
||||
if ts.Errors != 2 {
|
||||
t.Errorf("ByTransport tcp.Errors = %d, want 2", ts.Errors)
|
||||
}
|
||||
case "dropped":
|
||||
if ts.Dropped != 2 {
|
||||
t.Errorf("ByTransport tcp.Dropped = %d, want 2", ts.Dropped)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// Fields the aggregate does not know about stay out of it but do show up
|
||||
// per transport, which is how the console's transport tab works.
|
||||
s := new(Server)
|
||||
s.bump("udp", "sent")
|
||||
s.bump("udp", "truncated")
|
||||
s.bump("udp", "nonsense")
|
||||
if got := s.Stats(); got.Queries+got.Blocked+got.Cached+got.Errors+got.Dropped != 0 {
|
||||
t.Errorf("Stats() = %+v, want every aggregate field 0", got)
|
||||
}
|
||||
ts := s.ByTransport()["udp"]
|
||||
if ts.Sent != 1 || ts.Truncated != 1 {
|
||||
t.Errorf("ByTransport udp = %+v, want Sent 1 Truncated 1", ts)
|
||||
}
|
||||
}
|
||||
|
||||
// TestStatsSnapshotIsSafeWhileCountersMove hammers bump() from many
|
||||
// goroutines while Stats() and ByTransport() are read. Under -race this is the
|
||||
// real assertion; the final check is an invariant (the aggregate equals the
|
||||
// sum over transports) rather than a claim about what a reader happened to
|
||||
// observe mid-flight, so it cannot flake.
|
||||
func TestStatsSnapshotIsSafeWhileCountersMove(t *testing.T) {
|
||||
const (
|
||||
writers = 8
|
||||
bumpsPerWriter = 200
|
||||
readers = 4
|
||||
)
|
||||
s := new(Server)
|
||||
transports := []string{"udp", "tcp", "dot", "doh"}
|
||||
|
||||
var start sync.WaitGroup
|
||||
start.Add(1)
|
||||
done := make(chan struct{})
|
||||
|
||||
// Writers and readers wait on separate groups: the readers stop only when
|
||||
// `done` is closed, and `done` is closed once the writers are finished, so
|
||||
// folding both into one WaitGroup would wait for readers that are waiting
|
||||
// for the very Wait that waits for them.
|
||||
var writersWG, readersWG sync.WaitGroup
|
||||
for w := 0; w < writers; w++ {
|
||||
writersWG.Add(1)
|
||||
go func(w int) {
|
||||
defer writersWG.Done()
|
||||
transport := transports[w%len(transports)]
|
||||
start.Wait()
|
||||
for i := 0; i < bumpsPerWriter; i++ {
|
||||
s.bump(transport, "queries")
|
||||
s.bump(transport, "sent")
|
||||
}
|
||||
}(w)
|
||||
}
|
||||
for r := 0; r < readers; r++ {
|
||||
readersWG.Add(1)
|
||||
go func() {
|
||||
defer readersWG.Done()
|
||||
start.Wait()
|
||||
for {
|
||||
select {
|
||||
case <-done:
|
||||
return
|
||||
default:
|
||||
}
|
||||
_ = s.Stats()
|
||||
_ = s.ByTransport()
|
||||
}
|
||||
}()
|
||||
}
|
||||
start.Done()
|
||||
writersWG.Wait()
|
||||
close(done)
|
||||
readersWG.Wait()
|
||||
|
||||
total := s.Stats()
|
||||
var sum uint64
|
||||
for _, tr := range transports {
|
||||
ts := s.ByTransport()[tr]
|
||||
sum += ts.Queries
|
||||
if ts.Queries != ts.Sent {
|
||||
t.Errorf("transport %q: Queries %d != Sent %d", tr, ts.Queries, ts.Sent)
|
||||
}
|
||||
}
|
||||
if sum != total.Queries {
|
||||
t.Errorf("sum of per-transport queries = %d, aggregate = %d", sum, total.Queries)
|
||||
}
|
||||
// One "queries" bump and one "sent" bump per iteration, so the aggregate
|
||||
// is writers*bumpsPerWriter queries and the same number of sends.
|
||||
if want := uint64(writers * bumpsPerWriter); total.Queries != want {
|
||||
t.Errorf("aggregate queries = %d, want %d", total.Queries, want)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user