carlos / platform Public

usage: protection counters, group tally and modes on the edge day

EdgeDay gains an additive Guard map: per host-owner hourly checked, watch
and block counts plus a capped group tally (AddGroup, 32 names, overflow to
"other"). EdgeFlush carries rows and guard deltas through AddFlush (which
replaces AddDeltas) and UpsertEdgeDay; an empty flush still writes nothing.
The owner is part of the guard key, so a host that changes hands mid-hour
keeps both owners' counts apart. Callers updated; usageLoop wraps its
existing drain as EdgeFlush{Rows: drain()} until the meter fills the guard.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev a2df86f671226a8c5d39bd08a7ed67c6a7454605 parent 4b51636
6 files changed, +301 −39
  • internal/console/apiinstances_ratelimit.go +1 −1
  • internal/console/apiinstances_ratelimit_test.go +1 −1
  • internal/host/usage_loop.go +1 −1
  • internal/usage/edge.go +127 −13
  • internal/usage/edge_ratelimit_test.go +10 −10
  • internal/usage/edge_test.go +161 −13
diff --git a/internal/console/apiinstances_ratelimit.go b/internal/console/apiinstances_ratelimit.go
index e9780a9a6..732abc55b 100644
--- a/internal/console/apiinstances_ratelimit.go
+++ b/internal/console/apiinstances_ratelimit.go
@@ -175,7 +175,7 @@ func (s *Server) handleAPIInstanceRateLimitGet(w http.ResponseWriter, r *http.Re
// A row counts only under this instance's own account and app. A host can
// change hands, and the last owner's traffic is not the new owner's to see.
// A row is labelled with its latest owner, and both accumulation stages (the
-// edge's UsageMeter and usage.EdgeDay.AddDeltas) reset its two refusal
+// edge's UsageMeter and usage.EdgeDay.AddFlush) reset its two refusal
// counters when that label changes (usage.EdgeRow.SetOwner), so a host
// re-owned inside one hour shows the new owner only its own refusals.
//
diff --git a/internal/console/apiinstances_ratelimit_test.go b/internal/console/apiinstances_ratelimit_test.go
index 4a31652c6..dd020cad3 100644
--- a/internal/console/apiinstances_ratelimit_test.go
+++ b/internal/console/apiinstances_ratelimit_test.go
@@ -201,7 +201,7 @@ type rlRateLimitView struct {
func rlUpsert(t *testing.T, fx *consoleFixture, box string, at time.Time, host string, row usage.EdgeRow) {
t.Helper()
- if err := usage.UpsertEdgeDay(context.Background(), fx.rel, box, at, map[string]usage.EdgeRow{host: row}); err != nil {
+ if err := usage.UpsertEdgeDay(context.Background(), fx.rel, box, at, usage.EdgeFlush{Rows: map[string]usage.EdgeRow{host: row}}); err != nil {
t.Fatal(err)
}
}
diff --git a/internal/host/usage_loop.go b/internal/host/usage_loop.go
index 77442159a..a25f671bb 100644
--- a/internal/host/usage_loop.go
+++ b/internal/host/usage_loop.go
@@ -23,7 +23,7 @@ import (
// 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, drain())
+ err := usage.UpsertEdgeDay(ctx, s, box, now, usage.EdgeFlush{Rows: drain()})
if am == nil {
return err
}
diff --git a/internal/usage/edge.go b/internal/usage/edge.go
index f37bc0987..7936172fc 100644
--- a/internal/usage/edge.go
+++ b/internal/usage/edge.go
@@ -6,6 +6,7 @@ import (
"errors"
"fmt"
"os"
+ "sort"
"time"
"github.com/carlosframework/platform/internal/release"
@@ -46,13 +47,82 @@ type EdgeRow struct {
PlanThrottled int64 `json:"plan_throttled,omitempty"`
}
+// GuardHour is one hour's edge-protection counts for one host and owner:
+// the requests the guard looked at, and those it only noted (watch) or
+// refused (block). Additive and omitempty, like the counters on EdgeRow.
+type GuardHour struct {
+ Checked int64 `json:"checked,omitempty"`
+ Watch int64 `json:"watch,omitempty"`
+ Block int64 `json:"block,omitempty"`
+}
+
+// GuardTally is one host-owner's protection counts for the day: hourly
+// counts, and a tally of which rule groups fired. It is keyed by GuardKey,
+// and the owner is part of the key on purpose: when a host changes hands
+// mid-hour both owners keep their own counts, where EdgeRow restarts its
+// counters (SetOwner) and so would otherwise show one account the other's
+// bad traffic.
+type GuardTally struct {
+ Host string `json:"host"`
+ Account string `json:"account"`
+ App string `json:"app"`
+ Hours map[string]GuardHour `json:"hours,omitempty"`
+ Groups map[string]int64 `json:"groups,omitempty"`
+}
+
+// GuardDelta is what the edge meter accumulates for one host-owner between
+// flushes, before AddFlush folds it into the day.
+type GuardDelta struct {
+ Host, Account, App string
+ Checked, Watch int64
+ Block int64
+ Groups map[string]int64
+}
+
+// GuardKey is the key of a host-owner's tally on the day, and of its delta
+// in a flush.
+func GuardKey(host, account, app string) string {
+ return host + "|" + account + "|" + app
+}
+
+// GuardGroupCap bounds how many group names one tally holds, "other"
+// included, so a scanner that invents a new rule group per request cannot
+// grow the day object without limit. GuardGroupOther takes the overflow.
+const (
+ GuardGroupCap = 32
+ GuardGroupOther = "other"
+)
+
+// AddGroup adds n to a group's count. A group already in the map always
+// sums; a new one is admitted only while fewer than GuardGroupCap-1 named
+// groups exist, so there is always room for "other", which takes the rest.
+func AddGroup(groups map[string]int64, group string, n int64) {
+ if _, ok := groups[group]; !ok && group != GuardGroupOther {
+ named := len(groups)
+ if _, ok := groups[GuardGroupOther]; ok {
+ named--
+ }
+ if named >= GuardGroupCap-1 {
+ group = GuardGroupOther
+ }
+ }
+ groups[group] += n
+}
+
+// EdgeFlush is what one meter drain hands to UpsertEdgeDay: the traffic
+// rows by host, and the protection counts by GuardKey.
+type EdgeFlush struct {
+ Rows map[string]EdgeRow
+ Guard map[string]GuardDelta
+}
+
// SetOwner labels the row with the route's current account and app. When
// that changes who owns a row, the rate-limit refusal counters start again
// from zero first: the owner reads them back (the console's rate-limit GET
// filters rows by account and app), and the previous owner's refusals are
// not the new owner's to see. Requests, BytesOut and the hop subset carry on
// summing under the new label as they always have (modelling grade, see
-// AddDeltas).
+// AddFlush).
func (r *EdgeRow) SetOwner(account, app string) {
if r.Account != account || r.App != app {
r.RateShed, r.RateCeiling, r.PlanThrottled = 0, 0, 0
@@ -70,6 +140,10 @@ type EdgeDay struct {
Box string `json:"box"`
Date string `json:"date"`
Hours map[string]map[string]EdgeRow `json:"hours"` // "09" -> host -> row
+ // Guard is the day's edge-protection tally per host-owner, keyed by
+ // GuardKey. Additive and omitempty: a day written before it parses with
+ // it nil, and a box that catches nothing writes the object it always did.
+ Guard map[string]GuardTally `json:"guard,omitempty"`
}
// EdgeDayKey is the bucket key for a box's day object.
@@ -83,12 +157,13 @@ func EdgeDaysPrefix(box string) string { return "usage/edge/" + box + "/days/" }
// EdgeBoxesPrefix is the ListDirs prefix that discovers metering boxes.
const EdgeBoxesPrefix = "usage/edge/"
-// AddDeltas folds drained per-host deltas into the day's hour bucket,
-// summing counters and refreshing the route identity (a host re-pointed to
-// a new app mid-hour lands on the later identity — modelling grade). The
-// rate-limit counters are the exception: a new identity starts them afresh
-// (SetOwner).
-func (d *EdgeDay) AddDeltas(hour string, deltas map[string]EdgeRow) {
+// AddFlush folds a drained flush into the day's hour bucket. Rows sum
+// counters and refresh the route identity (a host re-pointed to a new app
+// mid-hour lands on the later identity — modelling grade); the rate-limit
+// counters are the exception: a new identity starts them afresh (SetOwner).
+// Each guard delta sums into the tally for its host-owner, whose key carries
+// the owner, so a host that changes hands keeps both owners' counts apart.
+func (d *EdgeDay) AddFlush(hour string, f EdgeFlush) {
if d.Hours == nil {
d.Hours = map[string]map[string]EdgeRow{}
}
@@ -97,7 +172,8 @@ func (d *EdgeDay) AddDeltas(hour string, deltas map[string]EdgeRow) {
rows = map[string]EdgeRow{}
d.Hours[hour] = rows
}
- for host, delta := range deltas {
+ d.addGuard(hour, f.Guard)
+ for host, delta := range f.Rows {
row := rows[host]
row.SetOwner(delta.Account, delta.App)
row.Requests += delta.Requests
@@ -111,11 +187,49 @@ func (d *EdgeDay) AddDeltas(hour string, deltas map[string]EdgeRow) {
}
}
-// UpsertEdgeDay CAS-merges deltas into the box's day object for now's UTC
-// day and hour: read (etag), add, conditional put; on ErrCASConflict re-read
-// and retry, three attempts. Empty deltas write nothing.
-func UpsertEdgeDay(ctx context.Context, s release.Store, box string, now time.Time, deltas map[string]EdgeRow) error {
+// addGuard sums each delta into its host-owner's tally for the hour. Group
+// names go in sorted order, so when a tally is at its cap the same flush
+// always overflows the same names into "other".
+func (d *EdgeDay) addGuard(hour string, deltas map[string]GuardDelta) {
if len(deltas) == 0 {
+ return
+ }
+ if d.Guard == nil {
+ d.Guard = map[string]GuardTally{}
+ }
+ for key, delta := range deltas {
+ t := d.Guard[key]
+ t.Host, t.Account, t.App = delta.Host, delta.Account, delta.App
+ if t.Hours == nil {
+ t.Hours = map[string]GuardHour{}
+ }
+ h := t.Hours[hour]
+ h.Checked += delta.Checked
+ h.Watch += delta.Watch
+ h.Block += delta.Block
+ t.Hours[hour] = h
+ if len(delta.Groups) > 0 {
+ if t.Groups == nil {
+ t.Groups = map[string]int64{}
+ }
+ names := make([]string, 0, len(delta.Groups))
+ for g := range delta.Groups {
+ names = append(names, g)
+ }
+ sort.Strings(names)
+ for _, g := range names {
+ AddGroup(t.Groups, g, delta.Groups[g])
+ }
+ }
+ d.Guard[key] = t
+ }
+}
+
+// UpsertEdgeDay CAS-merges a flush into the box's day object for now's UTC
+// day and hour: read (etag), add, conditional put; on ErrCASConflict re-read
+// and retry, three attempts. An empty flush writes nothing.
+func UpsertEdgeDay(ctx context.Context, s release.Store, box string, now time.Time, f EdgeFlush) error {
+ if len(f.Rows) == 0 && len(f.Guard) == 0 {
return nil
}
date, hour := DayOf(now), HourLabel(now)
@@ -133,7 +247,7 @@ func UpsertEdgeDay(ctx context.Context, s release.Store, box string, now time.Ti
default:
return err
}
- day.AddDeltas(hour, deltas)
+ day.AddFlush(hour, f)
out, err := json.Marshal(day)
if err != nil {
return err
diff --git a/internal/usage/edge_ratelimit_test.go b/internal/usage/edge_ratelimit_test.go
index a262aeb89..424a6edd7 100644
--- a/internal/usage/edge_ratelimit_test.go
+++ b/internal/usage/edge_ratelimit_test.go
@@ -9,10 +9,10 @@ import (
// The rate-limit counters ride the edge row like the hop counters: summed
// across flushes, and absent from the JSON of a row that has none, so a box
// that limits nothing writes the same day object it wrote before.
-func TestAddDeltasSumsRateCounters(t *testing.T) {
+func TestAddFlushSumsRateCounters(t *testing.T) {
var d EdgeDay
- d.AddDeltas("09", map[string]EdgeRow{"shop.example.com": {Requests: 3, RateShed: 2, RateCeiling: 1}})
- d.AddDeltas("09", map[string]EdgeRow{"shop.example.com": {Requests: 1, RateShed: 1, RateCeiling: 4}})
+ d.AddFlush("09", EdgeFlush{Rows: map[string]EdgeRow{"shop.example.com": {Requests: 3, RateShed: 2, RateCeiling: 1}}})
+ d.AddFlush("09", EdgeFlush{Rows: map[string]EdgeRow{"shop.example.com": {Requests: 1, RateShed: 1, RateCeiling: 4}}})
row := d.Hours["09"]["shop.example.com"]
if row.Requests != 4 || row.RateShed != 3 || row.RateCeiling != 5 {
t.Fatalf("row = %+v, want requests 4, rate_shed 3, rate_ceiling 5", row)
@@ -38,28 +38,28 @@ func TestAddDeltasSumsRateCounters(t *testing.T) {
// under the new owner: they are readable by the row's owner, and the last
// owner's are not the new one's to see. Requests, bytes and the hop subset
// fold exactly as before, whoever owns the row.
-func TestAddDeltasOwnerChangeResetsRateCounters(t *testing.T) {
+func TestAddFlushOwnerChangeResetsRateCounters(t *testing.T) {
var d EdgeDay
- d.AddDeltas("09", map[string]EdgeRow{"shop.example.com": {
+ d.AddFlush("09", EdgeFlush{Rows: map[string]EdgeRow{"shop.example.com": {
Account: "bac", App: "shop", Requests: 10, BytesOut: 100, HopRequests: 4, HopBytesOut: 40, RateShed: 3, RateCeiling: 2,
- }})
- d.AddDeltas("09", map[string]EdgeRow{"shop.example.com": {
+ }}})
+ d.AddFlush("09", EdgeFlush{Rows: map[string]EdgeRow{"shop.example.com": {
Account: "bab", App: "shop", Requests: 1, BytesOut: 5, HopRequests: 1, HopBytesOut: 5, RateShed: 1,
- }})
+ }}})
want := EdgeRow{Account: "bab", App: "shop", Requests: 11, BytesOut: 105, HopRequests: 5, HopBytesOut: 45, RateShed: 1}
if got := d.Hours["09"]["shop.example.com"]; got != want {
t.Fatalf("after an account change = %+v, want %+v", got, want)
}
// Another app under the same account is another owner too.
- d.AddDeltas("09", map[string]EdgeRow{"shop.example.com": {Account: "bab", App: "other", Requests: 1, RateCeiling: 7}})
+ d.AddFlush("09", EdgeFlush{Rows: map[string]EdgeRow{"shop.example.com": {Account: "bab", App: "other", Requests: 1, RateCeiling: 7}}})
want = EdgeRow{Account: "bab", App: "other", Requests: 12, BytesOut: 105, HopRequests: 5, HopBytesOut: 45, RateCeiling: 7}
if got := d.Hours["09"]["shop.example.com"]; got != want {
t.Fatalf("after an app change = %+v, want %+v", got, want)
}
// The same owner keeps summing.
- d.AddDeltas("09", map[string]EdgeRow{"shop.example.com": {Account: "bab", App: "other", RateShed: 2, RateCeiling: 1}})
+ d.AddFlush("09", EdgeFlush{Rows: map[string]EdgeRow{"shop.example.com": {Account: "bab", App: "other", RateShed: 2, RateCeiling: 1}}})
if got := d.Hours["09"]["shop.example.com"]; got.RateShed != 2 || got.RateCeiling != 8 {
t.Fatalf("same owner = %+v, want rate_shed 2, rate_ceiling 8", got)
}
diff --git a/internal/usage/edge_test.go b/internal/usage/edge_test.go
index c3393a437..25bb16042 100644
--- a/internal/usage/edge_test.go
+++ b/internal/usage/edge_test.go
@@ -3,6 +3,8 @@ package usage
import (
"context"
"encoding/json"
+ "fmt"
+ "strings"
"testing"
"time"
@@ -33,11 +35,11 @@ func TestUpsertEdgeDayMergesAcrossFlushes(t *testing.T) {
d1 := map[string]EdgeRow{
"a.example.com": {Account: "bab", App: "hello", Requests: 10, BytesOut: 1000},
}
- if err := UpsertEdgeDay(ctx, s, "box1", at, d1); err != nil {
+ if err := UpsertEdgeDay(ctx, s, "box1", at, EdgeFlush{Rows: d1}); err != nil {
t.Fatal(err)
}
// Second flush, same hour: counts must ADD, not replace.
- if err := UpsertEdgeDay(ctx, s, "box1", at.Add(5*time.Minute), d1); err != nil {
+ if err := UpsertEdgeDay(ctx, s, "box1", at.Add(5*time.Minute), EdgeFlush{Rows: d1}); err != nil {
t.Fatal(err)
}
// Third flush, next hour and a second host.
@@ -45,7 +47,7 @@ func TestUpsertEdgeDayMergesAcrossFlushes(t *testing.T) {
"a.example.com": {Account: "bab", App: "hello", Requests: 1, BytesOut: 50},
"b.example.com": {Account: "ops", App: "site", Requests: 2, BytesOut: 20},
}
- if err := UpsertEdgeDay(ctx, s, "box1", at.Add(time.Hour), d2); err != nil {
+ if err := UpsertEdgeDay(ctx, s, "box1", at.Add(time.Hour), EdgeFlush{Rows: d2}); err != nil {
t.Fatal(err)
}
@@ -87,9 +89,9 @@ func TestEdgeDayHopFieldsAdditive(t *testing.T) {
t.Fatalf("row = %+v, want the old counters and zero hop counters", row)
}
// And it folds a hop-bearing delta on top without losing the old counts.
- day.AddDeltas("09", map[string]EdgeRow{
+ day.AddFlush("09", EdgeFlush{Rows: map[string]EdgeRow{
"a.example.com": {Account: "bab", App: "hello", Requests: 3, BytesOut: 300, HopRequests: 2, HopBytesOut: 250},
- })
+ }})
row = day.Hours["09"]["a.example.com"]
if row.Requests != 13 || row.BytesOut != 1300 || row.HopRequests != 2 || row.HopBytesOut != 250 {
t.Fatalf("folded row = %+v", row)
@@ -123,12 +125,12 @@ func TestEdgeDayHopFieldsAdditive(t *testing.T) {
// totals — they are counters in the same hour bucket, not a snapshot.
func TestEdgeDayHourFoldSumsHopFields(t *testing.T) {
var day EdgeDay
- delta := map[string]EdgeRow{
+ delta := EdgeFlush{Rows: map[string]EdgeRow{
"a.example.com": {Account: "bab", App: "hello", Requests: 4, BytesOut: 400, HopRequests: 1, HopBytesOut: 100},
- }
- day.AddDeltas("09", delta)
- day.AddDeltas("09", delta)
- day.AddDeltas("10", delta)
+ }}
+ day.AddFlush("09", delta)
+ day.AddFlush("09", delta)
+ day.AddFlush("10", delta)
if got := day.Hours["09"]["a.example.com"]; got.Requests != 8 || got.BytesOut != 800 ||
got.HopRequests != 2 || got.HopBytesOut != 200 {
@@ -147,7 +149,7 @@ func TestEdgeDayHourFoldSumsHopFields(t *testing.T) {
func TestUpsertEdgeDayEmptyDeltasIsNoop(t *testing.T) {
s := release.NewDirStore(t.TempDir())
- if err := UpsertEdgeDay(context.Background(), s, "box1", time.Now().UTC(), nil); err != nil {
+ if err := UpsertEdgeDay(context.Background(), s, "box1", time.Now().UTC(), EdgeFlush{}); err != nil {
t.Fatal(err)
}
if keys, _ := s.List(context.Background(), "usage/"); len(keys) != 0 {
@@ -157,8 +159,8 @@ func TestUpsertEdgeDayEmptyDeltasIsNoop(t *testing.T) {
func TestPlanThrottledSumsAndResetsWithOwner(t *testing.T) {
var d EdgeDay
- d.AddDeltas("10", map[string]EdgeRow{"h": {Account: "bdk", App: "web", PlanThrottled: 2}})
- d.AddDeltas("10", map[string]EdgeRow{"h": {Account: "bdk", App: "web", PlanThrottled: 3}})
+ d.AddFlush("10", EdgeFlush{Rows: map[string]EdgeRow{"h": {Account: "bdk", App: "web", PlanThrottled: 2}}})
+ d.AddFlush("10", EdgeFlush{Rows: map[string]EdgeRow{"h": {Account: "bdk", App: "web", PlanThrottled: 3}}})
if got := d.Hours["10"]["h"].PlanThrottled; got != 5 {
t.Fatalf("summed = %d, want 5", got)
}
@@ -168,3 +170,149 @@ func TestPlanThrottledSumsAndResetsWithOwner(t *testing.T) {
t.Fatal("a new owner sees the old owner's plan-throttle count")
}
}
+
+// putFailsStore fails the test on any Put: the empty-flush promise is that
+// nothing is written, not that an empty object is.
+type putFailsStore struct {
+ release.Store
+ t *testing.T
+}
+
+func (s putFailsStore) Put(_ context.Context, key string, _ []byte, _ string) (string, error) {
+ s.t.Fatalf("Put(%q) on an empty flush", key)
+ return "", nil
+}
+
+func TestUpsertEdgeDayEmptyFlushWritesNothing(t *testing.T) {
+ s := putFailsStore{Store: release.NewDirStore(t.TempDir()), t: t}
+ if err := UpsertEdgeDay(context.Background(), s, "box1", time.Now().UTC(), EdgeFlush{}); err != nil {
+ t.Fatal(err)
+ }
+ // Empty, not nil: maps that exist but hold nothing are still empty.
+ empty := EdgeFlush{Rows: map[string]EdgeRow{}, Guard: map[string]GuardDelta{}}
+ if err := UpsertEdgeDay(context.Background(), s, "box1", time.Now().UTC(), empty); err != nil {
+ t.Fatal(err)
+ }
+}
+
+func guardDelta(host, account, app string, checked, watch, block int64, groups map[string]int64) GuardDelta {
+ return GuardDelta{Host: host, Account: account, App: app, Checked: checked, Watch: watch, Block: block, Groups: groups}
+}
+
+func TestAddFlushSumsGuardHours(t *testing.T) {
+ const host = "shop.example.com"
+ key := GuardKey(host, "bab", "shop")
+ flush := func() EdgeFlush {
+ return EdgeFlush{Guard: map[string]GuardDelta{
+ key: guardDelta(host, "bab", "shop", 10, 2, 1, map[string]int64{"probe/wordpress": 2, "hard/secrets": 1}),
+ }}
+ }
+ var d EdgeDay
+ d.AddFlush("09", flush())
+ d.AddFlush("09", flush())
+
+ g, ok := d.Guard[key]
+ if !ok || len(d.Guard) != 1 {
+ t.Fatalf("Guard = %+v, want exactly %q", d.Guard, key)
+ }
+ if g.Host != host || g.Account != "bab" || g.App != "shop" {
+ t.Fatalf("tally identity = %+v", g)
+ }
+ if got, want := g.Hours["09"], (GuardHour{Checked: 20, Watch: 4, Block: 2}); got != want {
+ t.Fatalf("hour 09 = %+v, want %+v", got, want)
+ }
+ if g.Groups["probe/wordpress"] != 4 || g.Groups["hard/secrets"] != 2 || len(g.Groups) != 2 {
+ t.Fatalf("groups = %v, want probe/wordpress 4 and hard/secrets 2", g.Groups)
+ }
+}
+
+// A host that changes hands inside an hour keeps both owners' counts, each
+// under its own key. The row's own counters restart (SetOwner); the guard
+// tallies must not, or one account would read the other's bad traffic.
+func TestGuardOwnerChangeMidHourKeepsBoth(t *testing.T) {
+ const host = "shop.example.com"
+ oldKey, newKey := GuardKey(host, "bab", "shop"), GuardKey(host, "bdk", "shop")
+ var d EdgeDay
+ d.AddFlush("09", EdgeFlush{
+ Rows: map[string]EdgeRow{host: {Account: "bab", App: "shop", Requests: 5}},
+ Guard: map[string]GuardDelta{oldKey: guardDelta(host, "bab", "shop", 0, 3, 0, map[string]int64{"probe/wordpress": 3})},
+ })
+ d.AddFlush("09", EdgeFlush{
+ Rows: map[string]EdgeRow{host: {Account: "bdk", App: "shop", Requests: 4}},
+ Guard: map[string]GuardDelta{newKey: guardDelta(host, "bdk", "shop", 0, 2, 0, map[string]int64{"probe/wordpress": 2})},
+ })
+
+ if len(d.Guard) != 2 {
+ t.Fatalf("Guard keys = %v, want exactly the two owners", d.Guard)
+ }
+ sum := func(m map[string]int64) (n int64) {
+ for _, v := range m {
+ n += v
+ }
+ return n
+ }
+ for _, c := range []struct {
+ key string
+ watch int64
+ }{{oldKey, 3}, {newKey, 2}} {
+ g, ok := d.Guard[c.key]
+ if !ok {
+ t.Fatalf("missing %q in %v", c.key, d.Guard)
+ }
+ if g.Hours["09"].Watch != c.watch || sum(g.Groups) != c.watch {
+ t.Fatalf("%q = %+v, want watch %d and groups summing to it", c.key, g, c.watch)
+ }
+ }
+}
+
+func TestAddGroupCapsAtOther(t *testing.T) {
+ groups := map[string]int64{}
+ for i := 0; i < 40; i++ {
+ AddGroup(groups, fmt.Sprintf("g%02d", i), 1)
+ }
+ AddGroup(groups, "g00", 1)
+
+ if len(groups) != GuardGroupCap {
+ t.Fatalf("len = %d, want %d", len(groups), GuardGroupCap)
+ }
+ if named := len(groups) - 1; named != GuardGroupCap-1 {
+ t.Fatalf("named keys = %d, want %d", named, GuardGroupCap-1)
+ }
+ if groups[GuardGroupOther] != 9 {
+ t.Fatalf("other = %d, want 9", groups[GuardGroupOther])
+ }
+ if groups["g00"] != 2 {
+ t.Fatalf("g00 = %d, want 2", groups["g00"])
+ }
+ var total int64
+ for _, v := range groups {
+ total += v
+ }
+ if total != 41 {
+ t.Fatalf("total = %d, want 41", total)
+ }
+}
+
+// Day objects already in the bucket predate the guard fields.
+func TestEdgeDayOldShapeParses(t *testing.T) {
+ const old = `{"v":1,"box":"box1","date":"2026-08-24","hours":{"09":{"a.example.com":` +
+ `{"account":"bab","app":"hello","requests":10,"bytes_out":1000}}}}`
+ var day EdgeDay
+ if err := json.Unmarshal([]byte(old), &day); err != nil {
+ t.Fatal(err)
+ }
+ if day.Guard != nil {
+ t.Fatalf("Guard = %v, want nil", day.Guard)
+ }
+ if row := day.Hours["09"]["a.example.com"]; row.Requests != 10 || row.BytesOut != 1000 {
+ t.Fatalf("row = %+v", row)
+ }
+ // And a day with no guard data writes none: the object stays as it was.
+ out, err := json.Marshal(day)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if strings.Contains(string(out), "guard") {
+ t.Fatalf("json = %s, want no guard key", out)
+ }
+}