v0.1.1
Go quality gates / test (push) Waiting to run

This commit is contained in:
Mateusz Gruszczyński committed 2026-11-30 14:44:28 +01:00
1 parent 8c4d463f1e
commit de13d851a8
75 files changed
+4656 -442

No files matched your search

+116
View File
@@ -0,0 +1,116 @@
package telemetry
import (
"time"
)
// FleetNode is an authenticated panel-only view of measured samples. It
// contains no credentials or server configuration mutation capabilities.
// Each node owns a separate history; no synthetic data is produced.
type FleetNode struct {
ID string `json:"id"`
Name string `json:"name"`
Role string `json:"role"`
Samples []Sample `json:"samples"`
Error string `json:"error,omitempty"`
LastPoll time.Time `json:"lastPoll"`
}
// FleetPoint contains only quantities for which across-node arithmetic is
// valid. Percentile latency is intentionally excluded: it cannot be computed
// from separately reported per-node p50/p95/p99 values.
type FleetPoint struct {
Time time.Time `json:"time"`
QueryRate *float64 `json:"queryRate"`
NoErrorRate *float64 `json:"noerror"`
NXDomainRate *float64 `json:"nxdomain"`
ServFailRate *float64 `json:"servfail"`
RefusedRate *float64 `json:"refused"`
BlockedRate *float64 `json:"blocked"`
CacheHitRate *float64 `json:"cacheHitRate"`
Contributors int `json:"contributors"`
}
const fleetStep = 15 * time.Second
const fleetMaxAge = 23 * time.Second
// AggregateFleet produces timestamp-aligned, fully-covered sum-of-rates
// points for all registered servers. Each node contributes its latest real
// reading at or before the UTC grid timestamp, no older than 23 seconds.
// Missing/reset/stale samples produce a gap (null), never a misleading 0 or a
// reduced total disguised as a whole-fleet total. Cache ratio is weighted by
// cache hit/miss operations per second, not averaged from percentages.
func AggregateFleet(nodes []FleetNode) []FleetPoint {
if len(nodes) == 0 {
return nil
}
var earliest, latest time.Time
for _, n := range nodes {
for _, p := range n.Samples {
if earliest.IsZero() || p.Time.Before(earliest) {
earliest = p.Time
}
if latest.IsZero() || p.Time.After(latest) {
latest = p.Time
}
}
}
if earliest.IsZero() {
return nil
}
start := earliest.Truncate(fleetStep).Add(fleetStep)
end := latest.Truncate(fleetStep).Add(fleetStep)
if end.Before(start) {
return nil
}
// Bound comparison data to the same six-hour, 1440-poll memory horizon as
// each node's History. Never add empty points before the first poll.
if end.Sub(start) > time.Duration(maxSamples-1)*fleetStep {
start = end.Add(-time.Duration(maxSamples-1) * fleetStep)
}
points := make([]FleetPoint, 0, int(end.Sub(start)/fleetStep)+1)
index := make([]int, len(nodes))
for t := start; !t.After(end); t = t.Add(fleetStep) {
point := FleetPoint{Time: t}
var query, noerror, nxdomain, servfail, refused, blocked float64
var hitQPS, missQPS float64
cacheComplete := true
for i, n := range nodes {
for index[i] < len(n.Samples) && !n.Samples[index[i]].Time.After(t) {
index[i]++
}
if index[i] == 0 {
cacheComplete = false
continue
}
sample := n.Samples[index[i]-1]
if age := t.Sub(sample.Time); age < 0 || age > fleetMaxAge || sample.QueryRate == nil || sample.NoErrorRate == nil || sample.NXDomainRate == nil || sample.ServFailRate == nil || sample.RefusedRate == nil || sample.BlockedRate == nil {
cacheComplete = false
continue
}
point.Contributors++
query += *sample.QueryRate
noerror += *sample.NoErrorRate
nxdomain += *sample.NXDomainRate
servfail += *sample.ServFailRate
refused += *sample.RefusedRate
blocked += *sample.BlockedRate
if sample.cacheHitQPS == nil || sample.cacheMissQPS == nil {
cacheComplete = false
} else {
hitQPS += *sample.cacheHitQPS
missQPS += *sample.cacheMissQPS
}
}
if point.Contributors == len(nodes) {
point.QueryRate, point.NoErrorRate, point.NXDomainRate = &query, &noerror, &nxdomain
point.ServFailRate, point.RefusedRate, point.BlockedRate = &servfail, &refused, &blocked
if cacheComplete && hitQPS+missQPS > 0 {
ratio := 100 * hitQPS / (hitQPS + missQPS)
point.CacheHitRate = &ratio
}
}
points = append(points, point)
}
return points
}
+92
View File
@@ -0,0 +1,92 @@
package telemetry
import (
"encoding/json"
"math"
"strings"
"testing"
"time"
"git.linuxiarz.pl/gru/EasyDNS-Web/internal/easydns"
)
func fleetStats(queries, hits, misses uint64) easydns.Stats {
return easydns.Stats{
QueriesTotal: queries,
Responses: map[string]uint64{"noerror": queries / 2, "nxdomain": queries / 4},
Blocked: queries / 10,
Cache: easydns.Cache{Hits: hits, Misses: misses},
LatencyP95S: .021,
}
}
func TestFleetAggregateSumsRatesAndWeightsCacheCounts(t *testing.T) {
base := time.Date(2026, 11, 30, 10, 0, 2, 0, time.UTC)
inputs := []struct {
name string
off time.Duration
first, last easydns.Stats
}{
{"primary", 0, fleetStats(100, 10, 10), fleetStats(130, 30, 10)},
{"secondary-1", 2 * time.Second, fleetStats(200, 0, 0), fleetStats(260, 0, 60)},
{"secondary-2", 5 * time.Second, fleetStats(50, 0, 0), fleetStats(95, 10, 10)},
}
var nodes []FleetNode
for i, tc := range inputs {
h := New()
h.Record(base.Add(tc.off), tc.first)
h.Record(base.Add(tc.off+15*time.Second), tc.last)
samples, _, _ := h.Snapshot()
nodes = append(nodes, FleetNode{ID: string(rune('a' + i)), Name: tc.name, Samples: samples})
}
points := AggregateFleet(nodes)
if len(points) != 2 {
t.Fatalf("expected grid points at 10:00:15 and 10:00:30, got %d", len(points))
}
last := points[len(points)-1]
if last.Contributors != 3 || last.QueryRate == nil || math.Abs(*last.QueryRate-9) > .0001 {
t.Fatalf("3-node sum must be (30+60+45)/15 = 9 QPS: %+v", last)
}
// 20 hits + 0 hits + 10 hits vs 0 + 60 + 10 misses = 30%.
if last.CacheHitRate == nil || math.Abs(*last.CacheHitRate-30) > .0001 {
t.Fatalf("fleet cache ratio must be weighted 30%%, not avg of percentages: %+v", last)
}
if last.NoErrorRate == nil || *last.NoErrorRate <= 0 || last.BlockedRate == nil {
t.Fatalf("additive response/blocked rates missing: %+v", last)
}
body, err := json.Marshal(last)
if err != nil {
t.Fatal(err)
}
if strings.Contains(string(body), "p95") || strings.Contains(string(body), "p50") {
t.Fatal("aggregated latency percentiles would be invalid")
}
}
func TestFleetAggregateNeverTreatsMissingNodesAsZero(t *testing.T) {
base := time.Date(2026, 11, 30, 10, 0, 2, 0, time.UTC)
a, b := New(), New()
a.Record(base, fleetStats(100, 10, 10))
a.Record(base.Add(15*time.Second), fleetStats(145, 30, 10))
b.Record(base.Add(3*time.Second), fleetStats(500, 20, 20)) // no second sample: rate unknown
points := AggregateFleet([]FleetNode{{ID: "a", Samples: historySamples(a)}, {ID: "b", Samples: historySamples(b)}})
last := points[len(points)-1]
if last.QueryRate != nil || last.CacheHitRate != nil || last.Contributors != 1 {
t.Fatalf("partial fleet must produce gap, not 3 QPS presented as total: %+v", last)
}
// Counter reset on one node must also introduce a null, not a negative QPS.
b.Record(base.Add(18*time.Second), fleetStats(0, 0, 0))
points = AggregateFleet([]FleetNode{{ID: "a", Samples: historySamples(a)}, {ID: "b", Samples: historySamples(b)}})
last = points[len(points)-1]
if last.QueryRate != nil || last.Contributors != 1 {
t.Fatalf("reset must not show a partial aggregate as full: %+v", last)
}
}
func TestFleetEmptyHistory(t *testing.T) {
if AggregateFleet(nil) != nil || AggregateFleet([]FleetNode{{Name: "no readings"}}) != nil {
t.Fatal("fleet with no readings must stay empty")
}
}
func historySamples(h *History) []Sample { s, _, _ := h.Snapshot(); return s }
+6
View File
@@ -33,6 +33,10 @@ type Sample struct {
P50MS float64 `json:"p50ms"`
P95MS float64 `json:"p95ms"`
P99MS float64 `json:"p99ms"`
// Per-second cache increments allow mathematically weighted fleet cache
// ratios. These are derived from real counters and never sent to the browser.
cacheHitQPS *float64
cacheMissQPS *float64
}
type History struct {
@@ -66,6 +70,8 @@ func (h *History) Record(t time.Time, s easydns.Stats) {
if p.CacheHits >= prev.CacheHits && p.CacheMisses >= prev.CacheMisses {
hits := p.CacheHits - prev.CacheHits
misses := p.CacheMisses - prev.CacheMisses
p.cacheHitQPS = delta(prev.CacheHits, p.CacheHits, secs)
p.cacheMissQPS = delta(prev.CacheMisses, p.CacheMisses, secs)
if hits+misses > 0 {
v := 100 * float64(hits) / float64(hits+misses)
p.CacheHitRate = &v