carlos / platform Public

edge: count protection checks and matches into the usage meter

The usage meter now keeps protection counts per host-owner beside its
traffic rows: RecordGuard counts every request the guard checked, and
every watch or block under its tier/group (burst rules are checked, never
caught). Drain hands both to the flush as a usage.EdgeFlush.

Counts follow records: ServeHTTP's observer defer and serveAssetFar's
defer each count once per guard state, beside the observeRecords call and
under the same "this box answered it" condition, whether or not records
are on. A backhauled probe is counted once, by the home.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev 484709a41e4d7fe4c6d6beea13ff0a8a2e3484e3 parent 007ea99
22 files changed, +579 −55
  • fleet_public_routes_e2e_test.go +1 −1
  • internal/edge/asset_e2e_test.go +1 −1
  • internal/edge/asset_far_test.go +5 −5
  • internal/edge/asset_local_test.go +6 −6
  • internal/edge/assetcatch.go +8 −3
  • internal/edge/backhaul_e2e_test.go +2 −2
  • internal/edge/compress_test.go +1 −1
  • internal/edge/edge.go +5 −0
  • internal/edge/edge_test.go +1 −1
  • internal/edge/forwardha_test.go +1 −1
  • internal/edge/gate_test.go +1 −1
  • internal/edge/guard.go +21 −0
  • internal/edge/guard_usage_test.go +339 −0
  • internal/edge/path_test.go +1 −1
  • internal/edge/planthrottle_test.go +1 −1
  • internal/edge/ratelimit_test.go +4 −4
  • internal/edge/regional_e2e_test.go +1 −1
  • internal/edge/usagemeter.go +55 −7
  • internal/edge/usagemeter_test.go +81 −5
  • internal/host/applessroute_test.go +1 −1
  • internal/host/usage_loop.go +7 −7
  • internal/host/usage_loop_test.go +36 −6
