edge: 5-minute fleet traffic counters
Count visitor answers at ingress, with trusted-hop, tunnel, door, status, and infrastructure-probe exclusions. Keep bounded five-minute windows, served-app lists, guard decisions and enforced/observed rate decisions. Expose the recorder's daily ClientID for matching fleet sources to Logs. Task 2 of fleet-alerts Plan 2 rev 3, including R3 finding 3. Tests cover counter rotation, startup gaps, floods, sanitising, real two-edge hops, HA forwarding, far assets, refusals, probes, upgrades and client identity. Targeted edge/reqrec tests and their race run pass; vet and gofmt are clean. Eight targeted mutations were caught: hop skip, health-probe skip, refusal partition, hostname cap, startup partial slot, observed rate split, guard burst exclusion and acknowledged-fill ownership. Code drift: a failed backhaul dial answers 502, not the plan's 503; retain that behavior and assert S5xx. observeGuardCount now takes the request for client IP and country. Steering probes only have a healthy response; the load-balancer probe tests cover healthy and failed responses. The prescribed Opus review remains pending outside this network-free implementer run. No push, merge or census update was attempted.
Co-Authored-By: GPT-6 Astra (codex) <noreply@openai.com>
9 files changed,
+1,283
−7
internal/edge/assetcatch.go+2 −1internal/edge/edge.go+32 −4internal/edge/guard.go+8 −2internal/edge/planthrottle.go+2 −0internal/edge/ratelimit.go+11 −0internal/edge/traffic.go+492 −0internal/edge/traffic_test.go+707 −0internal/reqrec/recorder.go+14 −0internal/reqrec/recorder_test.go+15 −0
diff --git a/internal/edge/assetcatch.go b/internal/edge/assetcatch.go| index efd237e71..983c7c300 100644 |
| --- a/internal/edge/assetcatch.go |
| +++ b/internal/edge/assetcatch.go |
| @@ -1075,6 +1075,7 @@ func (e *Edge) serveAssetFar(w http.ResponseWriter, r *http.Request, host string |
| if m := e.usageMeter.Load(); m != nil { |
| m.Record(rt, 1, n, false) |
| } |
| + e.traffic.Load().served(time.Now(), release.RouteAccount(rt), rt.App, cw.status) |
| } |
| // Every answer this edge wrote itself is recorded here when a rule |
| // matched it, as ServeHTTP's observer defer records a matched |
| @@ -1089,7 +1090,7 @@ func (e *Edge) serveAssetFar(w http.ResponseWriter, r *http.Request, host string |
| if out.guard.verdict != nil { |
| e.observeRecords(rt, false, r, cw, out) |
| } |
| - e.observeGuardCount(rt, out) |
| + e.observeGuardCount(rt, r, out) |
| } |
| }() |
| // The hard and probe checks, as ServeHTTP runs them for a request this |
diff --git a/internal/edge/edge.go b/internal/edge/edge.go| index c2b405f3e..8a227c1c8 100644 |
| --- a/internal/edge/edge.go |
| +++ b/internal/edge/edge.go |
| @@ -180,6 +180,9 @@ type Edge struct { |
| // tunnelLoop attaches via the ready hook — serving may already be |
| // underway. |
| usageMeter atomic.Pointer[UsageMeter] |
| + |
| + // traffic counts visitor answers independently of the optional usage and log sinks. |
| + traffic atomic.Pointer[trafficCounter] |
| // errSink, when set, receives edge-observed errors (an upstream 5xx) |
| // — spec 2026-09-07 §3.2. Nil disables emission; nothing else changes. |
| errSink atomic.Pointer[errorSinkRef] |
| @@ -1812,6 +1815,8 @@ func firstSegmentClean(p string) string { |
| } |
| func (e *Edge) ServeHTTP(w http.ResponseWriter, r *http.Request) { |
| + w, r, finishTraffic := e.observeIngress(w, r) |
| + defer finishTraffic() |
| host := r.Host |
| if h, _, err := net.SplitHostPort(host); err == nil { |
| host = h |
| @@ -1843,6 +1848,7 @@ func (e *Edge) ServeHTTP(w http.ResponseWriter, r *http.Request) { |
| // forever. Inert (one comparison against "") unless this deployment |
| // steers. |
| if !isDoor && e.steeringProbe(w, r, host) { |
| + noteIngressSkip(r) |
| return |
| } |
| // The reserved tunnel hostname is answered by the hub itself — before the |
| @@ -1856,6 +1862,7 @@ func (e *Edge) ServeHTTP(w http.ResponseWriter, r *http.Request) { |
| // hub ends its handshake in a hijack, so it must be handed the REAL |
| // ResponseWriter, never a recordingResponseWriter wrapping it. |
| if !isDoor && e.tunnels != nil && host == e.tunnels.Host() { |
| + noteIngressSkip(r) |
| // The fleet store door (storedoor.go) shares this hostname, under |
| // /store/ — the same host gate as registration, which is the whole |
| // reason it is reachable at all: it is not a registry route, so no |
| @@ -1880,6 +1887,9 @@ func (e *Edge) ServeHTTP(w http.ResponseWriter, r *http.Request) { |
| // On a request carrying no X-Carlos-Hop this is one Header.Get and |
| // nothing else. |
| r, hopped := e.acceptHop(r, host) |
| + if hopped { |
| + noteIngressSkip(r) |
| + } |
| // The asset cache's fill vocabulary (assetcatch.go, design §5.3) is this |
| // edge's to send, never a client's: a far edge's assertion is honoured |
| // only on a verified hop, where the home's fill hook consumes it, and no |
| @@ -1908,6 +1918,9 @@ func (e *Edge) ServeHTTP(w http.ResponseWriter, r *http.Request) { |
| r = e.withForwardKey(r) |
| up, ok := e.lookupUpstreamPath(host, r.URL.Path) |
| + if ok && up.route.Kind == "status" { |
| + noteIngressSkip(r) |
| + } |
| // Regional names (#447, regional.go): a regional name is never served |
| // from, or backhauled to, another region. Decided here, on the Host's own |
| // entry, before every arm below that can leave the box: the exact-home |
| @@ -2183,8 +2196,11 @@ func (e *Edge) ServeHTTP(w http.ResponseWriter, r *http.Request) { |
| // An acknowledged home fill is billed by the far edge that |
| // delivers it (assetcatch.go); every other observer below |
| // still sees it. |
| - if m := e.usageMeter.Load(); m != nil && !out.unbilled { |
| - m.Record(up.route, 1, bytes, hopped) |
| + if !out.unbilled { |
| + if m := e.usageMeter.Load(); m != nil { |
| + m.Record(up.route, 1, bytes, hopped) |
| + } |
| + e.traffic.Load().served(time.Now(), release.RouteAccount(up.route), up.route.App, ob.status) |
| } |
| if ob.status >= 500 && !out.answered { |
| e.emitEdgeError(up.route, up.viaTunnel, r, ob.status, out.cause) |
| @@ -2195,7 +2211,7 @@ func (e *Edge) ServeHTTP(w http.ResponseWriter, r *http.Request) { |
| // guard ran for, beside the call that files its Match. Not |
| // under !out.unbilled: an acknowledged home fill is checked |
| // and recorded here, so it is counted here too. |
| - e.observeGuardCount(up.route, out) |
| + e.observeGuardCount(up.route, r, out) |
| }() |
| } |
| @@ -2886,6 +2902,7 @@ func (e *Edge) unknownHost(w http.ResponseWriter, r *http.Request) { |
| if h, _, err := net.SplitHostPort(host); err == nil { |
| host = h |
| } |
| + noteIngressUnknown(r, host) |
| if e.underPlatformDomain(host) { |
| e.pendingHost(w, r) |
| return |
| @@ -2920,6 +2937,8 @@ func (e *Edge) unknownHost(w http.ResponseWriter, r *http.Request) { |
| // handler, so a challenge request never reaches lookupUpstream at all. |
| func (e *Edge) httpFallbackHandler() http.Handler { |
| return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + w, r, finishTraffic := e.observeIngress(w, r) |
| + defer finishTraffic() |
| host := r.Host |
| if h, _, err := net.SplitHostPort(host); err == nil { |
| host = h |
| @@ -2928,6 +2947,7 @@ func (e *Edge) httpFallbackHandler() http.Handler { |
| // any host, so it comes before every host-based branch. Inert with |
| // region HA off. |
| if e.lbHealthAnswer(w, r) { |
| + noteIngressSkip(r) |
| return |
| } |
| // The steering hostname answers here too (ServeHTTP's own first |
| @@ -2936,6 +2956,7 @@ func (e *Edge) httpFallbackHandler() http.Handler { |
| // edge's fallback redirect for a name that is deployment |
| // infrastructure. |
| if e.steeringProbe(w, r, host) { |
| + noteIngressSkip(r) |
| return |
| } |
| // The reserved tunnel hostname is answered by the hub itself on 443 |
| @@ -2944,8 +2965,15 @@ func (e *Edge) httpFallbackHandler() http.Handler { |
| // plain http://<tunnel-host>/ fell through to unknownHost instead of |
| // redirecting like every other routable host. |
| routable := e.tunnels != nil && host == e.tunnels.Host() |
| + if routable { |
| + noteIngressSkip(r) |
| + } |
| if !routable { |
| - _, routable = e.lookupUpstream(host) |
| + var up upstream |
| + up, routable = e.lookupUpstream(host) |
| + if routable && up.route.Kind == "status" { |
| + noteIngressSkip(r) |
| + } |
| } |
| if !routable { |
| // A host this box does not serve but another box HOMES: 443 |
diff --git a/internal/edge/guard.go b/internal/edge/guard.go| index 410a40753..449fd0d7c 100644 |
| --- a/internal/edge/guard.go |
| +++ b/internal/edge/guard.go |
| @@ -6,6 +6,7 @@ import ( |
| "log" |
| "net/http" |
| "strings" |
| + "time" |
| "github.com/carlosframework/platform/internal/edgeguard" |
| "github.com/carlosframework/platform/internal/registry" |
| @@ -102,8 +103,9 @@ func (e *Edge) newGuardState() *guardState { |
| // the same "this box answered it" condition, as the observeRecords call that |
| // may file the request's Match, so the counts follow the records: the |
| // observer defer in ServeHTTP and serveAssetFar's defer. Unlike the records |
| -// it does not depend on a recorder being enabled. |
| -func (e *Edge) observeGuardCount(rt registry.Route, out *outcome) { |
| +// it does not depend on a recorder being enabled. The same non-burst verdict |
| +// feeds fleet traffic; r supplies the client identity and country for its list. |
| +func (e *Edge) observeGuardCount(rt registry.Route, r *http.Request, out *outcome) { |
| m := e.usageMeter.Load() |
| if m == nil || out == nil || out.guard == nil { |
| return |
| @@ -114,6 +116,10 @@ func (e *Edge) observeGuardCount(rt registry.Route, out *outcome) { |
| rule, blocked = v.rule, v.block |
| } |
| m.RecordGuard(rt, rule, blocked) |
| + if rule != nil && rule.Mode != edgeguard.ModeBurst { |
| + country, _ := geoAnswerFrom(r.Context()) |
| + e.traffic.Load().guard(time.Now(), blocked, clientIP(r), country.Country) |
| + } |
| } |
| // guardDecide notes hit as r's verdict and, when the mode blocks the rule, |
diff --git a/internal/edge/planthrottle.go b/internal/edge/planthrottle.go| index e2a98743d..d70391254 100644 |
| --- a/internal/edge/planthrottle.go |
| +++ b/internal/edge/planthrottle.go |
| @@ -4,6 +4,7 @@ import ( |
| "context" |
| "net/http" |
| "net/netip" |
| + "time" |
| "github.com/carlosframework/platform/internal/plans" |
| "github.com/carlosframework/platform/internal/ratelimit" |
| @@ -45,6 +46,7 @@ func (e *Edge) notePlanThrottled(rt registry.Route, what string) { |
| if m := e.usageMeter.Load(); m != nil { |
| m.RecordPlanThrottled(rt) |
| } |
| + e.traffic.Load().rate(time.Now(), release.RouteAccount(rt), rt.App, ratePlan) |
| e.logThrottled("plan-throttle "+rt.Host, "plan throttle: refused "+what+" for "+rt.Host+" (the account is slowed down until the month ends)") |
| } |
diff --git a/internal/edge/ratelimit.go b/internal/edge/ratelimit.go| index a111d3601..232dcbf56 100644 |
| --- a/internal/edge/ratelimit.go |
| +++ b/internal/edge/ratelimit.go |
| @@ -24,6 +24,7 @@ import ( |
| "github.com/carlosframework/platform/internal/ratelimit" |
| "github.com/carlosframework/platform/internal/registry" |
| + "github.com/carlosframework/platform/internal/release" |
| ) |
| // rateLimitBody is the whole body of a rate-limit refusal. Plain text, |
| @@ -160,6 +161,16 @@ func (e *Edge) noteRateLimited(rt registry.Route, d ratelimit.Decision, client s |
| if m := e.usageMeter.Load(); m != nil { |
| m.RecordRateLimited(rt, d) |
| } |
| + kind := rateCeiling |
| + if d == ratelimit.Shed { |
| + kind = rateShed |
| + } |
| + if observe { |
| + kind = rateObserved |
| + } |
| + if d != ratelimit.Allow { |
| + e.traffic.Load().rate(time.Now(), release.RouteAccount(rt), rt.App, kind) |
| + } |
| reason := "backstop" |
| if d == ratelimit.Shed { |
| reason = "fair-share" |
diff --git a/internal/edge/traffic.go b/internal/edge/traffic.go| new file mode 100644 |
| index 000000000..9700319e3 |
| --- /dev/null |
| +++ b/internal/edge/traffic.go |
| @@ -0,0 +1,492 @@ |
| +package edge |
| + |
| +import ( |
| + "bufio" |
| + "context" |
| + "fmt" |
| + "net" |
| + "net/http" |
| + "slices" |
| + "strings" |
| + "sync" |
| + "time" |
| + "unicode" |
| + "unicode/utf8" |
| + |
| + "github.com/carlosframework/platform/internal/reqrec" |
| + "github.com/carlosframework/platform/internal/status" |
| +) |
| + |
| +// rateKind keeps enforced and observed decisions separate from answer classes. |
| +type rateKind uint8 |
| + |
| +const ( |
| + rateShed rateKind = iota |
| + rateCeiling |
| + rateObserved |
| + ratePlan |
| +) |
| + |
| +// trafficAppKey keeps account and app boundaries even when either contains a slash. |
| +type trafficAppKey struct{ account, app string } |
| + |
| +// trafficSourceKey groups guard matches without retaining a visitor's full address. |
| +type trafficSourceKey struct{ client, country string } |
| + |
| +// trafficCounter holds one open window and three closed ones. One mutex covers |
| +// rotation and updates, so a heartbeat cannot see half of a request's counters. |
| +// The maps stop admitting new keys at their caps; totals still count every hit. |
| +type trafficCounter struct { |
| + mu sync.Mutex |
| + clientID func(string, time.Time) string |
| + first int64 |
| + current status.TrafficWindow |
| + closed []status.TrafficWindow |
| + apps map[trafficAppKey]status.TrafficApp |
| + rateApps map[trafficAppKey]status.TrafficApp |
| + paths map[string]int64 |
| + hosts map[string]int64 |
| + sources map[trafficSourceKey]int64 |
| +} |
| + |
| +// newTrafficCounter starts at the current slot but reports only slots observed |
| +// from their beginning. A process restart therefore leaves a gap in the series. |
| +func newTrafficCounter(now time.Time, clientID func(string, time.Time) string) *trafficCounter { |
| + start := now.UTC().Truncate(status.TrafficWindowLen) |
| + first := start |
| + if now.After(start) { |
| + first = first.Add(status.TrafficWindowLen) |
| + } |
| + c := &trafficCounter{clientID: clientID, first: first.Unix()} |
| + c.reset(start.Unix()) |
| + return c |
| +} |
| + |
| +// reset releases the old window's maps so a flood cannot retain keys across slots. |
| +// The caller holds mu except while constructing the counter. |
| +func (c *trafficCounter) reset(start int64) { |
| + c.current = status.TrafficWindow{Start: start} |
| + c.apps = make(map[trafficAppKey]status.TrafficApp) |
| + c.rateApps = make(map[trafficAppKey]status.TrafficApp) |
| + c.paths = make(map[string]int64) |
| + c.hosts = make(map[string]int64) |
| + c.sources = make(map[trafficSourceKey]int64) |
| +} |
| + |
| +// rotate closes elapsed slots under mu. It jumps over expired history after a |
| +// long idle period, so a late heartbeat does at most three empty-slot rotations. |
| +func (c *trafficCounter) rotate(at time.Time) { |
| + floor := at.UTC().Truncate(status.TrafficWindowLen).Unix() |
| + step := int64(status.TrafficWindowLen / time.Second) |
| + if floor <= c.current.Start { |
| + return |
| + } |
| + if c.current.Start >= c.first { |
| + c.closeWindow() |
| + } |
| + next := c.current.Start + step |
| + if earliest := floor - int64(status.TrafficWindowsKept)*step; next < earliest { |
| + next = earliest |
| + } |
| + c.reset(next) |
| + for c.current.Start < floor { |
| + if c.current.Start >= c.first { |
| + c.closeWindow() |
| + } |
| + c.reset(c.current.Start + step) |
| + } |
| +} |
| + |
| +// closeWindow ranks bounded maps once per slot and enforces the heartbeat's |
| +// encoded-size bound before retaining the result. The caller holds mu. |
| +func (c *trafficCounter) closeWindow() { |
| + w := c.current |
| + w.Apps = trafficTopApps(c.apps, false) |
| + w.RateApps = trafficTopApps(c.rateApps, true) |
| + w.Paths = trafficTopCounts(c.paths) |
| + w.Hosts = trafficTopCounts(c.hosts) |
| + for k, n := range c.sources { |
| + w.Sources = append(w.Sources, status.TrafficSource{Client: k.client, Country: k.country, Hits: n}) |
| + } |
| + slices.SortFunc(w.Sources, func(a, b status.TrafficSource) int { |
| + if a.Hits != b.Hits { |
| + if a.Hits > b.Hits { |
| + return -1 |
| + } |
| + return 1 |
| + } |
| + if n := strings.Compare(a.Client, b.Client); n != 0 { |
| + return n |
| + } |
| + return strings.Compare(a.Country, b.Country) |
| + }) |
| + if len(w.Sources) > status.TrafficTopN { |
| + w.Sources = w.Sources[:status.TrafficTopN] |
| + } |
| + status.TrimTrafficWindow(&w, status.TrafficWindowMaxBytes) |
| + // Retain only the surviving entries, not the backing arrays of all keys. |
| + w.Apps = slices.Clone(w.Apps) |
| + w.RateApps = slices.Clone(w.RateApps) |
| + w.Paths = slices.Clone(w.Paths) |
| + w.Hosts = slices.Clone(w.Hosts) |
| + w.Sources = slices.Clone(w.Sources) |
| + c.closed = append(c.closed, w) |
| + if len(c.closed) > status.TrafficWindowsKept { |
| + c.closed = slices.Clone(c.closed[len(c.closed)-status.TrafficWindowsKept:]) |
| + } |
| +} |
| + |
| +// trafficTopApps ranks served and limited apps by their respective measures, |
| +// with account and app as deterministic tie breakers. |
| +func trafficTopApps(m map[trafficAppKey]status.TrafficApp, rate bool) []status.TrafficApp { |
| + var rows []status.TrafficApp |
| + for _, row := range m { |
| + rows = append(rows, row) |
| + } |
| + slices.SortFunc(rows, func(a, b status.TrafficApp) int { |
| + an, bn := a.Requests, b.Requests |
| + if rate { |
| + an, bn = a.Refused+a.Observed, b.Refused+b.Observed |
| + } |
| + if an != bn { |
| + if an > bn { |
| + return -1 |
| + } |
| + return 1 |
| + } |
| + if n := strings.Compare(a.Account, b.Account); n != 0 { |
| + return n |
| + } |
| + return strings.Compare(a.App, b.App) |
| + }) |
| + if len(rows) > status.TrafficTopN { |
| + rows = rows[:status.TrafficTopN] |
| + } |
| + return rows |
| +} |
| + |
| +// trafficTopCounts makes tied path and hostname lists stable across heartbeats. |
| +func trafficTopCounts(m map[string]int64) []status.TrafficCount { |
| + var rows []status.TrafficCount |
| + for k, n := range m { |
| + rows = append(rows, status.TrafficCount{Key: k, Hits: n}) |
| + } |
| + slices.SortFunc(rows, func(a, b status.TrafficCount) int { |
| + if a.Hits != b.Hits { |
| + if a.Hits > b.Hits { |
| + return -1 |
| + } |
| + return 1 |
| + } |
| + return strings.Compare(a.Key, b.Key) |
| + }) |
| + if len(rows) > status.TrafficTopN { |
| + rows = rows[:status.TrafficTopN] |
| + } |
| + return rows |
| +} |
| + |
| +// trafficText bounds bytes after cleaning, so truncation never leaves invalid |
| +// UTF-8 and every box-provided list key is safe to carry as hostile text. |
| +func trafficText(s string, limit int) string { |
| + s = strings.Map(func(r rune) rune { |
| + if unicode.IsControl(r) { |
| + return '?' |
| + } |
| + return r |
| + }, strings.ToValidUTF8(s, "?")) |
| + if len(s) > limit { |
| + s = s[:limit] |
| + for !utf8.ValidString(s) { |
| + s = s[:len(s)-1] |
| + } |
| + } |
| + // A substring can otherwise keep the request's entire backing string alive. |
| + return strings.Clone(s) |
| +} |
| + |
| +// answer counts the final visitor answer once. Refusals occupy their own class; |
| +// unknown hosts take the separate unknownHost path and never call this method. |
| +func (c *trafficCounter) answer(at time.Time, code int, blockPage bool, path string) { |
| + if c == nil { |
| + return |
| + } |
| + c.mu.Lock() |
| + defer c.mu.Unlock() |
| + c.rotate(at) |
| + if at.Unix() < c.current.Start { |
| + return |
| + } |
| + w := &c.current |
| + w.Requests++ |
| + switch { |
| + case code == 429 || code == 404 && blockPage: |
| + w.Refused++ |
| + case code < 300: |
| + w.S2xx++ |
| + case code < 400: |
| + w.S3xx++ |
| + case code == 404: |
| + w.S404++ |
| + case code < 500: |
| + w.S4xx++ |
| + default: |
| + w.S5xx++ |
| + } |
| + if code == 404 { |
| + key := trafficText(reqrec.MaskPath(path), 512) |
| + if _, ok := c.paths[key]; ok || len(c.paths) < 1024 { |
| + c.paths[key]++ |
| + } |
| + } |
| +} |
| + |
| +// unknownHost counts unroutable visitors even when the answer is a redirect or |
| +// pending page. Its hostname list cannot grow with an attacker's cardinality. |
| +func (c *trafficCounter) unknownHost(at time.Time, host string) { |
| + if c == nil { |
| + return |
| + } |
| + key := trafficText(strings.ToLower(strings.ToValidUTF8(host, "?")), 253) |
| + c.mu.Lock() |
| + defer c.mu.Unlock() |
| + c.rotate(at) |
| + if at.Unix() < c.current.Start { |
| + return |
| + } |
| + c.current.UnknownHost++ |
| + if _, ok := c.hosts[key]; ok || len(c.hosts) < 256 { |
| + c.hosts[key]++ |
| + } |
| +} |
| + |
| +// served attributes app activity at the billing owner, independently of which |
| +// edge counted the visitor's answer. It adds no ingress totals. |
| +func (c *trafficCounter) served(at time.Time, account, app string, code int) { |
| + if c == nil { |
| + return |
| + } |
| + k := trafficAppKey{trafficText(account, 128), trafficText(app, 128)} |
| + c.mu.Lock() |
| + defer c.mu.Unlock() |
| + c.rotate(at) |
| + if at.Unix() < c.current.Start { |
| + return |
| + } |
| + row, ok := c.apps[k] |
| + if !ok && len(c.apps) >= 4096 { |
| + return |
| + } |
| + row.Account, row.App = k.account, k.app |
| + row.Requests++ |
| + if code >= 500 { |
| + row.S5xx++ |
| + } |
| + c.apps[k] = row |
| +} |
| + |
| +// guard records a matched non-burst verdict beside the protection meter. |
| +// Salt lookup precedes mu because it can wait for disk; ordinary answers must |
| +// not queue behind it. Without a salt, only the existing coarse prefix remains. |
| +func (c *trafficCounter) guard(at time.Time, blocked bool, clientIP, country string) { |
| + if c == nil { |
| + return |
| + } |
| + client := "" |
| + if c.clientID != nil { |
| + client = c.clientID(clientIP, at) |
| + } |
| + if client == "" { |
| + client = reqrec.ClientPrefix(clientIP) |
| + } |
| + k := trafficSourceKey{trafficText(client, 64), trafficText(country, 2)} |
| + c.mu.Lock() |
| + defer c.mu.Unlock() |
| + c.rotate(at) |
| + if at.Unix() < c.current.Start { |
| + return |
| + } |
| + if blocked { |
| + c.current.Blocked++ |
| + } else { |
| + c.current.Watched++ |
| + } |
| + if _, ok := c.sources[k]; ok || len(c.sources) < 1024 { |
| + c.sources[k]++ |
| + } |
| +} |
| + |
| +// rate counts decisions without claiming that an observed refusal was enforced. |
| +// The app list includes plan refusals, while each scalar retains its reason. |
| +func (c *trafficCounter) rate(at time.Time, account, app string, kind rateKind) { |
| + if c == nil { |
| + return |
| + } |
| + k := trafficAppKey{trafficText(account, 128), trafficText(app, 128)} |
| + c.mu.Lock() |
| + defer c.mu.Unlock() |
| + c.rotate(at) |
| + if at.Unix() < c.current.Start { |
| + return |
| + } |
| + switch kind { |
| + case rateShed: |
| + c.current.RateShed++ |
| + case rateCeiling: |
| + c.current.RateCeiling++ |
| + case rateObserved: |
| + c.current.RateObserved++ |
| + case ratePlan: |
| + c.current.PlanThrottled++ |
| + } |
| + row, ok := c.rateApps[k] |
| + if !ok && len(c.rateApps) >= 1024 { |
| + return |
| + } |
| + row.Account, row.App = k.account, k.app |
| + if kind == rateObserved { |
| + row.Observed++ |
| + } else { |
| + row.Refused++ |
| + } |
| + c.rateApps[k] = row |
| +} |
| + |
| +// windows returns owned copies of the three most recent completed slots. |
| +// Empty completed slots are included; the partial startup slot never is. |
| +func (c *trafficCounter) windows(now time.Time) []status.TrafficWindow { |
| + if c == nil { |
| + return nil |
| + } |
| + c.mu.Lock() |
| + defer c.mu.Unlock() |
| + c.rotate(now) |
| + floor := now.UTC().Truncate(status.TrafficWindowLen) |
| + earliest := floor.Add(-status.TrafficWindowsKept * status.TrafficWindowLen).Unix() |
| + var out []status.TrafficWindow |
| + for _, w := range c.closed { |
| + if w.Start < earliest || w.Start >= floor.Unix() { |
| + continue |
| + } |
| + w.Apps = slices.Clone(w.Apps) |
| + w.RateApps = slices.Clone(w.RateApps) |
| + w.Paths = slices.Clone(w.Paths) |
| + w.Hosts = slices.Clone(w.Hosts) |
| + w.Sources = slices.Clone(w.Sources) |
| + out = append(out, w) |
| + } |
| + return out |
| +} |
| + |
| +// EnableTraffic starts fleet counting when the agent's edge is ready. Standalone |
| +// edges do not enable it. Atomic publication keeps concurrent requests safe. |
| +func (e *Edge) EnableTraffic(clientID func(string, time.Time) string) { |
| + e.traffic.Store(newTrafficCounter(time.Now(), clientID)) |
| +} |
| + |
| +// TrafficWindows supplies completed windows to the existing status heartbeat. |
| +// It is nil until counting is enabled, so an old or standalone edge adds no data. |
| +func (e *Edge) TrafficWindows(now time.Time) []status.TrafficWindow { |
| + return e.traffic.Load().windows(now) |
| +} |
| + |
| +// ingressNote carries routing facts back to the outermost answer observer. |
| +// Only trusted branches set skip; an incoming header cannot suppress counting. |
| +type ingressNote struct { |
| + skip, unknown bool |
| + host string |
| +} |
| + |
| +// ingressNoteKey isolates the observer's note from other request context values. |
| +type ingressNoteKey struct{} |
| + |
| +// noteIngressSkip excludes platform calls once their origin or target is known. |
| +func noteIngressSkip(r *http.Request) { |
| + if r != nil { |
| + if n, _ := r.Context().Value(ingressNoteKey{}).(*ingressNote); n != nil { |
| + n.skip = true |
| + } |
| + } |
| +} |
| + |
| +// noteIngressUnknown records routing failure separately from the response class. |
| +func noteIngressUnknown(r *http.Request, host string) { |
| + if r != nil { |
| + if n, _ := r.Context().Value(ingressNoteKey{}).(*ingressNote); n != nil { |
| + n.unknown, n.host = true, host |
| + } |
| + } |
| +} |
| + |
| +// observeIngress wraps every answer before any routing branch can return. The |
| +// deferred finish uses the note shared with derived requests across the handler. |
| +func (e *Edge) observeIngress(w http.ResponseWriter, r *http.Request) (http.ResponseWriter, *http.Request, func()) { |
| + c := e.traffic.Load() |
| + if c == nil { |
| + return w, r, func() {} |
| + } |
| + note := &ingressNote{} |
| + if _, door := doorCallerFrom(r.Context()); door || fromTunnel(r.Context()) || hopDoorFrom(r.Context()) { |
| + note.skip = true |
| + } |
| + r = r.WithContext(context.WithValue(r.Context(), ingressNoteKey{}, note)) |
| + out := &ingressWriter{ResponseWriter: w} |
| + return out, r, func() { |
| + if note.skip { |
| + return |
| + } |
| + if note.unknown { |
| + c.unknownHost(time.Now(), note.host) |
| + return |
| + } |
| + c.answer(time.Now(), out.status, out.blockPage, r.URL.Path) |
| + } |
| +} |
| + |
| +// ingressWriter observes the first final header, including 101, without changing |
| +// headers or buffering bodies. Its optional interfaces preserve streams and hops. |
| +type ingressWriter struct { |
| + http.ResponseWriter |
| + status int |
| + blockPage bool |
| +} |
| + |
| +// WriteHeader ignores interim headers when selecting the answer's class. |
| +func (w *ingressWriter) WriteHeader(code int) { |
| + if w.status == 0 && (code >= 200 || code == http.StatusSwitchingProtocols) { |
| + w.status = code |
| + w.blockPage = code == 404 && w.Header().Get("X-Carlos-Ref") != "" |
| + } |
| + w.ResponseWriter.WriteHeader(code) |
| +} |
| + |
| +// Write observes implicit 200 headers before the underlying writer emits them. |
| +func (w *ingressWriter) Write(p []byte) (int, error) { |
| + if w.status == 0 { |
| + w.WriteHeader(http.StatusOK) |
| + } |
| + return w.ResponseWriter.Write(p) |
| +} |
| + |
| +// Flush commits an implicit 200 just as net/http does, then forwards streaming. |
| +func (w *ingressWriter) Flush() { |
| + if w.status == 0 { |
| + w.WriteHeader(http.StatusOK) |
| + } |
| + if f, ok := w.ResponseWriter.(http.Flusher); ok { |
| + f.Flush() |
| + } |
| +} |
| + |
| +// Hijack preserves upgrades and tunnel handshakes without wrapping their bytes. |
| +// A proxy that writes 101 directly on the connection leaves status zero, which |
| +// has the same S2xx classification as 101. |
| +func (w *ingressWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) { |
| + if h, ok := w.ResponseWriter.(http.Hijacker); ok { |
| + return h.Hijack() |
| + } |
| + return nil, nil, fmt.Errorf("edge: underlying ResponseWriter does not support http.Hijacker") |
| +} |
| + |
| +// Unwrap lets response controllers reach deadlines and other transport features. |
| +func (w *ingressWriter) Unwrap() http.ResponseWriter { return w.ResponseWriter } |
diff --git a/internal/edge/traffic_test.go b/internal/edge/traffic_test.go| new file mode 100644 |
| index 000000000..0293e1db3 |
| --- /dev/null |
| +++ b/internal/edge/traffic_test.go |
| @@ -0,0 +1,707 @@ |
| +package edge |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "fmt" |
| + "io" |
| + "net/http" |
| + "net/http/httptest" |
| + "strings" |
| + "sync" |
| + "sync/atomic" |
| + "testing" |
| + "time" |
| + "unicode" |
| + "unicode/utf8" |
| + |
| + "github.com/carlosframework/platform/internal/lbhealth" |
| + "github.com/carlosframework/platform/internal/plans" |
| + "github.com/carlosframework/platform/internal/ratelimit" |
| + "github.com/carlosframework/platform/internal/registry" |
| + "github.com/carlosframework/platform/internal/reqrec" |
| + "github.com/carlosframework/platform/internal/status" |
| + "github.com/carlosframework/platform/internal/tunnelclient" |
| +) |
| + |
| +// trafficStart gives counter tests an aligned UTC start without waiting for a tick. |
| +func trafficStart() time.Time { return time.Date(2026, 11, 1, 10, 0, 0, 0, time.UTC) } |
| + |
| +// TestTrafficWindowsRotateAndKeepThree pins both retention and chronological order. |
| +func TestTrafficWindowsRotateAndKeepThree(t *testing.T) { |
| + at := trafficStart() |
| + c := newTrafficCounter(at, nil) |
| + for i := 0; i < 5; i++ { |
| + for j := 0; j <= i; j++ { |
| + c.answer(at.Add(time.Duration(i)*5*time.Minute), 200, false, "/") |
| + } |
| + } |
| + ws := c.windows(at.Add(25 * time.Minute)) |
| + if len(ws) != 3 { |
| + t.Fatalf("windows: %+v", ws) |
| + } |
| + for i, w := range ws { |
| + if w.Start != at.Add(time.Duration(i+2)*5*time.Minute).Unix() || w.Requests != int64(i+3) { |
| + t.Fatalf("window %d: %+v", i, w) |
| + } |
| + } |
| +} |
| + |
| +// TestTrafficIdleWindowsAreZero distinguishes a running idle edge from a missing heartbeat. |
| +func TestTrafficIdleWindowsAreZero(t *testing.T) { |
| + at := trafficStart() |
| + c := newTrafficCounter(at, nil) |
| + ws := c.windows(at.Add(12 * time.Minute)) |
| + if len(ws) != 2 || ws[0].Requests != 0 || ws[1].Start != at.Add(5*time.Minute).Unix() { |
| + t.Fatalf("idle: %+v", ws) |
| + } |
| + ws = c.windows(at.Add(365 * 24 * time.Hour)) |
| + if len(ws) != 3 || ws[0].Start != at.Add(365*24*time.Hour-15*time.Minute).Unix() { |
| + t.Fatalf("long idle: %+v", ws) |
| + } |
| +} |
| + |
| +// TestTrafficPartialFirstWindowNotReported prevents a restart from claiming a full window. |
| +func TestTrafficPartialFirstWindowNotReported(t *testing.T) { |
| + at := trafficStart() |
| + c := newTrafficCounter(at.Add(2*time.Minute), nil) |
| + c.answer(at.Add(3*time.Minute), 503, false, "/") |
| + if ws := c.windows(at.Add(5 * time.Minute)); len(ws) != 0 { |
| + t.Fatalf("partial: %+v", ws) |
| + } |
| + ws := c.windows(at.Add(15 * time.Minute)) |
| + if len(ws) != 2 || ws[0].Start != at.Add(5*time.Minute).Unix() || ws[0].Requests != 0 { |
| + t.Fatalf("complete: %+v", ws) |
| + } |
| +} |
| + |
| +// TestTrafficAnswerClasses ensures refusals occupy exactly one class. |
| +func TestTrafficAnswerClasses(t *testing.T) { |
| + at := trafficStart() |
| + c := newTrafficCounter(at, nil) |
| + for _, code := range []int{200, 0, 101, 301, 404, 429, 403, 503} { |
| + c.answer(at, code, false, "/probe") |
| + } |
| + c.answer(at, 404, true, "/probe") |
| + w := c.windows(at.Add(5 * time.Minute))[0] |
| + if w.Requests != 9 || w.S2xx != 3 || w.S3xx != 1 || w.S404 != 1 || w.S4xx != 1 || w.S5xx != 1 || w.Refused != 2 || w.Requests != w.Answered()+w.Refused || len(w.Paths) != 1 || w.Paths[0].Hits != 2 { |
| + t.Fatalf("classes: %+v", w) |
| + } |
| +} |
| + |
| +// TestTrafficKeyCapsHold sends flood-sized cardinality through every bounded map. |
| +func TestTrafficKeyCapsHold(t *testing.T) { |
| + at := trafficStart() |
| + c := newTrafficCounter(at, nil) |
| + for i := 0; i < 100000; i++ { |
| + key := fmt.Sprintf("%c%c%c%c%s", 'a'+i%26, 'a'+i/26%26, 'a'+i/676%26, 'a'+i/17576%26, strings.Repeat("<", 500)) |
| + c.unknownHost(at, key[:253]) |
| + c.answer(at, 404, false, "/probe-"+key[:4]+"/"+strings.Repeat("</", 250)) |
| + c.served(at, "acct", key, 503) |
| + c.rate(at, "acct", key, rateShed) |
| + c.guard(at, true, fmt.Sprintf("10.%d.%d.1", i/256, i%256), "IE") |
| + } |
| + if len(c.hosts) != 256 || len(c.paths) != 1024 || len(c.apps) != 4096 || len(c.rateApps) != 1024 || len(c.sources) != 1024 { |
| + t.Fatalf("map caps: %d %d %d %d %d", len(c.hosts), len(c.paths), len(c.apps), len(c.rateApps), len(c.sources)) |
| + } |
| + w := c.windows(at.Add(5 * time.Minute))[0] |
| + b, err := json.Marshal(w) |
| + if err != nil || len(b) > status.TrafficWindowMaxBytes || w.UnknownHost != 100000 || w.S404 != 100000 || w.Blocked != 100000 { |
| + t.Fatalf("flood: bytes=%d err=%v window=%+v", len(b), err, w) |
| + } |
| +} |
| + |
| +// TestTrafficHostSanitised keeps invalid bytes and controls out of the heartbeat. |
| +func TestTrafficHostSanitised(t *testing.T) { |
| + at := trafficStart() |
| + c := newTrafficCounter(at, nil) |
| + c.unknownHost(at, "UPPER\x00\xff"+strings.Repeat("é", 200)) |
| + k := c.windows(at.Add(5 * time.Minute))[0].Hosts[0].Key |
| + if len(k) > 253 || !utf8.ValidString(k) || strings.ContainsFunc(k, unicode.IsControl) || !strings.HasPrefix(k, "upper??") { |
| + t.Fatalf("host: %q (%d bytes)", k, len(k)) |
| + } |
| +} |
| + |
| +// TestTrafficTopNOrder makes tied results independent of map iteration order. |
| +func TestTrafficTopNOrder(t *testing.T) { |
| + at := trafficStart() |
| + c := newTrafficCounter(at, nil) |
| + for i := 19; i >= 0; i-- { |
| + k := fmt.Sprintf("host-%02d", i) |
| + c.unknownHost(at, k) |
| + c.served(at, "a", k, 200) |
| + c.rate(at, "a", k, rateObserved) |
| + c.answer(at, 404, false, "/"+k) |
| + } |
| + ws := c.windows(at.Add(5 * time.Minute)) |
| + w := ws[0] |
| + if len(w.Hosts) != 10 || len(w.Apps) != 10 || len(w.RateApps) != 10 || len(w.Paths) != 10 { |
| + t.Fatalf("tops: %+v", w) |
| + } |
| + for i := range w.Hosts { |
| + if w.Hosts[i].Key != fmt.Sprintf("host-%02d", i) || w.Apps[i].App != w.Hosts[i].Key || w.RateApps[i].App != w.Hosts[i].Key { |
| + t.Fatalf("order: %+v", w) |
| + } |
| + } |
| + ws[0].Hosts[0].Key = "changed" |
| + if c.windows(at.Add(5 * time.Minute))[0].Hosts[0].Key == "changed" { |
| + t.Fatal("snapshot aliases retained lists") |
| + } |
| +} |
| + |
| +// TestTrafficConcurrentCounts exercises heartbeat reads alongside request completion. |
| +func TestTrafficConcurrentCounts(t *testing.T) { |
| + at := trafficStart() |
| + c := newTrafficCounter(at, nil) |
| + var wg sync.WaitGroup |
| + for range 8 { |
| + wg.Go(func() { |
| + for range 100 { |
| + c.answer(at, 200, false, "/") |
| + c.windows(at) |
| + } |
| + }) |
| + } |
| + wg.Wait() |
| + if w := c.windows(at.Add(5 * time.Minute))[0]; w.Requests != 800 { |
| + t.Fatalf("concurrent: %+v", w) |
| + } |
| +} |
| + |
| +// enableTestTraffic includes the current slot so integration tests need no five-minute sleep. |
| +func enableTestTraffic(edges ...*Edge) time.Time { |
| + at := time.Now().UTC().Truncate(status.TrafficWindowLen) |
| + for _, e := range edges { |
| + e.EnableTraffic(nil) |
| + e.traffic.Store(newTrafficCounter(at, nil)) |
| + } |
| + return at.Add(status.TrafficWindowLen) |
| +} |
| + |
| +// trafficWindow closes the test slot after all handlers have returned. |
| +func trafficWindow(t *testing.T, e *Edge, end time.Time) status.TrafficWindow { |
| + t.Helper() |
| + ws := e.TrafficWindows(end) |
| + if len(ws) != 1 { |
| + t.Fatalf("windows: %+v", ws) |
| + } |
| + return ws[0] |
| +} |
| + |
| +// trafficGet runs the actual routing path synchronously, including its observer defers. |
| +func trafficGet(e *Edge, host, path string) *httptest.ResponseRecorder { |
| + w := httptest.NewRecorder() |
| + r := httptest.NewRequest("GET", "http://"+host+path, nil) |
| + r.RemoteAddr = "203.0.113.1:1234" |
| + e.ServeHTTP(w, r) |
| + return w |
| +} |
| + |
| +// trafficHandlersDone waits for the server-side defers, which can finish after |
| +// a client has read the last byte of a response. |
| +func trafficHandlersDone(t *testing.T, s *backhaulScene) { |
| + t.Helper() |
| + laWaitFor(t, "traffic observers to return", func() bool { |
| + return s.a.served.Load() == s.a.calls.Load() && s.b.served.Load() == s.b.calls.Load() |
| + }) |
| +} |
| + |
| +// trafficOnce asserts the counting owner as well as the fleet-wide partition. |
| +func trafficOnce(t *testing.T, front, home *Edge, end time.Time, code int) (status.TrafficWindow, status.TrafficWindow) { |
| + t.Helper() |
| + a, b := trafficWindow(t, front, end), trafficWindow(t, home, end) |
| + if a.Requests != 1 || b.Requests+b.UnknownHost != 0 || a.UnknownHost != 0 || a.Requests != a.Answered()+a.Refused { |
| + t.Fatalf("front=%+v home=%+v", a, b) |
| + } |
| + if (code == 429 || code == 404) && a.Refused != 1 || code >= 500 && a.S5xx != 1 || code == 200 && a.S2xx != 1 { |
| + t.Fatalf("status %d: %+v", code, a) |
| + } |
| + return a, b |
| +} |
| + |
| +// TestEdgeTrafficIngressDirect counts a served app even without a usage or log sink. |
| +func TestEdgeTrafficIngressDirect(t *testing.T) { |
| + g := guardEdge(t, false, false, 200, "ok") |
| + end := enableTestTraffic(g.e) |
| + if w := g.get("/"); w.Code != 200 { |
| + t.Fatal(w.Code) |
| + } |
| + w := trafficWindow(t, g.e, end) |
| + if w.Requests != 1 || w.S2xx != 1 || len(w.Apps) != 1 || w.Apps[0].App != "shop" || w.Apps[0].Requests != 1 { |
| + t.Fatalf("direct: %+v", w) |
| + } |
| +} |
| + |
| +// TestEdgeTrafficIngressBackhaulDelivered separates ingress ownership from serving ownership. |
| +func TestEdgeTrafficIngressBackhaulDelivered(t *testing.T) { |
| + s := newBackhaulScene(t) |
| + s.converge(t) |
| + end := enableTestTraffic(s.a.edge, s.b.edge) |
| + resp, _ := s.get(t, s.b, "https://"+e2eHomedHost+"/", nil, false) |
| + if resp.StatusCode != 200 { |
| + t.Fatal(resp.StatusCode) |
| + } |
| + trafficHandlersDone(t, s) |
| + _, home := trafficOnce(t, s.b.edge, s.a.edge, end, 200) |
| + if len(home.Apps) != 1 || home.Apps[0].Requests != 1 { |
| + t.Fatalf("home app: %+v", home) |
| + } |
| +} |
| + |
| +// TestEdgeTrafficIngressBackhaulEarlyHome503 covers the return before the home's observer. |
| +func TestEdgeTrafficIngressBackhaulEarlyHome503(t *testing.T) { |
| + s := newBackhaulScene(t) |
| + s.converge(t) |
| + end := enableTestTraffic(s.a.edge, s.b.edge) |
| + resp, _ := s.get(t, s.b, "https://"+e2eMovedHost+"/", nil, false) |
| + if resp.StatusCode != 503 { |
| + t.Fatal(resp.StatusCode) |
| + } |
| + trafficHandlersDone(t, s) |
| + trafficOnce(t, s.b.edge, s.a.edge, end, 503) |
| +} |
| + |
| +// TestEdgeTrafficIngressBackhaulRefusals covers admission, saturation and a closed home. |
| +func TestEdgeTrafficIngressBackhaulRefusals(t *testing.T) { |
| + for _, kind := range []string{"admission", "saturation", "dial"} { |
| + t.Run(kind, func(t *testing.T) { |
| + s := newBackhaulScene(t) |
| + s.converge(t) |
| + end := enableTestTraffic(s.a.edge, s.b.edge) |
| + s.b.edge.rateMode = RateEnforce |
| + backhaulCap(t, 64) |
| + want := 503 |
| + if kind == "dial" { |
| + s.a.door.Close() |
| + want = 502 |
| + } else { |
| + n, key := 64, "" |
| + if kind == "admission" { |
| + n, key, want = 32, "203.0.113.1/32", 429 |
| + } |
| + for range n { |
| + release, ok, shed := s.b.edge.backhaulAcquire("annie", key) |
| + if !ok || shed { |
| + t.Fatal("precondition: could not fill slots") |
| + } |
| + t.Cleanup(release) |
| + } |
| + } |
| + w := trafficGet(s.b.edge, e2eHomedHost, "/") |
| + if w.Code != want { |
| + t.Fatalf("%s: %d", kind, w.Code) |
| + } |
| + trafficOnce(t, s.b.edge, s.a.edge, end, want) |
| + }) |
| + } |
| +} |
| + |
| +// TestEdgeTrafficIngressHomeRefusalKeepsClass verifies refusal headers survive the real hop. |
| +func TestEdgeTrafficIngressHomeRefusalKeepsClass(t *testing.T) { |
| + for _, kind := range []string{"rate", "guard"} { |
| + t.Run(kind, func(t *testing.T) { |
| + s := newBackhaulSceneWith(t, backhaulSceneExtra{}) |
| + s.converge(t) |
| + rt, ok := s.a.edge.lookupUpstream(e2eHomedHost) |
| + if !ok { |
| + t.Fatal("missing home") |
| + } |
| + row := rt.route |
| + row.Kind = "instance" |
| + row.RateLimit = `{"rate":1,"burst":1}` |
| + if err := s.a.reg.Upsert(row); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := s.a.edge.Reload(); err != nil { |
| + t.Fatal(err) |
| + } |
| + s.a.edge.EnableUsage(NewUsageMeter()) |
| + s.a.edge.rateMode = RateEnforce |
| + path, want := "/", 429 |
| + if kind == "guard" { |
| + s.a.edge.guard = guardBlock |
| + path, want = "/.env", 404 |
| + } else { |
| + if w := trafficGet(s.b.edge, e2eHomedHost, "/"); w.Code != 200 { |
| + t.Fatal(w.Code) |
| + } |
| + } |
| + trafficHandlersDone(t, s) |
| + end := enableTestTraffic(s.a.edge, s.b.edge) |
| + w := trafficGet(s.b.edge, e2eHomedHost, path) |
| + if w.Code != want { |
| + t.Fatal(w.Code) |
| + } |
| + trafficHandlersDone(t, s) |
| + _, home := trafficOnce(t, s.b.edge, s.a.edge, end, want) |
| + if kind == "guard" && home.Blocked != 1 || kind == "rate" && home.RateCeiling != 1 { |
| + t.Fatalf("decision: %+v", home) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// TestEdgeTrafficIngressForwardHA counts both a holder's answer and a local unreachable refusal. |
| +func TestEdgeTrafficIngressForwardHA(t *testing.T) { |
| + for _, refuse := range []bool{false, true} { |
| + t.Run(fmt.Sprint(refuse), func(t *testing.T) { |
| + s := newFwScene(t, fwOpts{}) |
| + s.aAct.refuse = refuse |
| + end := enableTestTraffic(s.a.edge, s.b.edge) |
| + resp, _ := s.fetch(t, fwHost, "/") |
| + want := 200 |
| + if refuse { |
| + want = 503 |
| + } |
| + if resp.StatusCode != want { |
| + t.Fatal(resp.StatusCode) |
| + } |
| + trafficHandlersDone(t, s.backhaulScene) |
| + trafficOnce(t, s.a.edge, s.b.edge, end, want) |
| + }) |
| + } |
| +} |
| + |
| +// TestEdgeTrafficIngressFarAsset keeps the far edge as owner even when a fill must be forwarded again. |
| +func TestEdgeTrafficIngressFarAsset(t *testing.T) { |
| + for _, kind := range []string{"fill", "unacknowledged", "fallback"} { |
| + t.Run(kind, func(t *testing.T) { |
| + s := newAssetE2E(t, assetE2EOpts{handler: assetOK(laBody), homeUnarmed: kind == "unacknowledged"}) |
| + end := enableTestTraffic(s.a.edge, s.b.edge) |
| + path := "/assets/app.js" |
| + if kind == "fallback" { |
| + path = "/assets/../assets/app.js" |
| + } |
| + resp, _ := s.fetch(t, s.b, path) |
| + if resp.StatusCode != 200 { |
| + t.Fatal(resp.StatusCode) |
| + } |
| + trafficHandlersDone(t, s.backhaulScene) |
| + front, home := trafficOnce(t, s.b.edge, s.a.edge, end, 200) |
| + if kind == "fill" && (len(front.Apps) != 1 || len(home.Apps) != 0) { |
| + t.Fatalf("fill apps front=%+v home=%+v", front.Apps, home.Apps) |
| + } |
| + if kind != "fill" && (len(home.Apps) != 1 || len(front.Apps) != 0) { |
| + t.Fatalf("forward apps front=%+v home=%+v", front.Apps, home.Apps) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// TestEdgeTrafficTunnelAndDoorSkipped excludes calls whose visitor was counted elsewhere. |
| +func TestEdgeTrafficTunnelAndDoorSkipped(t *testing.T) { |
| + g := guardEdge(t, false, true, 200, "ok") |
| + end := enableTestTraffic(g.e) |
| + r := httptest.NewRequest("GET", "http://app.test/", nil) |
| + tunnelclient.Mark(g.e).ServeHTTP(httptest.NewRecorder(), r) |
| + r = r.WithContext(context.WithValue(r.Context(), doorCallerKey{}, doorCaller{Account: "local", App: "shop"})) |
| + g.e.ServeHTTP(httptest.NewRecorder(), r) |
| + r = httptest.NewRequest("GET", "http://app.test/", nil) |
| + r.Header.Set(hopHeader, "1") |
| + r.Header.Set(hopAuthHeader, signHop(g.key, "app.test", time.Now())) |
| + r.Header.Set(hopDoorHeader, signHopDoor(g.key, "app.test", time.Now())) |
| + g.e.ServeHTTP(httptest.NewRecorder(), r) |
| + if w := trafficWindow(t, g.e, end); w.Requests+w.UnknownHost != 0 { |
| + t.Fatalf("internal calls: %+v", w) |
| + } |
| +} |
| + |
| +// TestEdgeTrafficInfraProbesSkipped pins R3's steering and load-balancer exclusions. |
| +func TestEdgeTrafficInfraProbesSkipped(t *testing.T) { |
| + e := steeringEdge(t, "Z0ABCDEF1234", "example.com", "") |
| + t.Cleanup(e.probers.Stop) |
| + end := enableTestTraffic(e) |
| + if w := trafficGet(e, "edge.example.com", "/"); w.Code != 200 { |
| + t.Fatal(w.Code) |
| + } |
| + if w := fallbackGet(e, "GET", "/", "edge.example.com"); w.Code != 200 { |
| + t.Fatal(w.Code) |
| + } |
| + for _, healthy := range []bool{true, false} { |
| + e.lbHealth = healthyState() |
| + e.lbHealth.SetHosting(healthy) |
| + w := fallbackGet(e, "GET", lbhealth.Path, "10.0.1.7") |
| + want := 503 |
| + if healthy { |
| + want = 200 |
| + } |
| + if w.Code != want { |
| + t.Fatal(w.Code) |
| + } |
| + } |
| + if w := trafficWindow(t, e, end); w.Requests+w.UnknownHost != 0 || len(w.Apps)+len(w.Paths)+len(w.Hosts) != 0 { |
| + t.Fatalf("probes: %+v", w) |
| + } |
| +} |
| + |
| +// TestEdgeTrafficUnknownHostOutsiderOnly keeps unknown-host answers outside the request partition. |
| +func TestEdgeTrafficUnknownHostOutsiderOnly(t *testing.T) { |
| + e, _, _ := hopEdge(t, "annie") |
| + end := enableTestTraffic(e) |
| + trafficGet(e, "UNKNOWN.test:443", "/probe") |
| + r := httptest.NewRequest("GET", "http://elsewhere.test/", nil) |
| + r = r.WithContext(context.WithValue(r.Context(), doorCallerKey{}, doorCaller{Account: "abc", App: "shop"})) |
| + e.ServeHTTP(httptest.NewRecorder(), r) |
| + w := trafficWindow(t, e, end) |
| + if w.UnknownHost != 1 || w.Requests != 0 || len(w.Hosts) != 1 || w.Hosts[0].Key != "unknown.test" { |
| + t.Fatalf("unknown: %+v", w) |
| + } |
| +} |
| + |
| +// TestEdgeTrafficGuardMatchesUsageMeter uses the same decisions and burst exclusion as protection. |
| +func TestEdgeTrafficGuardMatchesUsageMeter(t *testing.T) { |
| + g := guardEdge(t, false, false, 200, "ok") |
| + m := NewUsageMeter() |
| + g.e.EnableUsage(m) |
| + end := enableTestTraffic(g.e) |
| + g.e.guard = guardBlock |
| + g.get("/.env") |
| + g.get("/admin") |
| + g.e.guard = guardWatch |
| + g.get("/wp-login.php") |
| + w := trafficWindow(t, g.e, end) |
| + var blocked, watched int64 |
| + for _, d := range m.Drain().Guard { |
| + blocked += d.Block |
| + watched += d.Watch |
| + } |
| + if w.Blocked != 1 || w.Watched != 1 || w.Blocked != blocked || w.Watched != watched || len(w.Sources) != 1 || w.Sources[0].Hits != 2 { |
| + t.Fatalf("traffic=%+v meter=%d/%d", w, blocked, watched) |
| + } |
| +} |
| + |
| +// TestEdgeTrafficRateEnforcedVsObserved distinguishes a refusal from a would-be refusal. |
| +func TestEdgeTrafficRateEnforcedVsObserved(t *testing.T) { |
| + for _, mode := range []string{"enforce", "observe"} { |
| + t.Run(mode, func(t *testing.T) { |
| + ts, _ := countingUpstream(t, "ok", nil) |
| + s := newRateScene(t, mode, nil, rlRoute(ts.Listener.Addr().String(), `{"rate":1,"burst":1}`)) |
| + end := enableTestTraffic(s.e) |
| + frozen := time.Now() |
| + s.e.rateLimiter = ratelimit.NewLimiter(func() time.Time { return frozen }, 1000) |
| + trafficGet(s.e, rlHost, "/") |
| + response := trafficGet(s.e, rlHost, "/") |
| + w := trafficWindow(t, s.e, end) |
| + if len(w.RateApps) != 1 { |
| + t.Fatalf("rate apps: %+v", w) |
| + } |
| + if mode == "enforce" { |
| + if response.Code != 429 || w.Refused != 1 || w.RateCeiling != 1 || w.RateObserved != 0 || w.RateApps[0].Refused != 1 { |
| + t.Fatalf("enforced: %+v", w) |
| + } |
| + } else if response.Code != 200 || w.Refused != 0 || w.RateCeiling != 0 || w.RateObserved != 1 || w.RateApps[0].Observed != 1 { |
| + t.Fatalf("observed: %+v", w) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// TestTrafficSourceFallback checks that an unavailable salt retains only the existing prefix. |
| +func TestTrafficSourceFallback(t *testing.T) { |
| + at := trafficStart() |
| + for _, hash := range []string{"", "0123456789ab"} { |
| + c := newTrafficCounter(at, func(ip string, when time.Time) string { |
| + if ip != "203.0.113.7" || !when.Equal(at) { |
| + t.Fatal("wrong identity inputs") |
| + } |
| + return hash |
| + }) |
| + c.guard(at, false, "203.0.113.7", "IE") |
| + w := c.windows(at.Add(5 * time.Minute))[0] |
| + want := hash |
| + if want == "" { |
| + want = reqrec.ClientPrefix("203.0.113.7") |
| + } |
| + if len(w.Sources) != 1 || w.Sources[0].Client != want || w.Sources[0].Country != "IE" { |
| + t.Fatalf("source: %+v", w) |
| + } |
| + } |
| +} |
| + |
| +// TestEdgeTrafficDisabled keeps standalone edges out of heartbeat reporting. |
| +func TestEdgeTrafficDisabled(t *testing.T) { |
| + e := &Edge{} |
| + if ws := e.TrafficWindows(time.Now()); ws != nil { |
| + t.Fatalf("disabled: %+v", ws) |
| + } |
| +} |
| + |
| +// TestEdgeTrafficReservedHostsSkipped keeps status, tunnel and store-door |
| +// requests out of both the HTTPS counts and the HTTP redirect counts. |
| +func TestEdgeTrafficReservedHostsSkipped(t *testing.T) { |
| + reg := openReg(t) |
| + if err := reg.Upsert(registry.Route{Host: "status.test", Kind: "status", Status: "ready"}); err != nil { |
| + t.Fatal(err) |
| + } |
| + e, err := New(reg, nil) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(e.probers.Stop) |
| + e.EnableTunnels(NewTunnelHub("tunnel.test", nil)) |
| + end := enableTestTraffic(e) |
| + for _, path := range []struct{ host, path string }{{"status.test", "/"}, {"tunnel.test", "/register"}, {"tunnel.test", "/store/x"}} { |
| + trafficGet(e, path.host, path.path) |
| + fallbackGet(e, "GET", path.path, path.host) |
| + } |
| + if w := trafficWindow(t, e, end); w.Requests+w.UnknownHost != 0 { |
| + t.Fatalf("reserved hosts: %+v", w) |
| + } |
| +} |
| + |
| +// TestEdgeTrafficHTTPFallback counts an ordinary redirect and an unknown host |
| +// separately; probe exclusions must not suppress visitor requests on port 80. |
| +func TestEdgeTrafficHTTPFallback(t *testing.T) { |
| + e, _, _ := hopEdge(t, "annie", "app.test") |
| + end := enableTestTraffic(e) |
| + fallbackGet(e, "GET", "/", "app.test") |
| + fallbackGet(e, "GET", "/", "unknown.test") |
| + w := trafficWindow(t, e, end) |
| + if w.Requests != 1 || w.S3xx != 1 || w.UnknownHost != 1 { |
| + t.Fatalf("http: %+v", w) |
| + } |
| +} |
| + |
| +// TestEdgeTrafficForgedHopIsCounted prevents an untrusted header from hiding traffic. |
| +func TestEdgeTrafficForgedHopIsCounted(t *testing.T) { |
| + e, _, _ := hopEdge(t, "annie", "app.test") |
| + end := enableTestTraffic(e) |
| + r := httptest.NewRequest("GET", "http://app.test/", nil) |
| + r.Header.Set(hopHeader, "1") |
| + r.Header.Set(hopAuthHeader, "forged") |
| + r.Header.Set(hopDoorHeader, "forged") |
| + e.ServeHTTP(httptest.NewRecorder(), r) |
| + if w := trafficWindow(t, e, end); w.Requests != 1 { |
| + t.Fatalf("forged hop: %+v", w) |
| + } |
| +} |
| + |
| +// TestEdgeTrafficPlanRefusal counts plan throttling even while rate limiting observes. |
| +func TestEdgeTrafficPlanRefusal(t *testing.T) { |
| + var on, awake atomic.Bool |
| + on.Store(true) |
| + s := throttleScene(t, &on, &awake, okBackend(t)) |
| + for range plans.ThrottleRule.Burst { |
| + trafficGet(s.e, ptHost, "/") |
| + } |
| + end := enableTestTraffic(s.e) |
| + if w := trafficGet(s.e, ptHost, "/"); w.Code != 429 { |
| + t.Fatal(w.Code) |
| + } |
| + w := trafficWindow(t, s.e, end) |
| + if w.PlanThrottled != 1 || w.Refused != 1 || w.RateObserved+w.RateShed+w.RateCeiling != 0 || len(w.RateApps) != 1 || w.RateApps[0].Refused != 1 { |
| + t.Fatalf("plan: %+v", w) |
| + } |
| +} |
| + |
| +// TestEdgeTrafficRateShed records an enforced fair-share decision at the serving edge. |
| +func TestEdgeTrafficRateShed(t *testing.T) { |
| + up := newBlockingUpstream(t) |
| + s := newRateScene(t, "enforce", nil, rlRoute(up.addr(), `{"busy_at":2,"client_share":1}`)) |
| + t.Cleanup(up.open) |
| + a := s.goGet("203.0.113.1", rlHost, "/a") |
| + up.waitArrived(t, "first") |
| + b := s.goGet("203.0.113.2", rlHost, "/b") |
| + up.waitArrived(t, "second") |
| + end := enableTestTraffic(s.e) |
| + if w := trafficGet(s.e, rlHost, "/refused"); w.Code != 429 { |
| + t.Fatal(w.Code) |
| + } |
| + w := trafficWindow(t, s.e, end) |
| + if w.RateShed != 1 || w.Refused != 1 || w.RateCeiling+w.RateObserved != 0 { |
| + t.Fatalf("shed: %+v", w) |
| + } |
| + up.open() |
| + wantOK(t, waitResult(t, a, "first"), "first") |
| + wantOK(t, waitResult(t, b, "second"), "second") |
| +} |
| + |
| +// TestTrafficIngressWriterFinalStatus observes committed headers, including |
| +// flush and upgrade, without letting interim headers or trailers reclassify them. |
| +func TestTrafficIngressWriterFinalStatus(t *testing.T) { |
| + for _, tc := range []struct { |
| + name string |
| + write func(http.ResponseWriter) |
| + code int |
| + block bool |
| + }{ |
| + {"interim", func(w http.ResponseWriter) { w.WriteHeader(103); w.WriteHeader(503) }, 503, false}, |
| + {"upgrade", func(w http.ResponseWriter) { w.WriteHeader(101) }, 101, false}, |
| + {"flush", func(w http.ResponseWriter) { w.(http.Flusher).Flush(); w.WriteHeader(503) }, 200, false}, |
| + {"write", func(w http.ResponseWriter) { io.WriteString(w, "ok") }, 200, false}, |
| + {"block", func(w http.ResponseWriter) { |
| + w.Header().Set("X-Carlos-Ref", "ref") |
| + w.WriteHeader(404) |
| + w.Header().Del("X-Carlos-Ref") |
| + }, 404, true}, |
| + {"late ref", func(w http.ResponseWriter) { w.WriteHeader(404); w.Header().Set("X-Carlos-Ref", "ref") }, 404, false}, |
| + } { |
| + t.Run(tc.name, func(t *testing.T) { |
| + w := &ingressWriter{ResponseWriter: httptest.NewRecorder()} |
| + tc.write(w) |
| + if w.status != tc.code || w.blockPage != tc.block { |
| + t.Fatalf("status=%d block=%v", w.status, w.blockPage) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// TestTrafficClientIDOutsideLock lets the callback count another answer, which |
| +// would deadlock if salt lookup held the counter mutex. |
| +func TestTrafficClientIDOutsideLock(t *testing.T) { |
| + at := trafficStart() |
| + var c *trafficCounter |
| + c = newTrafficCounter(at, func(string, time.Time) string { c.answer(at, 200, false, "/"); return "hash" }) |
| + done := make(chan struct{}) |
| + go func() { c.guard(at, true, "203.0.113.1", "IE"); close(done) }() |
| + select { |
| + case <-done: |
| + case <-time.After(time.Second): |
| + t.Fatal("clientID called under the traffic mutex") |
| + } |
| + w := c.windows(at.Add(5 * time.Minute))[0] |
| + if w.Requests != 1 || w.Blocked != 1 { |
| + t.Fatalf("callback: %+v", w) |
| + } |
| +} |
| + |
| +// TestEdgeTrafficUpgrade preserves hijacking through the outer writer and counts |
| +// the completed upgraded request as S2xx, just like an explicit 101 header. |
| +func TestEdgeTrafficUpgrade(t *testing.T) { |
| + backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + conn, buf, err := w.(http.Hijacker).Hijack() |
| + if err != nil { |
| + return |
| + } |
| + defer conn.Close() |
| + buf.WriteString("HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n\r\n") |
| + if buf.Flush() != nil { |
| + return |
| + } |
| + line, err := buf.ReadString('\n') |
| + if err != nil { |
| + return |
| + } |
| + buf.WriteString("echo:" + line) |
| + buf.Flush() |
| + })) |
| + t.Cleanup(backend.Close) |
| + s := newRateScene(t, "off", nil, registry.Route{Host: ptHost, Kind: "instance", Addr: backend.Listener.Addr().String(), Status: "ready", App: "shop"}) |
| + end := enableTestTraffic(s.e) |
| + conn, reader, code := openSocket(t, s, ptHost) |
| + defer conn.Close() |
| + if code != 101 { |
| + t.Fatalf("upgrade: %d", code) |
| + } |
| + fmt.Fprint(conn, "hello\n") |
| + line, err := reader.ReadString('\n') |
| + if err != nil || line != "echo:hello\n" { |
| + t.Fatalf("echo %q: %v", line, err) |
| + } |
| + conn.Close() |
| + laWaitFor(t, "upgraded request to finish", func() bool { c := s.e.traffic.Load(); c.mu.Lock(); defer c.mu.Unlock(); return c.current.Requests == 1 }) |
| + w := trafficWindow(t, s.e, end) |
| + if w.Requests != 1 || w.S2xx != 1 { |
| + t.Fatalf("upgrade counters: %+v", w) |
| + } |
| +} |
diff --git a/internal/reqrec/recorder.go b/internal/reqrec/recorder.go| index e12bc910d..6a47cdc2d 100644 |
| --- a/internal/reqrec/recorder.go |
| +++ b/internal/reqrec/recorder.go |
| @@ -337,6 +337,20 @@ func (r *Recorder) Match(m Match) { |
| string(m.Kind)+" "+m.Tier.String()+" "+m.RuleID+" "+f["method"]+" "+f["path"], f) |
| } |
| +// ClientID returns the same daily identifier as request records, so fleet |
| +// traffic sources can be compared with Logs. Call without r.mu held: obtaining |
| +// a salt may wait for disk. A missing recorder, salt or client key yields "". |
| +func (r *Recorder) ClientID(ip string, at time.Time) string { |
| + if r == nil { |
| + return "" |
| + } |
| + key := ClientKey(ip) |
| + if key == "" { |
| + return "" |
| + } |
| + return ClientHash(r.saltFor(at.UTC().Format("2006-01-02")), key) |
| +} |
| + |
| // fields builds the redacted record body shared by not-found and match records. |
| // Empty values are left out. Every request-derived string is bounded and has |
| // its controls escaped: the method is one of a few words, the path and query |
diff --git a/internal/reqrec/recorder_test.go b/internal/reqrec/recorder_test.go| index f5d66ac79..2f5c0960a 100644 |
| --- a/internal/reqrec/recorder_test.go |
| +++ b/internal/reqrec/recorder_test.go |
| @@ -482,3 +482,18 @@ func TestRecorderFragmentControlsEscaped(t *testing.T) { |
| t.Fatalf("frag %q path %q msg %q", f["frag"], f["path"], s.msgs[0]) |
| } |
| } |
| + |
| +// TestRecorderClientIDMatchesRecords keeps fleet source IDs joinable with Logs. |
| +func TestRecorderClientIDMatchesRecords(t *testing.T) { |
| + at := time.Date(2026, 11, 1, 10, 0, 0, 0, time.UTC) |
| + sink := &memSink{} |
| + r := NewRecorder(sink, func(day string) []byte { return []byte("salt for " + day) }, func() time.Time { return at }) |
| + r.Response(Response{Acct: "abc", App: "shop", Status: 404, ClientIP: "203.0.113.7", When: at}) |
| + if len(sink.recs) != 1 || r.ClientID("203.0.113.7", at) == "" || r.ClientID("203.0.113.7", at) != sink.recs[0]["cid"] { |
| + t.Fatalf("records: %+v", sink.recs) |
| + } |
| + var absent *Recorder |
| + if absent.ClientID("203.0.113.7", at) != "" || NewRecorder(sink, nil, func() time.Time { return at }).ClientID("203.0.113.7", at) != "" || r.ClientID("bad", at) != "" { |
| + t.Fatal("unavailable identity must be empty") |
| + } |
| +} |