carlos / platform Public

edge: count bytes per instance by the hour each exchange ends

UsageMeter keeps a second map keyed by the UTC hour Record runs in and
the route row's account, app and instance host, for instance routes
only, under the same lock as the per-host rows. Record gains the
instance argument; ServeHTTP and the demo path pass the route host, the
far asset catch passes it only when the block's primary is the request
host. Drain returns Instances (nil when empty). SetClock for tests,
DisableInstances for CARLOS_INSTANCE_USAGE=off.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev d13762193a126c6d8ef52478e7ae13d0205555dc parent e3c40ee
7 files changed, +443 −20
  • internal/edge/asset_far_test.go +67 −0
  • internal/edge/assetcatch.go +11 −1
  • internal/edge/demo_traffic.go +1 −1
  • internal/edge/edge.go +1 −1
  • internal/edge/usagemeter.go +64 −8
  • internal/edge/usagemeter_instances_test.go +290 −0
  • internal/edge/usagemeter_test.go +9 −9
diff --git a/internal/edge/asset_far_test.go b/internal/edge/asset_far_test.go
index de1af1235..00ba7b206 100644
--- a/internal/edge/asset_far_test.go
+++ b/internal/edge/asset_far_test.go
@@ -5,6 +5,7 @@ import (
"context"
"fmt"
"io"
+ "maps"
"net"
"net/http"
"net/http/httptest"
@@ -22,6 +23,7 @@ import (
"github.com/carlosframework/platform/internal/ratelimit"
"github.com/carlosframework/platform/internal/registry"
"github.com/carlosframework/platform/internal/reqrec"
+ "github.com/carlosframework/platform/internal/usage"
)
// The far catch and fill (edge asset cache design §5.1 to §5.5, §8; plan 3
@@ -1375,3 +1377,68 @@ func TestFarLocalAnswersAreRecorded(t *testing.T) {
}
})
}
+
+// ---- per-instance attribution (instance usage T11) -------------------------
+
+// publishBlock lands betty's edges file homing host alone, owned by abc/shop,
+// with primary as its asset block's primary ("" leaves the field out, as an
+// older publisher does).
+func (s *farScene) publishBlock(t *testing.T, at time.Time, host, primary string) {
+ t.Helper()
+ putJSON(t, s.m.s, "control/edges/betty.json", fmt.Sprintf(
+ `{"v":1,"box":"betty","eip":%q,"hosts":{%q:{"role":"home","account":"abc","app":"shop",`+
+ `"assets":{"paths":["/assets/"],"gen":%q,"at":%d,"primary":%q}}}}`,
+ s.eip, host, laGen, at.Unix(), primary))
+ refreshHomeMap(t, s.m)
+}
+
+// farInstanceCase serves a miss then a hit for host through the far catch
+// and returns the drain.
+func farInstanceCase(t *testing.T, host, primary string) usage.EdgeFlush {
+ t.Helper()
+ s := newFarScene(t, assetOK(laBody))
+ s.publishBlock(t, time.Now(), host, primary)
+ s.meter.SetClock(func() time.Time { return time.Unix(1_796_000_000, 0) })
+ for _, want := range []string{"miss", "hit"} {
+ rec := s.serve(httptest.NewRequest(http.MethodGet, "http://"+host+"/assets/app.js", nil))
+ wantNoAck(t, rec)
+ wantCache(t, rec, want)
+ if rec.Code != 200 || rec.Body.String() != laBody {
+ t.Fatalf("%s = %d %q", want, rec.Code, rec.Body.String())
+ }
+ }
+ f := s.meter.Drain()
+ if row := f.Rows[host]; row.Requests != 2 || row.BytesOut != int64(2*len(laBody)) || row.Account != "abc" || row.App != "shop" {
+ t.Fatalf("old row %s = %+v, want 2 requests of %d bytes for abc/shop", host, row, len(laBody))
+ }
+ return f
+}
+
+// wantFarInstance: the drain holds one bucket, abc/shop's, under instance.
+func wantFarInstance(t *testing.T, f usage.EdgeFlush, instance string) {
+ t.Helper()
+ want := map[usage.InstanceBucket]usage.InstanceCount{
+ {Hour: 1_796_000_000 / 3600, Account: "abc", App: "shop", Instance: instance}: {Requests: 2, BytesOut: int64(2 * len(laBody))},
+ }
+ if !maps.Equal(f.Instances, want) {
+ t.Fatalf("instances = %+v, want %+v", f.Instances, want)
+ }
+}
+
+// A far delivery of the primary's own name is the primary's.
+func TestFarAssetInstanceIsThePrimary(t *testing.T) {
+ wantFarInstance(t, farInstanceCase(t, laHost, laHost), laHost)
+}
+
+// A far delivery under an alias keeps the request host in the old rows and is
+// unattributable in the new family: the block's primary may be an hour old.
+func TestFarAssetAliasIsUnattributed(t *testing.T) {
+ // Under example.com: the fake home's test certificate covers only that.
+ const alias = "www.example.com"
+ wantFarInstance(t, farInstanceCase(t, alias, laHost), "")
+}
+
+// A block from an older publisher names no primary: unattributable.
+func TestFarAssetNoPrimaryIsUnattributed(t *testing.T) {
+ wantFarInstance(t, farInstanceCase(t, laHost, ""), "")
+}
diff --git a/internal/edge/assetcatch.go b/internal/edge/assetcatch.go
index 40728a773..1b356fcb7 100644
--- a/internal/edge/assetcatch.go
+++ b/internal/edge/assetcatch.go
@@ -1157,6 +1157,16 @@ func (e *Edge) serveAssetFar(w http.ResponseWriter, r *http.Request, host string
}
st := e.assets.Load()
rt := registry.Route{Host: host, Account: a.Account, App: a.App, Kind: "instance"}
+ // The instance the per-instance usage family counts this delivery
+ // under (instance usage spec §4): the block's primary only when it is
+ // the request host itself. An alias, or a block from an older publisher
+ // with no primary, is the app's but no one instance's: the block is up
+ // to an hour old, and a domain moved within that hour must not be
+ // charged to the instance it left. The old rows still key by host.
+ var instance string
+ if a.Primary == host {
+ instance = host
+ }
var n int64
cw := &countingWriter{ResponseWriter: w, n: &n}
var billed, acked, reforwarded bool
@@ -1174,7 +1184,7 @@ func (e *Edge) serveAssetFar(w http.ResponseWriter, r *http.Request, host string
defer func() {
if billed || (acked && !reforwarded) {
if m := e.usageMeter.Load(); m != nil {
- m.Record(rt, 1, n, false)
+ m.Record(rt, instance, 1, n, false)
}
}
// Every answer this edge wrote itself is recorded here when a rule
diff --git a/internal/edge/demo_traffic.go b/internal/edge/demo_traffic.go
index c0151996f..6d9e14e9c 100644
--- a/internal/edge/demo_traffic.go
+++ b/internal/edge/demo_traffic.go
@@ -215,7 +215,7 @@ func (e *Edge) serveDemoTraffic(dst http.ResponseWriter, r *http.Request, up ups
return
}
if m := e.usageMeter.Load(); m != nil {
- m.Record(up.route, 1, delivered, hopped)
+ m.Record(up.route, up.route.Host, 1, delivered, hopped)
}
if ob.status >= 500 && !out.answered {
e.emitEdgeError(up.route, up.viaTunnel, r, ob.status, out.cause)
diff --git a/internal/edge/edge.go b/internal/edge/edge.go
index ec59c6987..7bb926a7b 100644
--- a/internal/edge/edge.go
+++ b/internal/edge/edge.go
@@ -2769,7 +2769,7 @@ func (e *Edge) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// 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)
+ m.Record(up.route, up.route.Host, 1, bytes, hopped)
}
if ob.status >= 500 && !out.answered {
e.emitEdgeError(up.route, up.viaTunnel, r, ob.status, out.cause)
diff --git a/internal/edge/usagemeter.go b/internal/edge/usagemeter.go
index 496c4be27..202d8cf23 100644
--- a/internal/edge/usagemeter.go
+++ b/internal/edge/usagemeter.go
@@ -6,6 +6,7 @@ import (
"net"
"net/http"
"sync"
+ "time"
"github.com/carlosframework/platform/internal/edgeguard"
"github.com/carlosframework/platform/internal/ratelimit"
@@ -15,17 +16,28 @@ import (
)
// UsageMeter accumulates per-route request/byte counters between flushes.
-// 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
+// Record sits on the serving path: one lock and at most two map updates per
+// request, no I/O. Drain swaps the maps 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.
+//
+// And it keeps the per-instance family (instance usage spec §4, §5): an
+// instance route's exchanges by the UTC hour Record ran in, and by the
+// route row's account, app and instance host at that moment. Record runs
+// after the last byte, so an exchange counts whole in the hour it
+// completed.
type UsageMeter struct {
mu sync.Mutex
m map[string]usage.EdgeRow
guard map[guardOwner]usage.GuardDelta
+ inst map[usage.InstanceBucket]usage.InstanceCount
+ // now is the clock the hour is read from; time.Now unless SetClock.
+ now func() time.Time
+ // instOff: CARLOS_INSTANCE_USAGE=off. The old family counts as ever.
+ instOff bool
}
// guardOwner keys a protection delta between flushes. A struct rather than
@@ -35,7 +47,29 @@ type guardOwner struct{ host, account, app string }
// NewUsageMeter returns an empty meter.
func NewUsageMeter() *UsageMeter {
- return &UsageMeter{m: map[string]usage.EdgeRow{}, guard: map[guardOwner]usage.GuardDelta{}}
+ return &UsageMeter{
+ m: map[string]usage.EdgeRow{},
+ guard: map[guardOwner]usage.GuardDelta{},
+ inst: map[usage.InstanceBucket]usage.InstanceCount{},
+ now: time.Now,
+ }
+}
+
+// SetClock replaces the clock the per-instance hour is read from. For tests.
+func (u *UsageMeter) SetClock(now func() time.Time) {
+ u.mu.Lock()
+ u.now = now
+ u.mu.Unlock()
+}
+
+// DisableInstances stops the per-instance family (CARLOS_INSTANCE_USAGE=off):
+// Record then counts only the old per-host rows, and Drain returns no
+// Instances.
+func (u *UsageMeter) DisableInstances() {
+ u.mu.Lock()
+ u.instOff = true
+ u.inst = map[usage.InstanceBucket]usage.InstanceCount{}
+ u.mu.Unlock()
}
// Record adds one served exchange for rt. hopped says the request arrived
@@ -45,10 +79,17 @@ func NewUsageMeter() *UsageMeter {
// usage.EdgeRow). One method rather than a separate RecordHop: two methods
// for one exchange invite calling both, which is exactly the double count
// this arrangement exists to make impossible.
-func (u *UsageMeter) Record(rt registry.Route, requests, bytes int64, hopped bool) {
+//
+// instance is the instance host the per-instance family counts the
+// exchange under, read only when rt is an instance route: rt.Host where the
+// route row served is the instance's own, "" where the exchange is this
+// app's but not attributable to one instance (a far alias delivery). It
+// never changes the old per-host row, which keys by rt.Host as ever.
+func (u *UsageMeter) Record(rt registry.Route, instance string, requests, bytes int64, hopped bool) {
+ account := release.RouteAccount(rt)
u.mu.Lock()
row := u.m[rt.Host]
- row.SetOwner(release.RouteAccount(rt), rt.App)
+ row.SetOwner(account, rt.App)
row.Requests += requests
row.BytesOut += bytes
if hopped {
@@ -56,6 +97,17 @@ func (u *UsageMeter) Record(rt registry.Route, requests, bytes int64, hopped boo
row.HopBytesOut += bytes
}
u.m[rt.Host] = row
+ if rt.Kind == "instance" && !u.instOff {
+ k := usage.InstanceBucket{Hour: u.now().Unix() / 3600, Account: account, App: rt.App, Instance: instance}
+ c := u.inst[k]
+ c.Requests += requests
+ c.BytesOut += bytes
+ if hopped {
+ c.HopRequests += requests
+ c.HopBytesOut += bytes
+ }
+ u.inst[k] = c
+ }
u.mu.Unlock()
}
@@ -118,15 +170,19 @@ func (u *UsageMeter) RecordGuard(rt registry.Route, rule *edgeguard.Rule, blocke
u.mu.Unlock()
}
-// Drain returns the accumulated rows and protection counts and resets the
-// meter.
+// Drain returns the accumulated rows, protection counts and per-instance
+// buckets (nil when there are none) and resets the meter.
func (u *UsageMeter) Drain() usage.EdgeFlush {
u.mu.Lock()
- rows, guard := u.m, u.guard
+ rows, guard, inst := u.m, u.guard, u.inst
u.m = map[string]usage.EdgeRow{}
u.guard = map[guardOwner]usage.GuardDelta{}
+ u.inst = map[usage.InstanceBucket]usage.InstanceCount{}
u.mu.Unlock()
f := usage.EdgeFlush{Rows: rows}
+ if len(inst) > 0 {
+ f.Instances = inst
+ }
if len(guard) > 0 {
f.Guard = make(map[string]usage.GuardDelta, len(guard))
for k, d := range guard {
diff --git a/internal/edge/usagemeter_instances_test.go b/internal/edge/usagemeter_instances_test.go
new file mode 100644
index 000000000..b39e948d0
--- /dev/null
+++ b/internal/edge/usagemeter_instances_test.go
@@ -0,0 +1,290 @@
+package edge
+
+import (
+ "io"
+ "maps"
+ "net/http"
+ "net/http/httptest"
+ "sync"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/registry"
+ "github.com/carlosframework/platform/internal/usage"
+)
+
+// fakeMeterClock is a settable clock for the meter, safe to move while
+// another goroutine records.
+type fakeMeterClock struct{ ns atomic.Int64 }
+
+func newFakeMeterClock(at time.Time) *fakeMeterClock {
+ c := &fakeMeterClock{}
+ c.set(at)
+ return c
+}
+
+func (c *fakeMeterClock) set(at time.Time) { c.ns.Store(at.UnixNano()) }
+func (c *fakeMeterClock) now() time.Time { return time.Unix(0, c.ns.Load()) }
+
+func mustTime(t *testing.T, s string) time.Time {
+ t.Helper()
+ at, err := time.Parse(time.RFC3339, s)
+ if err != nil {
+ t.Fatalf("parse %s: %v", s, err)
+ }
+ return at
+}
+
+func instanceRoute(host, account, app string) registry.Route {
+ return registry.Route{Host: host, Kind: "instance", Account: account, App: app}
+}
+
+// An exchange counts whole in the UTC hour Record runs in, which is when it
+// completed: two exchanges either side of midnight land in two buckets an
+// hour apart, the first on the earlier date.
+func TestRecordPlacesHourAtCompletion(t *testing.T) {
+ m := NewUsageMeter()
+ clk := newFakeMeterClock(mustTime(t, "2026-11-30T23:58:30Z"))
+ m.SetClock(clk.now)
+ rt := instanceRoute("shop.bab.oncarlos.com", "bab", "shop")
+ m.Record(rt, rt.Host, 1, 100, false)
+ clk.set(mustTime(t, "2026-12-01T00:00:10Z"))
+ m.Record(rt, rt.Host, 1, 40, false)
+
+ got := m.Drain().Instances
+ if len(got) != 2 {
+ t.Fatalf("instances = %+v, want two buckets", got)
+ }
+ before := mustTime(t, "2026-11-30T23:00:00Z").Unix() / 3600
+ first := usage.InstanceBucket{Hour: before, Account: "bab", App: "shop", Instance: rt.Host}
+ second := usage.InstanceBucket{Hour: before + 1, Account: "bab", App: "shop", Instance: rt.Host}
+ if c := got[first]; c != (usage.InstanceCount{Requests: 1, BytesOut: 100}) {
+ t.Fatalf("first bucket = %+v, want 1 request 100 bytes; all %+v", c, got)
+ }
+ if c := got[second]; c != (usage.InstanceCount{Requests: 1, BytesOut: 40}) {
+ t.Fatalf("second bucket = %+v, want 1 request 40 bytes; all %+v", c, got)
+ }
+ if d := usage.HourDate(first.Hour); d != "2026-11-30" {
+ t.Fatalf("first bucket's date = %s, want 2026-11-30", d)
+ }
+ if d := usage.HourDate(second.Hour); d != "2026-12-01" {
+ t.Fatalf("second bucket's date = %s, want 2026-12-01", d)
+ }
+}
+
+// A static row is counted in the old family as today and never in the
+// per-instance one.
+func TestRecordStaticNotInInstances(t *testing.T) {
+ m := NewUsageMeter()
+ rt := registry.Route{Host: "docs.bab.oncarlos.com", Kind: "static", Account: "bab", App: "docs"}
+ m.Record(rt, rt.Host, 1, 70, false)
+
+ f := m.Drain()
+ if row := f.Rows[rt.Host]; row.Requests != 1 || row.BytesOut != 70 {
+ t.Fatalf("old row = %+v, want 1 request 70 bytes", row)
+ }
+ if f.Instances != nil {
+ t.Fatalf("instances = %+v, want nil for a static route", f.Instances)
+ }
+}
+
+// A host that changes hands keeps each owner's bytes in a bucket of its own.
+func TestRecordOwnerChangeKeepsTwoBuckets(t *testing.T) {
+ m := NewUsageMeter()
+ m.SetClock(newFakeMeterClock(mustTime(t, "2026-11-30T10:15:00Z")).now)
+ const host = "shop.example.oncarlos.com"
+ m.Record(instanceRoute(host, "bab", "shop"), host, 1, 10, false)
+ m.Record(instanceRoute(host, "bdk", "shop"), host, 2, 30, false)
+
+ got := m.Drain().Instances
+ hour := mustTime(t, "2026-11-30T10:00:00Z").Unix() / 3600
+ want := map[usage.InstanceBucket]usage.InstanceCount{
+ {Hour: hour, Account: "bab", App: "shop", Instance: host}: {Requests: 1, BytesOut: 10},
+ {Hour: hour, Account: "bdk", App: "shop", Instance: host}: {Requests: 2, BytesOut: 30},
+ }
+ if !maps.Equal(got, want) {
+ t.Fatalf("instances = %+v, want %+v", got, want)
+ }
+}
+
+// A hopped exchange is counted once in the totals and also annotated in the
+// hop subset, as in the old family.
+func TestRecordHopSubset(t *testing.T) {
+ m := NewUsageMeter()
+ m.SetClock(newFakeMeterClock(mustTime(t, "2026-11-30T10:15:00Z")).now)
+ rt := instanceRoute("shop.bab.oncarlos.com", "bab", "shop")
+ m.Record(rt, rt.Host, 1, 100, true)
+ m.Record(rt, rt.Host, 1, 50, false)
+
+ got := m.Drain().Instances
+ if len(got) != 1 {
+ t.Fatalf("instances = %+v, want one bucket", got)
+ }
+ for _, c := range got {
+ want := usage.InstanceCount{Requests: 2, BytesOut: 150, HopRequests: 1, HopBytesOut: 100}
+ if c != want {
+ t.Fatalf("bucket = %+v, want %+v (hop inside the totals)", c, want)
+ }
+ }
+}
+
+// CARLOS_INSTANCE_USAGE=off: no per-instance buckets, the old rows as ever.
+func TestDisableInstances(t *testing.T) {
+ m := NewUsageMeter()
+ m.DisableInstances()
+ rt := instanceRoute("shop.bab.oncarlos.com", "bab", "shop")
+ m.Record(rt, rt.Host, 1, 100, true)
+
+ f := m.Drain()
+ if f.Instances != nil {
+ t.Fatalf("instances = %+v, want nil while disabled", f.Instances)
+ }
+ want := usage.EdgeRow{Account: "bab", App: "shop", Requests: 1, BytesOut: 100, HopRequests: 1, HopBytesOut: 100}
+ if got := f.Rows[rt.Host]; got != want {
+ t.Fatalf("old row = %+v, want %+v", got, want)
+ }
+}
+
+// The instance argument never changes the old family: one script recorded
+// with "" and with the route's own host drains to equal rows.
+func TestOldRowsUnchangedByInstanceArg(t *testing.T) {
+ script := func(instance func(registry.Route) string) map[string]usage.EdgeRow {
+ m := NewUsageMeter()
+ a := instanceRoute("a.bab.oncarlos.com", "bab", "shop")
+ b := registry.Route{Host: "b.bab.oncarlos.com", Kind: "static", Account: "bab", App: "docs"}
+ moved := instanceRoute("a.bab.oncarlos.com", "bdk", "shop")
+ m.Record(a, instance(a), 1, 100, false)
+ m.Record(a, instance(a), 1, 20, true)
+ m.Record(b, instance(b), 1, 5, false)
+ m.Record(moved, instance(moved), 3, 7, true)
+ return m.Drain().Rows
+ }
+ blank := script(func(registry.Route) string { return "" })
+ own := script(func(rt registry.Route) string { return rt.Host })
+ if !maps.Equal(blank, own) {
+ t.Fatalf("rows with instance \"\" = %+v, with the route host = %+v; want equal", blank, own)
+ }
+ if len(own) != 2 {
+ t.Fatalf("rows = %+v, want two hosts", own)
+ }
+}
+
+// T13: Record from many goroutines while another drains in a loop. Every
+// recorded exchange is in exactly one drain, in both families.
+func TestRecordConcurrentDrain(t *testing.T) {
+ m := NewUsageMeter()
+ clk := newFakeMeterClock(mustTime(t, "2026-11-30T10:59:59Z"))
+ m.SetClock(clk.now)
+ rt := instanceRoute("shop.bab.oncarlos.com", "bab", "shop")
+ const workers, each = 8, 2000
+
+ var rows, inst atomic.Int64
+ sum := func(f usage.EdgeFlush) {
+ for _, r := range f.Rows {
+ rows.Add(r.Requests)
+ }
+ for _, c := range f.Instances {
+ inst.Add(c.Requests)
+ }
+ }
+ stop := make(chan struct{})
+ drained := make(chan struct{})
+ go func() {
+ defer close(drained)
+ for {
+ select {
+ case <-stop:
+ return
+ default:
+ sum(m.Drain())
+ }
+ }
+ }()
+ var wg sync.WaitGroup
+ for w := 0; w < workers; w++ {
+ wg.Add(1)
+ go func(w int) {
+ defer wg.Done()
+ for j := 0; j < each; j++ {
+ if w == 0 && j == each/2 {
+ clk.set(mustTime(t, "2026-11-30T11:00:01Z"))
+ }
+ m.Record(rt, rt.Host, 1, 10, j%2 == 0)
+ }
+ }(w)
+ }
+ wg.Wait()
+ close(stop)
+ <-drained
+ sum(m.Drain())
+
+ if got := rows.Load(); got != workers*each {
+ t.Fatalf("old rows counted %d requests, want %d", got, workers*each)
+ }
+ if got := inst.Load(); got != workers*each {
+ t.Fatalf("instance buckets counted %d requests, want %d", got, workers*each)
+ }
+}
+
+// A custom domain attached to instance A is requested at 10:10, attached to
+// instance B, then requested at 10:40. Each request counts to the instance
+// that served it, in the same hour; the old rows key by each served route's
+// host as today. Tested at the edge: real registry rows, a real alias row
+// re-pointed and reloaded, requests through ServeHTTP.
+func TestDomainMovedMidHourSplitsAtCountTime(t *testing.T) {
+ backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ io.WriteString(w, "hello")
+ }))
+ t.Cleanup(backend.Close)
+ const hostA, hostB, domain = "a.bab.oncarlos.com", "b.bab.oncarlos.com", "www.customer.example"
+ reg := openReg(t)
+ for _, h := range []string{hostA, hostB} {
+ if err := reg.Upsert(registry.Route{Host: h, Kind: "instance", Account: "bab", App: "shop",
+ Addr: backend.Listener.Addr().String(), Status: "ready"}); err != nil {
+ t.Fatalf("upsert %s: %v", h, err)
+ }
+ }
+ upsertAlias(t, reg, domain, hostA)
+ e, err := New(reg, nil)
+ if err != nil {
+ t.Fatalf("New: %v", err)
+ }
+ meter := NewUsageMeter()
+ clk := newFakeMeterClock(mustTime(t, "2026-11-30T10:10:00Z"))
+ meter.SetClock(clk.now)
+ e.EnableUsage(meter)
+ srv := httptest.NewServer(e)
+ t.Cleanup(srv.Close)
+
+ if code, body := getHost(t, srv.URL, domain); code != http.StatusOK || body != "hello" {
+ t.Fatalf("10:10 via A: %d %q", code, body)
+ }
+ upsertAlias(t, reg, domain, hostB)
+ if err := e.Reload(); err != nil {
+ t.Fatalf("Reload: %v", err)
+ }
+ clk.set(mustTime(t, "2026-11-30T10:40:00Z"))
+ if code, body := getHost(t, srv.URL, domain); code != http.StatusOK || body != "hello" {
+ t.Fatalf("10:40 via B: %d %q", code, body)
+ }
+
+ f := meter.Drain()
+ hour := mustTime(t, "2026-11-30T10:00:00Z").Unix() / 3600
+ one := usage.InstanceCount{Requests: 1, BytesOut: 5}
+ want := map[usage.InstanceBucket]usage.InstanceCount{
+ {Hour: hour, Account: "bab", App: "shop", Instance: hostA}: one,
+ {Hour: hour, Account: "bab", App: "shop", Instance: hostB}: one,
+ }
+ if !maps.Equal(f.Instances, want) {
+ t.Fatalf("instances = %+v, want %+v", f.Instances, want)
+ }
+ for _, h := range []string{hostA, hostB} {
+ if row := f.Rows[h]; row.Requests != 1 || row.BytesOut != 5 {
+ t.Fatalf("old row %s = %+v, want 1 request 5 bytes", h, row)
+ }
+ }
+ if _, ok := f.Rows[domain]; ok {
+ t.Fatalf("old rows = %+v, want none keyed by the attached domain", f.Rows)
+ }
+}
diff --git a/internal/edge/usagemeter_test.go b/internal/edge/usagemeter_test.go
index 8ad8e0cd9..18801ce47 100644
--- a/internal/edge/usagemeter_test.go
+++ b/internal/edge/usagemeter_test.go
@@ -18,9 +18,9 @@ import (
func TestUsageMeterRecordAndDrain(t *testing.T) {
m := NewUsageMeter()
rt := registry.Route{Host: "a.example.com", App: "hello", Account: "bab"}
- m.Record(rt, 1, 100, false)
- m.Record(rt, 1, 50, false)
- m.Record(registry.Route{Host: "b.example.com", App: "site"}, 1, 10, false) // Account "" -> release.OpsAccount
+ m.Record(rt, rt.Host, 1, 100, false)
+ m.Record(rt, rt.Host, 1, 50, false)
+ m.Record(registry.Route{Host: "b.example.com", App: "site"}, "b.example.com", 1, 10, false) // Account "" -> release.OpsAccount
got := m.Drain().Rows
a := got["a.example.com"]
@@ -43,8 +43,8 @@ func TestUsageMeterRecordAndDrain(t *testing.T) {
func TestRecordHopAnnotatesSubset(t *testing.T) {
m := NewUsageMeter()
rt := registry.Route{Host: "a.example.com", App: "hello", Account: "bab"}
- m.Record(rt, 1, 100, true)
- m.Record(rt, 1, 50, false)
+ m.Record(rt, rt.Host, 1, 100, true)
+ m.Record(rt, rt.Host, 1, 50, false)
row := m.Drain().Rows["a.example.com"]
if row.Requests != 2 || row.BytesOut != 150 {
@@ -70,7 +70,7 @@ func TestUsageMeterConcurrent(t *testing.T) {
go func() {
defer wg.Done()
for j := 0; j < 100; j++ {
- m.Record(rt, 1, 10, false)
+ m.Record(rt, rt.Host, 1, 10, false)
}
}()
}
@@ -130,9 +130,9 @@ func TestUsageMeterOwnerChangeResetsRateCounters(t *testing.T) {
after := registry.Route{Host: "shop.example.com", App: "shop", Account: "bab"}
m.RecordRateLimited(before, ratelimit.Shed)
m.RecordRateLimited(before, ratelimit.OverCeiling)
- m.Record(before, 2, 20, false)
+ m.Record(before, before.Host, 2, 20, false)
m.RecordRateLimited(after, ratelimit.Shed)
- m.Record(after, 1, 10, false)
+ m.Record(after, after.Host, 1, 10, false)
got := m.Drain().Rows["shop.example.com"]
want := usage.EdgeRow{Account: "bab", App: "shop", Requests: 3, BytesOut: 30, RateShed: 1}
@@ -200,7 +200,7 @@ func TestRecordGuardOwnerChangeWithinDrain(t *testing.T) {
}
rule := catalogueRule(t, "probe.wordpress.wp-login")
m.RecordGuard(before, rule, false)
- m.Record(after, 1, 10, false)
+ m.Record(after, after.Host, 1, 10, false)
m.RecordGuard(after, rule, false)
f := m.Drain()