diff --git a/fleet_public_routes_e2e_test.go b/fleet_public_routes_e2e_test.go
index 66ff7935f..8d7a0b1be 100644
--- a/fleet_public_routes_e2e_test.go
+++ b/fleet_public_routes_e2e_test.go
@@ -614,7 +614,7 @@ func TestFleetAppServesThroughTheHub(t *testing.T) {
if got := fprCount(t, upAddr); got != oks {
t.Fatalf("the app saw %d requests for /limited, want the %d admitted: the refused one never crossed the tunnel", got, oks)
}
- if h, b := hubMeter.Drain()[shopHost], boxMeter.Drain()[shopHost]; h.RateCeiling != 1 || b.RateCeiling != 0 {
+ if h, b := hubMeter.Drain().Rows[shopHost], boxMeter.Drain().Rows[shopHost]; h.RateCeiling != 1 || b.RateCeiling != 0 {
t.Fatalf("refusals counted: hub %d, box %d; want the hub's 1 and none on the box", h.RateCeiling, b.RateCeiling)
}
diff --git a/internal/edge/asset_e2e_test.go b/internal/edge/asset_e2e_test.go
index 5b1f04198..c6fc187ef 100644
--- a/internal/edge/asset_e2e_test.go
+++ b/internal/edge/asset_e2e_test.go
@@ -431,7 +431,7 @@ type usageRowView struct {
}
func rowOf(m *UsageMeter) usageRowView {
- r := m.Drain()[laHost]
+ r := m.Drain().Rows[laHost]
return usageRowView{r.Requests, r.BytesOut, r.HopRequests, r.HopBytesOut}
}
diff --git a/internal/edge/asset_far_test.go b/internal/edge/asset_far_test.go
index db6c79d78..de1af1235 100644
--- a/internal/edge/asset_far_test.go
+++ b/internal/edge/asset_far_test.go
@@ -165,7 +165,7 @@ func (s *farScene) key(path string) assetcache.Key {
}
func (s *farScene) row() (requests, bytes int64, ok bool) {
- row, ok := s.meter.Drain()[laHost]
+ row, ok := s.meter.Drain().Rows[laHost]
return row.Requests, row.BytesOut, ok
}
@@ -259,7 +259,7 @@ func TestFarAcknowledgedFillIsMeteredOnceAtTheFarEdge(t *testing.T) {
s := newFarScene(t, assetOK(laBody))
wantCache(t, s.get(t, "/assets/app.js"), "miss")
wantCache(t, s.get(t, "/assets/app.js"), "hit")
- row := s.meter.Drain()[laHost]
+ row := s.meter.Drain().Rows[laHost]
if row.Requests != 2 || row.BytesOut != int64(2*len(laBody)) {
t.Fatalf("row = %+v, want the fill and the hit metered once each (%d bytes each)", row, len(laBody))
}
@@ -851,7 +851,7 @@ func TestFarHitsPassThePlanThrottle(t *testing.T) {
if refused != 1 {
t.Fatalf("%d far hits refused past the throttle's burst, want 1", refused)
}
- row := s.meter.Drain()[laHost]
+ row := s.meter.Drain().Rows[laHost]
if row.PlanThrottled != 1 || row.Requests != int64(plans.ThrottleRule.Burst+1) {
t.Fatalf("row = %+v, want one plan-throttle refusal and every answer metered", row)
}
@@ -1068,7 +1068,7 @@ func TestFarBufferedReforwardIsBilledOnce(t *testing.T) {
if req, _, ok := s.row(); ok && req != 0 {
t.Fatalf("the far edge billed %d request(s), want none: the home billed the delivery", req)
}
- row := homeMeter.Drain()[laHost]
+ row := homeMeter.Drain().Rows[laHost]
if row.Requests != 1 || row.BytesOut != int64(rec.Body.Len()) || row.HopRequests != 1 {
t.Fatalf("home row = %+v, want one hop of %d delivered bytes", row, rec.Body.Len())
}
@@ -1201,7 +1201,7 @@ func TestFarHitsMeetTheGuard(t *testing.T) {
t.Fatalf("the warm entry for %s went", p)
}
}
- if row := s.meter.Drain()[laHost]; row.Requests != int64(len(rules)+3) {
+ if row := s.meter.Drain().Rows[laHost]; row.Requests != int64(len(rules)+3) {
t.Fatalf("row = %+v, want the %d watched hits and the 3 block pages metered", row, len(rules))
}
if len(rec.resp) != 0 {
diff --git a/internal/edge/asset_local_test.go b/internal/edge/asset_local_test.go
index 7b82aef7a..1be33b9f9 100644
--- a/internal/edge/asset_local_test.go
+++ b/internal/edge/asset_local_test.go
@@ -877,7 +877,7 @@ func TestHomeFillAcknowledgesAndSkipsTheMeter(t *testing.T) {
if hitExp != exp || hit.Body.String() != laBody || s.b.n.Load() != 1 {
t.Fatalf("home hit = %q expiry %d, backend saw %d", hit.Body.String(), hitExp, s.b.n.Load())
}
- if row, ok := m.Drain()[laHost]; ok && (row.Requests != 0 || row.BytesOut != 0) {
+ if row, ok := m.Drain().Rows[laHost]; ok && (row.Requests != 0 || row.BytesOut != 0) {
t.Fatalf("the home metered an acknowledged fill: %+v", row)
}
if n := s.lruLen(); n != 0 {
@@ -887,7 +887,7 @@ func TestHomeFillAcknowledgesAndSkipsTheMeter(t *testing.T) {
func wantMeteredHop(t *testing.T, m *UsageMeter) {
t.Helper()
- row := m.Drain()[laHost]
+ row := m.Drain().Rows[laHost]
if row.Requests != 1 || row.HopRequests != 1 {
t.Fatalf("row = %+v, want one metered hop", row)
}
@@ -933,7 +933,7 @@ func TestHomeFillUncacheableIsAcknowledgedWithZeroExpiry(t *testing.T) {
if st := s.store.Stats(); st.Entries != 0 {
t.Fatalf("stored %+v", st)
}
- if row, ok := m.Drain()[laHost]; ok && row.Requests != 0 {
+ if row, ok := m.Drain().Rows[laHost]; ok && row.Requests != 0 {
t.Fatalf("the home metered an acknowledged fill: %+v", row)
}
}
@@ -1014,7 +1014,7 @@ func TestAssetHitsPassThePlanThrottle(t *testing.T) {
if refused != 1 {
t.Fatalf("%d hits refused past the throttle's burst, want 1", refused)
}
- if row := m.Drain()[laHost]; row.PlanThrottled != 1 {
+ if row := m.Drain().Rows[laHost]; row.PlanThrottled != 1 {
t.Fatalf("row = %+v, want one plan-throttle refusal metered", row)
}
}
@@ -1100,7 +1100,7 @@ func TestHomeFillWaiterRefusedByTheRateLimitIsAcknowledged(t *testing.T) {
t.Fatalf("the refused waiter's 429 carries expiry %q ack %q, want an acknowledgement with expiry 0",
exp, rec.Header().Get(assetAckHeader))
}
- if row, ok := m.Drain()[laHost]; ok && row.Requests != 0 {
+ if row, ok := m.Drain().Rows[laHost]; ok && row.Requests != 0 {
t.Fatalf("the home billed an acknowledged fill: %+v", row)
}
}
@@ -1220,7 +1220,7 @@ func TestHomeFillMeetsThePlanThrottle(t *testing.T) {
if refused != 1 {
t.Fatalf("%d fill hops refused past the throttle's burst, want 1", refused)
}
- if row := m.Drain()[laHost]; row.PlanThrottled != 1 || row.Requests != 1 || row.HopRequests != 1 {
+ if row := m.Drain().Rows[laHost]; row.PlanThrottled != 1 || row.Requests != 1 || row.HopRequests != 1 {
t.Fatalf("row = %+v, want the one refusal metered as a hop with its plan-throttle count", row)
}
if n := s.b.n.Load(); n != 1 {
diff --git a/internal/edge/assetcatch.go b/internal/edge/assetcatch.go
index 1aa24858d..efd237e71 100644
--- a/internal/edge/assetcatch.go
+++ b/internal/edge/assetcatch.go
@@ -1082,9 +1082,14 @@ func (e *Edge) serveAssetFar(w http.ResponseWriter, r *http.Request, host string
// any answer written without reaching the home (a backhaul refusal,
// the no-key 503, a failed dial's 502). A request a hop delivered
// to the home is the home's to judge and record, as for any
- // backhauled request (ordinary-backhaul parity).
- if out != nil && out.guard != nil && out.guard.verdict != nil && (billed || !reached.Load()) {
- e.observeRecords(rt, false, r, cw, out)
+ // backhauled request (ordinary-backhaul parity). The protection count
+ // follows the same rule, matched or not: one for every request this
+ // edge answered itself, none for one the home has to count.
+ if out != nil && out.guard != nil && (billed || !reached.Load()) {
+ if out.guard.verdict != nil {
+ e.observeRecords(rt, false, r, cw, out)
+ }
+ e.observeGuardCount(rt, out)
}
}()
// The hard and probe checks, as ServeHTTP runs them for a request this
diff --git a/internal/edge/backhaul_e2e_test.go b/internal/edge/backhaul_e2e_test.go
index b91bf2625..2ea75ea2a 100644
--- a/internal/edge/backhaul_e2e_test.go
+++ b/internal/edge/backhaul_e2e_test.go
@@ -991,7 +991,7 @@ func TestHopServedRequestMetersOnceWithHopCounters(t *testing.T) {
t.Fatalf("marker = %q, want the home edge's app", seen.marker)
}
- rows := home.Drain()
+ rows := home.Drain().Rows
row, ok := rows[e2eHomedHost]
if !ok {
t.Fatalf("the home edge metered nothing for %s: %+v", e2eHomedHost, rows)
@@ -1012,7 +1012,7 @@ func TestHopServedRequestMetersOnceWithHopCounters(t *testing.T) {
// The sending edge is meterless for this host BY DESIGN: no route row, no
// identity, so anything it wrote would be unattributed — and a second
// Record for one exchange is the double count this arrangement refuses.
- if got, ok := sender.Drain()[e2eHomedHost]; ok {
+ if got, ok := sender.Drain().Rows[e2eHomedHost]; ok {
t.Fatalf("the sending edge metered %+v for a host it has no route for", got)
}
}
diff --git a/internal/edge/compress_test.go b/internal/edge/compress_test.go
index 24db2cfe8..1213f231c 100644
--- a/internal/edge/compress_test.go
+++ b/internal/edge/compress_test.go
@@ -487,7 +487,7 @@ func TestEdgeMetersCompressedBytes(t *testing.T) {
rec := httptest.NewRecorder()
e.ServeHTTP(rec, gzipReq("GET", "http://app.test/tokens.css"))
- row, ok := m.Drain()["app.test"]
+ row, ok := m.Drain().Rows["app.test"]
if !ok {
t.Fatal("no usage row for app.test")
}
diff --git a/internal/edge/edge.go b/internal/edge/edge.go
index a953c2455..3e0ed90b1 100644
--- a/internal/edge/edge.go
+++ b/internal/edge/edge.go
@@ -2039,6 +2039,11 @@ func (e *Edge) ServeHTTP(w http.ResponseWriter, r *http.Request) {
}
e.observeAnalytics(up.route, r, ob, bytes)
e.observeRecords(up.route, up.viaTunnel, r, ob, out)
+ // Protection counts follow the records: one per request the
+ // 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)
}()
}
diff --git a/internal/edge/edge_test.go b/internal/edge/edge_test.go
index 4e61314ec..905802114 100644
--- a/internal/edge/edge_test.go
+++ b/internal/edge/edge_test.go
@@ -2254,7 +2254,7 @@ func TestServeHTTPMetersRequestsAndBytesExcludingStatus(t *testing.T) {
t.Fatalf("status route: %d, want 200", code)
}
- rows := meter.Drain()
+ rows := meter.Drain().Rows
row := rows["metered.example.com"]
wantBytes := int64(2 * len(body))
if row.Requests != 2 || row.BytesOut != wantBytes {
diff --git a/internal/edge/forwardha_test.go b/internal/edge/forwardha_test.go
index b12ae1356..d5fd78a32 100644
--- a/internal/edge/forwardha_test.go
+++ b/internal/edge/forwardha_test.go
@@ -399,7 +399,7 @@ func (x *fwScene) take(t *testing.T, host string) (annie, betty fwBox) {
})
box := func(m *UsageMeter, obs *memAnalytics, rec *lockedRecorder) fwBox {
var b fwBox
- b.use = m.Drain()[host]
+ b.use = m.Drain().Rows[host]
all := obs.snap()
b.obs = all[x.obs[obs]:]
x.obs[obs] = len(all)
diff --git a/internal/edge/gate_test.go b/internal/edge/gate_test.go
index dbeb39b26..cf6c8d2fe 100644
--- a/internal/edge/gate_test.go
+++ b/internal/edge/gate_test.go
@@ -378,7 +378,7 @@ func TestGatedRefusalIsMeteredToTheRoute(t *testing.T) {
// 2 KiB, so the headers reach the client before the handler returns and
// the meter's deferred Record has run.
io.ReadAll(resp.Body)
- row, ok := m.Drain()["gated.example.com"]
+ row, ok := m.Drain().Rows["gated.example.com"]
if !ok {
t.Fatal("no usage row for the gated route — the refusal was not metered")
}
diff --git a/internal/edge/guard.go b/internal/edge/guard.go
index dd2ee7f73..410a40753 100644
--- a/internal/edge/guard.go
+++ b/internal/edge/guard.go
@@ -8,6 +8,7 @@ import (
"strings"
"github.com/carlosframework/platform/internal/edgeguard"
+ "github.com/carlosframework/platform/internal/registry"
"github.com/carlosframework/platform/internal/reqrec"
)
@@ -95,6 +96,26 @@ func (e *Edge) newGuardState() *guardState {
return &guardState{mode: e.guard, mint: mint}
}
+// observeGuardCount counts one request the guard ran for into the usage
+// meter, with its verdict's rule and block, or with no rule when nothing
+// matched. It is called once per guard state, from the same place, and under
+// 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) {
+ m := e.usageMeter.Load()
+ if m == nil || out == nil || out.guard == nil {
+ return
+ }
+ var rule *edgeguard.Rule
+ var blocked bool
+ if v := out.guard.verdict; v != nil {
+ rule, blocked = v.rule, v.block
+ }
+ m.RecordGuard(rt, rule, blocked)
+}
+
// guardDecide notes hit as r's verdict and, when the mode blocks the rule,
// answers r with the block page and reports true: the caller must then stop
// serving. It does nothing when the guard is not running for r, or when a
diff --git a/internal/edge/guard_usage_test.go b/internal/edge/guard_usage_test.go
new file mode 100644
index 000000000..a5a37f7db
--- /dev/null
+++ b/internal/edge/guard_usage_test.go
@@ -0,0 +1,339 @@
+package edge
+
+import (
+ "io"
+ "maps"
+ "net/http"
+ "net/http/httptest"
+ "testing"
+
+ "github.com/carlosframework/platform/internal/edgeguard"
+ "github.com/carlosframework/platform/internal/registry"
+ "github.com/carlosframework/platform/internal/reqrec"
+ "github.com/carlosframework/platform/internal/tunnelclient"
+ "github.com/carlosframework/platform/internal/usage"
+)
+
+// Protection counts in the usage meter (console Protection tab, plan Task
+// 2), through real edges serving the embedded catalogue. Each scenario below
+// is one request; it returns what the box's recorder filed for it and what
+// its meter counted, so every test can check that the counts follow the
+// records, and TestGuardUsageCountsFollowRecords checks it for all of them.
+
+const guHost = "shop.example.com"
+
+// guardUsage is one request's outcome on the box that answered it: the
+// Match records filed for it (recorded false when records were off) and the
+// meter's flush.
+type guardUsage struct {
+ w *httptest.ResponseRecorder
+ recorded bool
+ matches []reqrec.Match
+ flush usage.EdgeFlush
+}
+
+// guardUsageEdge is a real Edge, built by New so CARLOS_EDGE_PROTECT is read
+// as on a box, over one instance route for guHost owned by bdk/shop, with a
+// usage meter and, when records is set, a recorder.
+func guardUsageEdge(t *testing.T, protect string, records bool) (*Edge, *UsageMeter, *memRecorder) {
+ t.Helper()
+ t.Setenv("CARLOS_EDGE_PROTECT", protect)
+ backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.WriteHeader(http.StatusNotFound)
+ io.WriteString(w, "the app's own 404")
+ }))
+ t.Cleanup(backend.Close)
+ reg := openReg(t)
+ if err := reg.Upsert(registry.Route{Host: guHost, Kind: "instance", Addr: backend.Listener.Addr().String(),
+ Status: "ready", Account: "bdk", App: "shop"}); err != nil {
+ t.Fatal(err)
+ }
+ e, err := New(reg, &fakeActivator{})
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(e.probers.Stop)
+ m := NewUsageMeter()
+ e.EnableUsage(m)
+ var rec *memRecorder
+ if records {
+ rec = &memRecorder{}
+ e.EnableRequestRecords(rec)
+ }
+ return e, m, rec
+}
+
+// localGuardUsage serves GET path on guardUsageEdge, delivered by a tunnel
+// when tunnel is set.
+func localGuardUsage(t *testing.T, protect string, records, tunnel bool, path string) guardUsage {
+ t.Helper()
+ e, m, rec := guardUsageEdge(t, protect, records)
+ var h http.Handler = e
+ if tunnel {
+ h = tunnelclient.Mark(e)
+ }
+ w := httptest.NewRecorder()
+ h.ServeHTTP(w, httptest.NewRequest("GET", "http://"+guHost+path, nil))
+ g := guardUsage{w: w, flush: m.Drain(), recorded: rec != nil}
+ if rec != nil {
+ g.matches = rec.match
+ }
+ return g
+}
+
+// farBlockGuardUsage is a probe on a declared asset path of a host homed on
+// another box, answered by this far edge's block page.
+func farBlockGuardUsage(t *testing.T) guardUsage {
+ t.Helper()
+ t.Setenv("CARLOS_EDGE_PROTECT", "block")
+ s := newFarScene(t, assetOK(laBody))
+ rec := &memRecorder{}
+ s.e.EnableRequestRecords(rec)
+ w := s.get(t, "/assets/.env")
+ if w.Code != http.StatusNotFound || w.Header().Get("X-Carlos-Ref") == "" {
+ t.Fatalf("far probe = %d ref %q, want the block page", w.Code, w.Header().Get("X-Carlos-Ref"))
+ }
+ if n := s.rec.get().n; n != 0 {
+ t.Fatalf("the home saw %d request(s), want none", n)
+ }
+ return guardUsage{w: w, recorded: true, matches: rec.match, flush: s.meter.Drain()}
+}
+
+// farHitGuardUsage is a plain request for an asset the far edge already
+// stored, answered from its store.
+func farHitGuardUsage(t *testing.T) guardUsage {
+ t.Helper()
+ t.Setenv("CARLOS_EDGE_PROTECT", "")
+ s := newFarScene(t, assetOK(laBody))
+ wantCache(t, s.get(t, "/assets/app.js"), "miss")
+ s.meter.Drain()
+ rec := &memRecorder{}
+ s.e.EnableRequestRecords(rec)
+ w := s.get(t, "/assets/app.js")
+ wantCache(t, w, "hit")
+ return guardUsage{w: w, recorded: true, matches: rec.match, flush: s.meter.Drain()}
+}
+
+// farReachedHomeGuardUsage is a watched probe on a cold asset path: the far
+// edge fills it from a real home edge, so the request reaches the home,
+// which checks, records and counts it. far is the far edge's outcome, home
+// the home's.
+func farReachedHomeGuardUsage(t *testing.T) (far, home guardUsage) {
+ t.Helper()
+ t.Setenv("CARLOS_EDGE_PROTECT", "")
+ homeMeter, homeRec := NewUsageMeter(), &memRecorder{}
+ s := newFarEdge(t, func(key []byte, m *homeMap) http.Handler {
+ h := newLAScene(t, assetOK(laBody))
+ hm := newHomeMap(m.s, "betty")
+ refreshHomeMap(t, hm)
+ h.e.homes.Store(hm)
+ h.e.EnableUsage(homeMeter)
+ h.e.EnableRequestRecords(homeRec)
+ return h.e
+ })
+ farRec := &memRecorder{}
+ s.e.EnableRequestRecords(farRec)
+ w := s.get(t, "/assets/app.php")
+ wantCache(t, w, "miss")
+ far = guardUsage{w: w, recorded: true, matches: farRec.match, flush: s.meter.Drain()}
+ home = guardUsage{recorded: true, matches: homeRec.match, flush: homeMeter.Drain()}
+ return far, home
+}
+
+// oneDelta is the flush's only guard delta, which must be the one for key.
+func oneDelta(t *testing.T, f usage.EdgeFlush, key string) usage.GuardDelta {
+ t.Helper()
+ if len(f.Guard) != 1 {
+ t.Fatalf("guard = %+v, want one delta", f.Guard)
+ }
+ d, ok := f.Guard[key]
+ if !ok {
+ t.Fatalf("guard = %+v, want the delta under %q", f.Guard, key)
+ }
+ return d
+}
+
+// followsRecords checks one request's counts against its records: the Match
+// records filed for it, burst rules aside, equal its watches and blocks.
+func followsRecords(t *testing.T, name string, g guardUsage) {
+ t.Helper()
+ if !g.recorded {
+ return
+ }
+ var filed, counted int64
+ for _, m := range g.matches {
+ if catalogueRule(t, m.RuleID).Mode != edgeguard.ModeBurst {
+ filed++
+ }
+ }
+ for _, d := range g.flush.Guard {
+ counted += d.Watch + d.Block
+ }
+ if filed != counted {
+ t.Fatalf("%s: %d match record(s) beyond burst rules, but %d counted caught (%+v)", name, filed, counted, g.flush.Guard)
+ }
+}
+
+var guKey = usage.GuardKey(guHost, "bdk", "shop")
+
+func TestGuardUsageCountsAProbe(t *testing.T) {
+ g := localGuardUsage(t, "", true, false, "/wp-login.php")
+ followsRecords(t, "probe", g)
+ d := oneDelta(t, g.flush, guKey)
+ if d.Checked != 1 || d.Watch != 1 || d.Block != 0 || !maps.Equal(d.Groups, map[string]int64{"probe/wordpress": 1}) {
+ t.Fatalf("delta = %+v, want one watched probe/wordpress", d)
+ }
+ if row := g.flush.Rows[guHost]; row.Requests != 1 {
+ t.Fatalf("row = %+v, want the request metered once as traffic", row)
+ }
+}
+
+func TestGuardUsagePlainRequestCountsChecked(t *testing.T) {
+ g := localGuardUsage(t, "", true, false, "/")
+ followsRecords(t, "plain", g)
+ d := oneDelta(t, g.flush, guKey)
+ if d.Checked != 1 || d.Watch != 0 || d.Block != 0 || len(d.Groups) != 0 {
+ t.Fatalf("delta = %+v, want checked only", d)
+ }
+}
+
+func TestGuardUsageBurstRuleNotCaught(t *testing.T) {
+ g := localGuardUsage(t, "", true, false, "/admin")
+ if len(g.matches) != 1 || g.matches[0].RuleID != "probe.admin.admin" {
+ t.Fatalf("matches %+v, want the burst rule recorded", g.matches)
+ }
+ followsRecords(t, "burst", g)
+ d := oneDelta(t, g.flush, guKey)
+ if d.Checked != 1 || d.Watch != 0 || d.Block != 0 || len(d.Groups) != 0 {
+ t.Fatalf("delta = %+v, want checked and not caught", d)
+ }
+}
+
+// The hub that forwarded a tunnel delivery checked it, recorded it and
+// counted it; this box does none of the three.
+func TestGuardUsageTunnelDeliveredNotCounted(t *testing.T) {
+ g := localGuardUsage(t, "", true, true, "/wp-login.php")
+ followsRecords(t, "tunnel", g)
+ if len(g.flush.Guard) != 0 {
+ t.Fatalf("guard = %+v, want nothing counted for a tunnel delivery", g.flush.Guard)
+ }
+}
+
+// Counting does not depend on records: a box with no recorder still counts
+// what its guard caught.
+func TestGuardUsageCountsWithRecordsOff(t *testing.T) {
+ g := localGuardUsage(t, "", false, false, "/wp-login.php")
+ d := oneDelta(t, g.flush, guKey)
+ if d.Checked != 1 || d.Watch != 1 || !maps.Equal(d.Groups, map[string]int64{"probe/wordpress": 1}) {
+ t.Fatalf("delta = %+v, want the probe counted with records off", d)
+ }
+}
+
+func TestGuardUsageModeOff(t *testing.T) {
+ g := localGuardUsage(t, "off", true, false, "/wp-login.php")
+ followsRecords(t, "off", g)
+ if len(g.flush.Guard) != 0 {
+ t.Fatalf("guard = %+v, want nothing counted with protection off", g.flush.Guard)
+ }
+ if row := g.flush.Rows[guHost]; row.Requests != 1 {
+ t.Fatalf("row = %+v, want the request still metered as traffic", row)
+ }
+}
+
+// R2 finding 1: the far edge's own block page is a check and a catch on the
+// far edge, under the owner the home published.
+func TestGuardUsageFarAssetBlockCounted(t *testing.T) {
+ g := farBlockGuardUsage(t)
+ followsRecords(t, "far block", g)
+ d := oneDelta(t, g.flush, usage.GuardKey(laHost, "abc", "shop"))
+ if d.Checked != 1 || d.Block != 1 || d.Watch != 0 || !maps.Equal(d.Groups, map[string]int64{"hard/secrets": 1}) {
+ t.Fatalf("delta = %+v, want one block in hard/secrets", d)
+ }
+}
+
+func TestGuardUsageFarAssetHitCounted(t *testing.T) {
+ g := farHitGuardUsage(t)
+ followsRecords(t, "far hit", g)
+ d := oneDelta(t, g.flush, usage.GuardKey(laHost, "abc", "shop"))
+ if d.Checked != 1 || d.Watch != 0 || d.Block != 0 {
+ t.Fatalf("delta = %+v, want checked only", d)
+ }
+}
+
+// A fill that reached the home is the home's to check, record and count,
+// as for any backhauled request; the far edge counts nothing for it.
+func TestGuardUsageFarAssetReachedHomeNotCountedHere(t *testing.T) {
+ far, home := farReachedHomeGuardUsage(t)
+ followsRecords(t, "far edge, fill reached the home", far)
+ followsRecords(t, "home, fill", home)
+ if len(far.flush.Guard) != 0 {
+ t.Fatalf("far guard = %+v, want nothing counted on the far edge", far.flush.Guard)
+ }
+ d := oneDelta(t, home.flush, usage.GuardKey(laHost, "abc", "shop"))
+ if d.Checked != 1 || d.Watch != 1 || !maps.Equal(d.Groups, map[string]int64{"probe/php": 1}) {
+ t.Fatalf("home delta = %+v, want the home to count the probe once", d)
+ }
+}
+
+// Review Focus 1: a probe backhauled over a verified hop is checked by one
+// box, the home, so the two edges together count it once.
+func TestGuardUsageHopCountsOnce(t *testing.T) {
+ t.Setenv("CARLOS_EDGE_PROTECT", "")
+ s := newBackhaulScene(t)
+ s.converge(t)
+ home, sender := NewUsageMeter(), NewUsageMeter()
+ s.a.edge.EnableUsage(home)
+ s.b.edge.EnableUsage(sender)
+
+ resp, _ := s.get(t, s.b, "https://"+e2eHomedHost+"/wp-login.php", nil, true)
+ if resp.StatusCode != http.StatusOK {
+ t.Fatalf("status = %d, want the home app's 200", resp.StatusCode)
+ }
+ var checked, caught int64
+ for _, f := range []usage.EdgeFlush{home.Drain(), sender.Drain()} {
+ for _, d := range f.Guard {
+ checked += d.Checked
+ caught += d.Watch + d.Block
+ }
+ }
+ if checked != 1 || caught != 1 {
+ t.Fatalf("checked %d, caught %d across both edges, want 1 and 1", checked, caught)
+ }
+}
+
+// Counts follow records: for every request above that runs with a
+// recorder, the Match records filed for it, burst rules aside, equal its
+// watches and blocks, on the box that answered it.
+func TestGuardUsageCountsFollowRecords(t *testing.T) {
+ type scenario func(t *testing.T) []guardUsage
+ local := func(protect string, tunnel bool, path string) scenario {
+ return func(t *testing.T) []guardUsage {
+ return []guardUsage{localGuardUsage(t, protect, true, tunnel, path)}
+ }
+ }
+ for _, tc := range []struct {
+ name string
+ run scenario
+ }{
+ {"probe", local("", false, "/wp-login.php")},
+ {"plain", local("", false, "/")},
+ {"burst", local("", false, "/admin")},
+ {"burst in block mode", local("block", false, "/admin")},
+ {"block", local("block", false, "/.git/config")},
+ {"watch mode", local("watch", false, "/.env")},
+ {"tunnel", local("", true, "/wp-login.php")},
+ {"off", local("off", false, "/wp-login.php")},
+ {"far block", func(t *testing.T) []guardUsage { return []guardUsage{farBlockGuardUsage(t)} }},
+ {"far hit", func(t *testing.T) []guardUsage { return []guardUsage{farHitGuardUsage(t)} }},
+ {"far fill reached the home", func(t *testing.T) []guardUsage {
+ far, home := farReachedHomeGuardUsage(t)
+ return []guardUsage{far, home}
+ }},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ for _, g := range tc.run(t) {
+ followsRecords(t, tc.name, g)
+ }
+ })
+ }
+}
diff --git a/internal/edge/path_test.go b/internal/edge/path_test.go
index b6c48e3ba..5a8cb7ff8 100644
--- a/internal/edge/path_test.go
+++ b/internal/edge/path_test.go
@@ -384,7 +384,7 @@ func TestPathRoutedRequestMetersAgainstTheTarget(t *testing.T) {
t.Fatalf("flipped request = %d %q, want 200 %q", code, got, body)
}
- rows := meter.Drain()
+ rows := meter.Drain().Rows
row, ok := rows["go.tito.io"]
if !ok {
t.Fatalf("usage rows = %+v, want the TARGET route metered", rows)
diff --git a/internal/edge/planthrottle_test.go b/internal/edge/planthrottle_test.go
index 245416df8..46ec100dc 100644
--- a/internal/edge/planthrottle_test.go
+++ b/internal/edge/planthrottle_test.go
@@ -258,7 +258,7 @@ func TestPlanThrottleRefusalCounted(t *testing.T) {
for i := 0; i <= plans.ThrottleRule.Burst; i++ {
s.get(t, "203.0.113.1", ptHost, "/")
}
- row := m.Drain()[ptHost]
+ row := m.Drain().Rows[ptHost]
if row.PlanThrottled != 1 || row.RateShed != 0 || row.RateCeiling != 0 {
t.Fatalf("row = %+v, want one plan-throttle refusal and no #358 counts", row)
}
diff --git a/internal/edge/ratelimit_test.go b/internal/edge/ratelimit_test.go
index c31e83bfa..1cc774234 100644
--- a/internal/edge/ratelimit_test.go
+++ b/internal/edge/ratelimit_test.go
@@ -592,7 +592,7 @@ func TestRateObserveCountsButServes(t *testing.T) {
if n := hits.Load(); n != 2 {
t.Fatalf("upstream hits = %d, want 2", n)
}
- row := m.Drain()[rlHost]
+ row := m.Drain().Rows[rlHost]
if row.Requests != 2 || row.RateCeiling != 1 || row.RateShed != 0 {
t.Fatalf("row = %+v, want 2 requests and rate_ceiling 1", row)
}
@@ -622,7 +622,7 @@ func TestRateOffDoesNothing(t *testing.T) {
for i, ch := range chans {
wantOK(t, waitResult(t, ch, fmt.Sprint(i)), fmt.Sprintf("request %d", i))
}
- if row := m.Drain()[rlHost]; row.RateShed != 0 || row.RateCeiling != 0 {
+ if row := m.Drain().Rows[rlHost]; row.RateShed != 0 || row.RateCeiling != 0 {
t.Fatalf("row = %+v, want no rate counts in off mode", row)
}
}
@@ -829,10 +829,10 @@ func TestRateTunnelSides(t *testing.T) {
wantOK(t, viaHub(), "first request via the hub")
wantOK(t, viaHub(), "second request via the hub")
want429(t, viaHub(), "1", "third request: the hub's burst of 2 is spent")
- if row := hubMeter.Drain()[rlHost]; row.RateCeiling != 1 {
+ if row := hubMeter.Drain().Rows[rlHost]; row.RateCeiling != 1 {
t.Fatalf("hub row = %+v, want rate_ceiling 1", row)
}
- if row := remoteMeter.Drain()[rlHost]; row.RateCeiling != 0 || row.RateShed != 0 || row.Requests != 2 {
+ if row := remoteMeter.Drain().Rows[rlHost]; row.RateCeiling != 0 || row.RateShed != 0 || row.Requests != 2 {
t.Fatalf("fleet row = %+v, want 2 requests and no rate counts", row)
}
diff --git a/internal/edge/regional_e2e_test.go b/internal/edge/regional_e2e_test.go
index ff17e67ee..1c5bfcb00 100644
--- a/internal/edge/regional_e2e_test.go
+++ b/internal/edge/regional_e2e_test.go
@@ -531,7 +531,7 @@ func TestRegionalNameNeverLeavesItsRegion(t *testing.T) {
s.a.edge.EnableUsage(meter)
before = now()
resp, _ = rgDo(t, s.a, http.MethodPost, "https://"+rgApex+gate.LoginPath, nil, url.Values{"next": {"/api/x"}, "password": {"x"}})
- rows := meter.Drain()
+ rows := meter.Drain().Rows
if resp.StatusCode != http.StatusNotFound {
t.Errorf("login POST = %d, want the ungated stray 404 of the regional entry", resp.StatusCode)
}
diff --git a/internal/edge/usagemeter.go b/internal/edge/usagemeter.go
index 869fa25e7..932b8106c 100644
--- a/internal/edge/usagemeter.go
+++ b/internal/edge/usagemeter.go
@@ -7,6 +7,7 @@ import (
"net/http"
"sync"
+ "github.com/carlosframework/platform/internal/edgeguard"
"github.com/carlosframework/platform/internal/ratelimit"
"github.com/carlosframework/platform/internal/registry"
"github.com/carlosframework/platform/internal/release"
@@ -17,14 +18,24 @@ import (
// Record sits on the serving path: one mutex'd map update per request —
// no allocation, no I/O. Drain swaps the map out for the usage flush loop
// (internal/host), so a slow bucket write never blocks serving.
+//
+// It also keeps the edge-protection counts (RecordGuard) per host-owner,
+// apart from the traffic rows: a row restarts its refusal counters when its
+// owner changes, while each owner keeps its own protection counts.
type UsageMeter struct {
- mu sync.Mutex
- m map[string]usage.EdgeRow
+ mu sync.Mutex
+ m map[string]usage.EdgeRow
+ guard map[guardOwner]usage.GuardDelta
}
+// guardOwner keys a protection delta between flushes. A struct rather than
+// usage.GuardKey's string, so counting a check on the serving path builds no
+// string; Drain makes the keys once per flush.
+type guardOwner struct{ host, account, app string }
+
// NewUsageMeter returns an empty meter.
func NewUsageMeter() *UsageMeter {
- return &UsageMeter{m: map[string]usage.EdgeRow{}}
+ return &UsageMeter{m: map[string]usage.EdgeRow{}, guard: map[guardOwner]usage.GuardDelta{}}
}
// Record adds one served exchange for rt. hopped says the request arrived
@@ -79,13 +90,50 @@ func (u *UsageMeter) RecordPlanThrottled(rt registry.Route) {
u.mu.Unlock()
}
-// Drain returns the accumulated rows and resets the meter.
-func (u *UsageMeter) Drain() map[string]usage.EdgeRow {
+// RecordGuard counts one request the hard and probe checks looked at on
+// this box, against rt's host and current owner. rule is the rule that
+// matched it, nil when none did, and blocked says the block page answered
+// it. A match on a burst rule is checked but not caught: an admin page is a
+// normal thing to visit once, so counting it would show a site's own
+// visitors as bad traffic. The host's traffic row is not touched; the
+// request itself is counted by Record like any other answer.
+func (u *UsageMeter) RecordGuard(rt registry.Route, rule *edgeguard.Rule, blocked bool) {
+ k := guardOwner{host: rt.Host, account: release.RouteAccount(rt), app: rt.App}
u.mu.Lock()
- out := u.m
+ d := u.guard[k]
+ d.Host, d.Account, d.App = k.host, k.account, k.app
+ d.Checked++
+ if rule != nil && rule.Mode != edgeguard.ModeBurst {
+ if blocked {
+ d.Block++
+ } else {
+ d.Watch++
+ }
+ if d.Groups == nil {
+ d.Groups = map[string]int64{}
+ }
+ usage.AddGroup(d.Groups, rule.Tier.String()+"/"+rule.Group, 1)
+ }
+ u.guard[k] = d
+ u.mu.Unlock()
+}
+
+// Drain returns the accumulated rows and protection counts and resets the
+// meter.
+func (u *UsageMeter) Drain() usage.EdgeFlush {
+ u.mu.Lock()
+ rows, guard := u.m, u.guard
u.m = map[string]usage.EdgeRow{}
+ u.guard = map[guardOwner]usage.GuardDelta{}
u.mu.Unlock()
- return out
+ f := usage.EdgeFlush{Rows: rows}
+ if len(guard) > 0 {
+ f.Guard = make(map[string]usage.GuardDelta, len(guard))
+ for k, d := range guard {
+ f.Guard[usage.GuardKey(k.host, k.account, k.app)] = d
+ }
+ }
+ return f
}
// countingWriter counts response body bytes and OBSERVES the final status
diff --git a/internal/edge/usagemeter_test.go b/internal/edge/usagemeter_test.go
index 5c3f78a99..879f2905f 100644
--- a/internal/edge/usagemeter_test.go
+++ b/internal/edge/usagemeter_test.go
@@ -1,11 +1,13 @@
package edge
import (
+ "maps"
"net/http"
"net/http/httptest"
"sync"
"testing"
+ "github.com/carlosframework/platform/internal/edgeguard"
"github.com/carlosframework/platform/internal/ratelimit"
"github.com/carlosframework/platform/internal/registry"
"github.com/carlosframework/platform/internal/release"
@@ -19,7 +21,7 @@ func TestUsageMeterRecordAndDrain(t *testing.T) {
m.Record(rt, 1, 50, false)
m.Record(registry.Route{Host: "b.example.com", App: "site"}, 1, 10, false) // Account "" -> release.OpsAccount
- got := m.Drain()
+ got := m.Drain().Rows
a := got["a.example.com"]
if a.Requests != 2 || a.BytesOut != 150 || a.Account != "bab" || a.App != "hello" {
t.Fatalf("a row = %+v", a)
@@ -27,7 +29,7 @@ func TestUsageMeterRecordAndDrain(t *testing.T) {
if got["b.example.com"].Account != release.OpsAccount {
t.Fatalf("b row = %+v", got["b.example.com"])
}
- if again := m.Drain(); len(again) != 0 {
+ if again := m.Drain(); len(again.Rows) != 0 {
t.Fatalf("drain did not reset: %+v", again)
}
}
@@ -43,7 +45,7 @@ func TestRecordHopAnnotatesSubset(t *testing.T) {
m.Record(rt, 1, 100, true)
m.Record(rt, 1, 50, false)
- row := m.Drain()["a.example.com"]
+ row := m.Drain().Rows["a.example.com"]
if row.Requests != 2 || row.BytesOut != 150 {
t.Fatalf("row = %+v, want both exchanges counted once in the totals", row)
}
@@ -72,7 +74,7 @@ func TestUsageMeterConcurrent(t *testing.T) {
}()
}
wg.Wait()
- row := m.Drain()["a.example.com"]
+ row := m.Drain().Rows["a.example.com"]
if row.Requests != 5000 || row.BytesOut != 50000 {
t.Fatalf("row = %+v", row)
}
@@ -131,9 +133,83 @@ func TestUsageMeterOwnerChangeResetsRateCounters(t *testing.T) {
m.RecordRateLimited(after, ratelimit.Shed)
m.Record(after, 1, 10, false)
- got := m.Drain()["shop.example.com"]
+ got := m.Drain().Rows["shop.example.com"]
want := usage.EdgeRow{Account: "bab", App: "shop", Requests: 3, BytesOut: 30, RateShed: 1}
if got != want {
t.Fatalf("row = %+v, want %+v", got, want)
}
}
+
+// catalogueRule is the rule with id from the embedded catalogue, so a test
+// counts what the edge would really be handed.
+func catalogueRule(t *testing.T, id string) *edgeguard.Rule {
+ t.Helper()
+ for _, r := range edgeguard.Rules() {
+ if r.ID == id {
+ return &r
+ }
+ }
+ t.Fatalf("no rule %s in the catalogue", id)
+ return nil
+}
+
+// Every check counts as checked; a watch and a block count as caught, each
+// under its tier and group. A burst rule's match is an admin page a visitor
+// may well ask for, so it is checked and never caught. None of it touches
+// the host's traffic row.
+func TestRecordGuardCounts(t *testing.T) {
+ m := NewUsageMeter()
+ rt := registry.Route{Host: "shop.example.com", App: "shop", Account: "bdk"}
+ m.RecordGuard(rt, catalogueRule(t, "probe.wordpress.wp-login"), false)
+ m.RecordGuard(rt, catalogueRule(t, "hard.secrets.env"), true)
+ m.RecordGuard(rt, nil, false)
+ m.RecordGuard(rt, catalogueRule(t, "probe.admin.admin"), false)
+
+ f := m.Drain()
+ if len(f.Rows) != 0 {
+ t.Fatalf("rows = %+v, want none: a check is not a served request", f.Rows)
+ }
+ if len(f.Guard) != 1 {
+ t.Fatalf("guard = %+v, want one delta", f.Guard)
+ }
+ d, ok := f.Guard[usage.GuardKey("shop.example.com", "bdk", "shop")]
+ if !ok {
+ t.Fatalf("guard = %+v, want the delta under the host-owner key", f.Guard)
+ }
+ if d.Host != "shop.example.com" || d.Account != "bdk" || d.App != "shop" || d.Checked != 4 || d.Watch != 1 || d.Block != 1 {
+ t.Fatalf("delta = %+v, want checked 4, watch 1, block 1 for bdk/shop", d)
+ }
+ if want := map[string]int64{"probe/wordpress": 1, "hard/secrets": 1}; !maps.Equal(d.Groups, want) {
+ t.Fatalf("groups = %v, want %v", d.Groups, want)
+ }
+ if again := m.Drain(); len(again.Guard) != 0 || len(again.Rows) != 0 {
+ t.Fatalf("drain did not reset: %+v", again)
+ }
+}
+
+// Review Focus 3: a host that changes hands between two matches in one
+// flush keeps each owner's counts apart, so neither owner is shown the
+// other's bad traffic. Host and app stay; only the account changes.
+func TestRecordGuardOwnerChangeWithinDrain(t *testing.T) {
+ m := NewUsageMeter()
+ before := registry.Route{Host: "shop.example.com", App: "shop", Account: "bab"}
+ after := registry.Route{Host: "shop.example.com", App: "shop", Account: "bdk"}
+ if release.RouteAccount(before) == release.RouteAccount(after) {
+ t.Fatal("the two routes resolve to one account; the test needs two owners")
+ }
+ rule := catalogueRule(t, "probe.wordpress.wp-login")
+ m.RecordGuard(before, rule, false)
+ m.Record(after, 1, 10, false)
+ m.RecordGuard(after, rule, false)
+
+ f := m.Drain()
+ if len(f.Guard) != 2 {
+ t.Fatalf("guard = %+v, want one delta per owner", f.Guard)
+ }
+ for _, acct := range []string{"bab", "bdk"} {
+ d := f.Guard[usage.GuardKey("shop.example.com", acct, "shop")]
+ if d.Account != acct || d.Checked != 1 || d.Watch != 1 || d.Block != 0 || !maps.Equal(d.Groups, map[string]int64{"probe/wordpress": 1}) {
+ t.Fatalf("%s delta = %+v, want one watch in probe/wordpress", acct, d)
+ }
+ }
+}
diff --git a/internal/host/applessroute_test.go b/internal/host/applessroute_test.go
index 20c3ab63d..840851c4b 100644
--- a/internal/host/applessroute_test.go
+++ b/internal/host/applessroute_test.go
@@ -187,7 +187,7 @@ func TestLogshipAndAnalyticsDropAppLessRecords(t *testing.T) {
am := analytics.NewMeter(t.TempDir(), "box1", func() time.Time { return now })
am.Observe(analytics.Obs{Acct: "bab", App: "", Host: "proof.example.com", Method: "GET", Status: 502, Path: "/", When: now})
am.Observe(analytics.Obs{Acct: "bab", App: "web", Host: "web.example.com", Method: "GET", Status: 200, ContentType: "text/html", Path: "/", UA: "Mozilla/5.0 Safari", ClientIP: "1.2.3.4", Bytes: 10, When: now})
- none := func() map[string]usage.EdgeRow { return nil }
+ none := func() usage.EdgeFlush { return usage.EdgeFlush{} }
for i := 0; i < 2; i++ { // a second flush proves the bad delta was not re-queued
if err := usageFlush(ctx, s, s, "box1", none, am, now); err != nil {
t.Fatal(err)
diff --git a/internal/host/usage_loop.go b/internal/host/usage_loop.go
index a25f671bb..9eb447431 100644
--- a/internal/host/usage_loop.go
+++ b/internal/host/usage_loop.go
@@ -13,17 +13,17 @@ import (
"github.com/carlosframework/platform/internal/usage"
)
-// usageFlush drains the edge meter and CAS-merges the deltas into the box's
-// usage/edge day object, then (when am is non-nil) drains the analytics
-// meter's deltas into their app-day objects (spec §3.3: the same tick, a
-// second CAS write per app). Usage writes go to s (rebased under
+// usageFlush drains the edge meter (traffic rows and protection counts) and
+// CAS-merges the deltas into the box's usage/edge day object, then (when am
+// is non-nil) drains the analytics meter's deltas into their app-day objects
+// (spec §3.3: the same tick, a second CAS write per app). Usage writes go to s (rebased under
// CARLOS_STATUS_PREFIX on a fleet box); analytics writes go to raw — a day
// file lives under apps/<sqid>/<app>/analytics/, the app's own data, and
// must NOT be rebased (same reasoning as log shipping — logship.go:54-61).
// A failed analytics batch is re-queued for the next tick; a failed usage
// write is returned but does not block the analytics flush.
-func usageFlush(ctx context.Context, s, raw release.Store, box string, drain func() map[string]usage.EdgeRow, am *analytics.Meter, now time.Time) error {
- err := usage.UpsertEdgeDay(ctx, s, box, now, usage.EdgeFlush{Rows: drain()})
+func usageFlush(ctx context.Context, s, raw release.Store, box string, drain func() usage.EdgeFlush, am *analytics.Meter, now time.Time) error {
+ err := usage.UpsertEdgeDay(ctx, s, box, now, drain())
if am == nil {
return err
}
@@ -56,7 +56,7 @@ func usageFlush(ctx context.Context, s, raw release.Store, box string, drain fun
// never fatal (the drained window is lost, the next one is not; modelling
// grade tolerates the gap). am is the analytics meter (nil disables the
// analytics half of the flush); its deltas are folded in on the same tick.
-func usageLoop(drain func() map[string]usage.EdgeRow, am *analytics.Meter) {
+func usageLoop(drain func() usage.EdgeFlush, am *analytics.Meter) {
defer func() {
if r := recover(); r != nil {
log.Printf("agent: usage loop panic, edge metering stopped for this process: %v", r)
diff --git a/internal/host/usage_loop_test.go b/internal/host/usage_loop_test.go
index d8b5fabb3..0b9145326 100644
--- a/internal/host/usage_loop_test.go
+++ b/internal/host/usage_loop_test.go
@@ -18,10 +18,10 @@ func TestUsageFlushWritesAndReflushesMerge(t *testing.T) {
rows := map[string]usage.EdgeRow{
"a.example.com": {Account: "bab", App: "hello", Requests: 3, BytesOut: 300},
}
- if err := usageFlush(ctx, s, s, "box1", func() map[string]usage.EdgeRow { return rows }, nil, at); err != nil {
+ if err := usageFlush(ctx, s, s, "box1", func() usage.EdgeFlush { return usage.EdgeFlush{Rows: rows} }, nil, at); err != nil {
t.Fatal(err)
}
- if err := usageFlush(ctx, s, s, "box1", func() map[string]usage.EdgeRow { return rows }, nil, at.Add(5*time.Minute)); err != nil {
+ if err := usageFlush(ctx, s, s, "box1", func() usage.EdgeFlush { return usage.EdgeFlush{Rows: rows} }, nil, at.Add(5*time.Minute)); err != nil {
t.Fatal(err)
}
raw, _, err := s.Get(ctx, usage.EdgeDayKey("box1", "2026-08-11"))
@@ -37,9 +37,39 @@ func TestUsageFlushWritesAndReflushesMerge(t *testing.T) {
}
}
+// The drain's protection counts reach the day object on the same write as
+// the traffic rows, even on a box whose only news is a probe count.
+func TestUsageFlushCarriesGuardCounts(t *testing.T) {
+ s := release.NewDirStore(t.TempDir())
+ ctx := context.Background()
+ at := time.Date(2026, 10, 30, 9, 0, 0, 0, time.UTC)
+ key := usage.GuardKey("shop.example.com", "bdk", "shop")
+ drain := func() usage.EdgeFlush {
+ return usage.EdgeFlush{Guard: map[string]usage.GuardDelta{key: {
+ Host: "shop.example.com", Account: "bdk", App: "shop", Checked: 3, Watch: 1,
+ Groups: map[string]int64{"probe/wordpress": 1},
+ }}}
+ }
+ if err := usageFlush(ctx, s, s, "box1", drain, nil, at); err != nil {
+ t.Fatal(err)
+ }
+ raw, _, err := s.Get(ctx, usage.EdgeDayKey("box1", "2026-10-30"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ var day usage.EdgeDay
+ if err := json.Unmarshal(raw, &day); err != nil {
+ t.Fatal(err)
+ }
+ g := day.Guard[key]
+ if h := g.Hours["09"]; h.Checked != 3 || h.Watch != 1 || g.Groups["probe/wordpress"] != 1 || g.Account != "bdk" {
+ t.Fatalf("guard tally = %+v, want checked 3, watch 1 in probe/wordpress for bdk", g)
+ }
+}
+
func TestUsageFlushEmptyDrainWritesNothing(t *testing.T) {
s := release.NewDirStore(t.TempDir())
- err := usageFlush(context.Background(), s, s, "box1", func() map[string]usage.EdgeRow { return nil }, nil, time.Now().UTC())
+ err := usageFlush(context.Background(), s, s, "box1", func() usage.EdgeFlush { return usage.EdgeFlush{} }, nil, time.Now().UTC())
if err != nil {
t.Fatal(err)
}
@@ -57,7 +87,7 @@ func TestUsageFlushAlsoFlushesAnalytics(t *testing.T) {
now := time.Date(2026, 9, 7, 9, 30, 0, 0, time.UTC)
am := analytics.NewMeter(t.TempDir(), "box1", func() time.Time { return now })
am.Observe(analytics.Obs{Acct: "bab", App: "web", Host: "h", Method: "GET", Status: 200, ContentType: "text/html", Path: "/", UA: "Mozilla/5.0 Safari", ClientIP: "1.2.3.4", Bytes: 10, When: now})
- if err := usageFlush(ctx, s, s, "box1", func() map[string]usage.EdgeRow { return nil }, am, now); err != nil {
+ if err := usageFlush(ctx, s, s, "box1", func() usage.EdgeFlush { return usage.EdgeFlush{} }, am, now); err != nil {
t.Fatal(err)
}
sum, err := analytics.ReadRange(ctx, s, "bab", "web", now, now)
@@ -66,8 +96,8 @@ func TestUsageFlushAlsoFlushesAnalytics(t *testing.T) {
}
// A failed analytics flush re-queues; the next flush lands it.
am.Observe(analytics.Obs{Acct: "bab", App: "web", Host: "h", Method: "GET", Status: 200, ContentType: "text/html", Path: "/", UA: "Mozilla/5.0 Safari", ClientIP: "1.2.3.4", Bytes: 10, When: now})
- _ = usageFlush(ctx, s, failingStore{Store: s}, "box1", func() map[string]usage.EdgeRow { return nil }, am, now)
- if err := usageFlush(ctx, s, s, "box1", func() map[string]usage.EdgeRow { return nil }, am, now); err != nil {
+ _ = usageFlush(ctx, s, failingStore{Store: s}, "box1", func() usage.EdgeFlush { return usage.EdgeFlush{} }, am, now)
+ if err := usageFlush(ctx, s, s, "box1", func() usage.EdgeFlush { return usage.EdgeFlush{} }, am, now); err != nil {
t.Fatal(err)
}
if sum, _ := analytics.ReadRange(ctx, s, "bab", "web", now, now); sum.PV != 2 {