console: one edge-day reader for root and fleet boxes; fleet rows vouch only for their own account
readEdgeDays reads the root boxes' edge days and those under fleets/<fleet>/usage/edge/ for the registry's fleets. An account's read drops every fleet it does not own before any store call and fails on any unreadable day; the operator's read leaves an unreadable fleet out and names it. rowCounts and tallyCounts are the ownership rule: a fleet's row or tally counts only for the fleet's owner. The rate-limit GET moves onto the reader (root results unchanged; its account's fleet boxes now count), and the usage-day cache recognises fleet edge days.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
5 files changed,
+545
−53
internal/console/apiinstances_ratelimit.go+25 −48internal/console/edgedays.go+178 −0internal/console/edgedays_test.go+317 −0internal/console/usagedays.go+10 −5internal/console/usagedays_test.go+15 −0
diff --git a/internal/console/apiinstances_ratelimit.go b/internal/console/apiinstances_ratelimit.go| index 732abc55b..19f995b36 100644 |
| --- a/internal/console/apiinstances_ratelimit.go |
| +++ b/internal/console/apiinstances_ratelimit.go |
| @@ -2,7 +2,6 @@ package console |
| import ( |
| "context" |
| - "encoding/json" |
| "errors" |
| "fmt" |
| "log" |
| @@ -15,7 +14,6 @@ import ( |
| "github.com/carlosframework/platform/internal/provision" |
| "github.com/carlosframework/platform/internal/ratelimit" |
| - "github.com/carlosframework/platform/internal/release" |
| "github.com/carlosframework/platform/internal/usage" |
| ) |
| @@ -167,68 +165,47 @@ func (s *Server) handleAPIInstanceRateLimitGet(w http.ResponseWriter, r *http.Re |
| } |
| // rateLimitCounts sums host's refusal counters over every box's edge day |
| -// objects for the 24 hours before now. The boxes are found the way the |
| -// usage sweep finds them (sweepUsage). Edge rows are hour buckets, so an |
| -// hour counts whole when any of it falls in the window: the counts can |
| -// reach up to an hour further back than Since, never less far. |
| +// objects for the 24 hours before now: the root boxes, and the boxes of the |
| +// fleets acct owns (readEdgeDays, read as acct's view, so another account's |
| +// fleet is never read). Edge rows are hour buckets, so an hour counts whole |
| +// when any of it falls in the window: the counts can reach up to an hour |
| +// further back than Since, never less far. |
| // |
| -// 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 |
| +// A row counts only under this instance's own account and app, and a fleet |
| +// box's row only when acct owns that fleet (rowCounts). 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.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. |
| // |
| // A missing day object is a box that served nothing that day. One that |
| -// does not decode is an error, never a zero. |
| +// does not decode is an error, never a zero: skipping it would report a |
| +// short total, which reads as fewer refusals. |
| func (s *Server) rateLimitCounts(ctx context.Context, acct *Account, app, host string, now time.Time) (rateLimitCountsView, error) { |
| now = now.UTC() |
| since := now.Add(-24 * time.Hour) |
| out := rateLimitCountsView{Since: since.Format(time.RFC3339)} |
| - boxes, err := s.cfg.Releases.ListDirs(ctx, usage.EdgeBoxesPrefix) |
| - if err != nil { |
| - return out, err |
| - } |
| days := []string{usage.DayOf(since)} |
| if d := usage.DayOf(now); d != days[0] { |
| days = append(days, d) |
| } |
| - for _, boxPrefix := range boxes { |
| - box := strings.TrimSuffix(strings.TrimPrefix(boxPrefix, usage.EdgeBoxesPrefix), "/") |
| - for _, date := range days { |
| - key := usage.EdgeDayKey(box, date) |
| - raw, _, err := s.cfg.Releases.Get(ctx, key) |
| - if errors.Is(err, os.ErrNotExist) { |
| - continue // the box served nothing that day |
| - } |
| - if err != nil { |
| - return out, err |
| - } |
| - var ed usage.EdgeDay |
| - // A day that cannot be read fails the whole answer: skipping it |
| - // would report a short total, which reads as fewer refusals. |
| - if err := json.Unmarshal(raw, &ed); err != nil { |
| - return out, fmt.Errorf("parse %s: %w", key, err) |
| + srcs, _, err := s.readEdgeDays(ctx, s.cfg.Releases, days, acct.Sqid) |
| + if err != nil { |
| + return out, err |
| + } |
| + for _, src := range srcs { |
| + for hour, rows := range src.Day.Hours { |
| + row, ok := rows[host] |
| + if !ok || !rowCounts(src, row, acct.Sqid, app) { |
| + continue |
| } |
| - for hour, rows := range ed.Hours { |
| - row, ok := rows[host] |
| - if !ok { |
| - continue |
| - } |
| - rowAcct := row.Account |
| - if rowAcct == "" { |
| - rowAcct = release.OpsAccount |
| - } |
| - if rowAcct != acct.Sqid || row.App != app { |
| - continue |
| - } |
| - start, err := time.Parse("2006-01-02 15", date+" "+hour) |
| - if err != nil || !start.Add(time.Hour).After(since) || start.After(now) { |
| - continue |
| - } |
| - out.Shed += row.RateShed |
| - out.Ceiling += row.RateCeiling |
| + start, err := time.Parse("2006-01-02 15", src.Day.Date+" "+hour) |
| + if err != nil || !start.Add(time.Hour).After(since) || start.After(now) { |
| + continue |
| } |
| + out.Shed += row.RateShed |
| + out.Ceiling += row.RateCeiling |
| } |
| } |
| return out, nil |
diff --git a/internal/console/edgedays.go b/internal/console/edgedays.go| new file mode 100644 |
| index 000000000..46e769256 |
| --- /dev/null |
| +++ b/internal/console/edgedays.go |
| @@ -0,0 +1,178 @@ |
| +package console |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "errors" |
| + "fmt" |
| + "log" |
| + "os" |
| + "sort" |
| + "strings" |
| + |
| + "github.com/carlosframework/platform/internal/release" |
| + "github.com/carlosframework/platform/internal/usage" |
| +) |
| + |
| +// The console's one reader of usage edge days, for every page that counts |
| +// an app's edge traffic: the rate-limit GET, the Protection tab and the |
| +// operator's protection page. A root box writes its day at |
| +// usage/edge/<box>/days/<date>.json; a fleet box writes the same object |
| +// through a store rebased under its fleet's prefix (CARLOS_STATUS_PREFIX, |
| +// internal/host/usage_loop.go), so at |
| +// fleets/<fleet>/usage/edge/<box>/days/<date>.json. |
| +// |
| +// The two are not trusted alike. A root box is the platform's own, and its |
| +// rows count for the account they name. A fleet box can write any bytes |
| +// anywhere under fleets/<fleet>/ (the store door, internal/edge/storedoor.go), |
| +// so its rows and tallies vouch only for the fleet's owner: rowCounts and |
| +// tallyCounts are the rule every consumer applies, never a check of its own. |
| + |
| +// edgeDaySource is one box's day as read, with where it came from: Fleet is |
| +// "" for a root box, and FleetAccount the owner of the fleet whose prefix |
| +// held it. Day.Box and Day.Date are the key's, never the body's. |
| +type edgeDaySource struct { |
| + Day usage.EdgeDay |
| + Fleet string |
| + FleetAccount string |
| +} |
| + |
| +// readEdgeDays reads every box's edge day for each of dates through st: the |
| +// root boxes, then the boxes of each fleet the registry knows. A missing day |
| +// is a box that served nothing that day. |
| +// |
| +// acct names whose view this is. An account's view (acct != "") reads only |
| +// the fleets acct owns; every other fleet is dropped before any store call, |
| +// so a fleet's bytes cannot fail, slow or be seen by another account's page. |
| +// Any read or parse error, on a root box or one of acct's own fleets, fails |
| +// the call: a short total must never look complete. The operator's view |
| +// (acct == "") reads every fleet, and a fleet it cannot read does not fail |
| +// the call: that fleet's days are left out and its name returned, so the |
| +// page can say which fleets it could not read. A root box's error fails it |
| +// as it does an account's. |
| +func (s *Server) readEdgeDays(ctx context.Context, st release.Store, dates []string, acct string) ([]edgeDaySource, []string, error) { |
| + fleets, err := s.edgeDayFleets(acct) |
| + if err != nil { |
| + return nil, nil, err |
| + } |
| + root, err := readEdgeDayBoxes(ctx, st, "", dates) |
| + if err != nil { |
| + return nil, nil, err |
| + } |
| + var out []edgeDaySource |
| + for _, d := range root { |
| + out = append(out, edgeDaySource{Day: d}) |
| + } |
| + var unread []string |
| + for _, f := range fleets { |
| + days, err := readEdgeDayBoxes(ctx, st, "fleets/"+f.name+"/", dates) |
| + if err != nil { |
| + // A read cut off by the deadline is a failed read, never a |
| + // fleet that could not be read. |
| + if acct != "" || ctx.Err() != nil { |
| + return nil, nil, fmt.Errorf("fleet %s: %w", f.name, err) |
| + } |
| + log.Printf("console: edge days: fleet %s left out: %v", f.name, err) |
| + unread = append(unread, f.name) |
| + continue |
| + } |
| + for _, d := range days { |
| + out = append(out, edgeDaySource{Day: d, Fleet: f.name, FleetAccount: f.account}) |
| + } |
| + } |
| + return out, unread, nil |
| +} |
| + |
| +// edgeDayFleet is a fleet readEdgeDays reads: its name and its owner. |
| +type edgeDayFleet struct{ name, account string } |
| + |
| +// edgeDayFleets is the registry's fleets in name order, only acct's when |
| +// acct is set. A console with no registry has no fleets. A registry that |
| +// cannot be read fails the read: the fleets it holds are unknown, and |
| +// leaving them out would be a short total. |
| +func (s *Server) edgeDayFleets(acct string) ([]edgeDayFleet, error) { |
| + if s.cfg.Registry == "" { |
| + return nil, nil |
| + } |
| + reg, err := s.openPassRegistry() |
| + if err != nil { |
| + return nil, fmt.Errorf("console: edge days: %w", err) |
| + } |
| + fleets, err := reg.ListFleets() |
| + if err != nil { |
| + return nil, fmt.Errorf("console: edge days: list fleets: %w", err) |
| + } |
| + var out []edgeDayFleet |
| + for _, f := range fleets { |
| + owner := edgeAccount(f.Account) |
| + if acct != "" && owner != acct { |
| + continue |
| + } |
| + out = append(out, edgeDayFleet{name: f.Name, account: owner}) |
| + } |
| + sort.Slice(out, func(i, j int) bool { return out[i].name < out[j].name }) |
| + return out, nil |
| +} |
| + |
| +// readEdgeDayBoxes reads each box's day for each of dates under base ("" or |
| +// a fleet's prefix), boxes in name order. A missing day is skipped; any |
| +// other error, a day that does not decode included, is returned. |
| +func readEdgeDayBoxes(ctx context.Context, st release.Store, base string, dates []string) ([]usage.EdgeDay, error) { |
| + dirs, err := st.ListDirs(ctx, base+usage.EdgeBoxesPrefix) |
| + if err != nil { |
| + return nil, err |
| + } |
| + sort.Strings(dirs) |
| + var out []usage.EdgeDay |
| + for _, dir := range dirs { |
| + box := strings.TrimSuffix(strings.TrimPrefix(dir, base+usage.EdgeBoxesPrefix), "/") |
| + if box == "" { |
| + continue |
| + } |
| + for _, date := range dates { |
| + key := base + usage.EdgeDayKey(box, date) |
| + raw, _, err := st.Get(ctx, key) |
| + if errors.Is(err, os.ErrNotExist) { |
| + continue // the box served nothing that day |
| + } |
| + if err != nil { |
| + return nil, err |
| + } |
| + var d usage.EdgeDay |
| + if err := json.Unmarshal(raw, &d); err != nil { |
| + return nil, fmt.Errorf("parse %s: %w", key, err) |
| + } |
| + d.Box, d.Date = box, date |
| + out = append(out, d) |
| + } |
| + } |
| + return out, nil |
| +} |
| + |
| +// rowCounts reports whether row is acct's app's traffic as src may vouch |
| +// for it: the row names acct (an empty account is the ops account, as on a |
| +// route) and app, and, read from a fleet's prefix, acct owns that fleet. |
| +func rowCounts(src edgeDaySource, row usage.EdgeRow, acct, app string) bool { |
| + return row.App == app && edgeOwnerCounts(src, row.Account, acct) |
| +} |
| + |
| +// tallyCounts is rowCounts' rule for a guard tally. |
| +func tallyCounts(src edgeDaySource, t usage.GuardTally, acct, app string) bool { |
| + return t.App == app && edgeOwnerCounts(src, t.Account, acct) |
| +} |
| + |
| +// edgeOwnerCounts is the account half of rowCounts: claimed is acct, and a |
| +// fleet source vouches for no account but its owner. |
| +func edgeOwnerCounts(src edgeDaySource, claimed, acct string) bool { |
| + claimed = edgeAccount(claimed) |
| + return claimed == acct && (src.Fleet == "" || claimed == edgeAccount(src.FleetAccount)) |
| +} |
| + |
| +// edgeAccount is an edge row's or a fleet's account, an empty one being the |
| +// ops account (release.RouteAccount's rule for a route with none). |
| +func edgeAccount(a string) string { |
| + if a == "" { |
| + return release.OpsAccount |
| + } |
| + return a |
| +} |
diff --git a/internal/console/edgedays_test.go b/internal/console/edgedays_test.go| new file mode 100644 |
| index 000000000..1a07ccf8d |
| --- /dev/null |
| +++ b/internal/console/edgedays_test.go |
| @@ -0,0 +1,317 @@ |
| +package console |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "io" |
| + "net/http" |
| + "reflect" |
| + "strings" |
| + "sync" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/registry" |
| + "github.com/carlosframework/platform/internal/release" |
| + "github.com/carlosframework/platform/internal/usage" |
| +) |
| + |
| +const edDate = "2026-11-02" |
| + |
| +// edAt is an hour inside edDate. |
| +var edAt = time.Date(2026, 11, 2, 9, 5, 0, 0, time.UTC) |
| + |
| +// edCreateFleet creates fleet name owned by account in the fixture's |
| +// registry, through its own handle, as the fleet-create door would. |
| +func edCreateFleet(t *testing.T, fx *consoleFixture, name, account string) { |
| + t.Helper() |
| + reg, err := registry.Open(fx.regPath) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer reg.Close() |
| + if created, err := reg.CreateFleet(registry.Fleet{Name: name, Account: account, Bucket: name + "-data"}); err != nil || !created { |
| + t.Fatalf("create fleet %s: %v, %v", name, created, err) |
| + } |
| +} |
| + |
| +// edFleetStore is the store a box of fleet writes through: the bucket |
| +// rebased under fleets/<fleet>/, as CARLOS_STATUS_PREFIX does on the box. |
| +func edFleetStore(fx *consoleFixture, fleet string) release.Store { |
| + return release.NewPrefixStore(fx.rel, "fleets/"+fleet+"/") |
| +} |
| + |
| +// edUpsert writes one host's row and one guard tally into box's day at at, |
| +// through the edge's own writer. |
| +func edUpsert(t *testing.T, st release.Store, box string, at time.Time, host string, row usage.EdgeRow) { |
| + t.Helper() |
| + f := usage.EdgeFlush{ |
| + Rows: map[string]usage.EdgeRow{host: row}, |
| + Guard: map[string]usage.GuardDelta{usage.GuardKey(host, row.Account, row.App): { |
| + Host: host, Account: row.Account, App: row.App, Checked: 5, Block: 1, Groups: map[string]int64{"scanner": 1}, |
| + }}, |
| + } |
| + if err := usage.UpsertEdgeDay(context.Background(), st, box, at, f); err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
| + |
| +func edPut(t *testing.T, st release.Store, key, body string) { |
| + t.Helper() |
| + if _, err := st.Put(context.Background(), key, []byte(body), ""); err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
| + |
| +// edKeyLog is a store that records every key and prefix it is asked to |
| +// read or list. |
| +type edKeyLog struct { |
| + release.Store |
| + mu sync.Mutex |
| + seen []string |
| +} |
| + |
| +func (l *edKeyLog) note(op, key string) { |
| + l.mu.Lock() |
| + l.seen = append(l.seen, op+" "+key) |
| + l.mu.Unlock() |
| +} |
| + |
| +func (l *edKeyLog) Get(ctx context.Context, key string) ([]byte, string, error) { |
| + l.note("get", key) |
| + return l.Store.Get(ctx, key) |
| +} |
| + |
| +func (l *edKeyLog) Open(ctx context.Context, key string) (io.ReadCloser, string, error) { |
| + l.note("open", key) |
| + return release.OpenObject(ctx, l.Store, key) |
| +} |
| + |
| +func (l *edKeyLog) List(ctx context.Context, prefix string) ([]string, error) { |
| + l.note("list", prefix) |
| + return l.Store.List(ctx, prefix) |
| +} |
| + |
| +func (l *edKeyLog) ListDirs(ctx context.Context, prefix string) ([]string, error) { |
| + l.note("listdirs", prefix) |
| + return l.Store.ListDirs(ctx, prefix) |
| +} |
| + |
| +// edForeignFixture is a console with a root box and fleet f1 (owned by |
| +// bab) each holding a good day, and fleet f2 (owned by bdk) holding a day |
| +// that does not decode. |
| +func edForeignFixture(t *testing.T) *consoleFixture { |
| + t.Helper() |
| + fx := newConsoleFixture(t) |
| + edCreateFleet(t, fx, "f1", "bab") |
| + edCreateFleet(t, fx, "f2", "bdk") |
| + edUpsert(t, fx.rel, "box-a", edAt, "shop.example.com", usage.EdgeRow{Account: "bab", App: "shop", Requests: 1}) |
| + edUpsert(t, edFleetStore(fx, "f1"), "pi-1", edAt, "shop.example.com", usage.EdgeRow{Account: "bab", App: "shop", Requests: 2}) |
| + edPut(t, fx.rel, "fleets/f2/"+usage.EdgeDayKey("pi-2", edDate), "{not json") |
| + return fx |
| +} |
| + |
| +// sourceNames is each source as "<fleet>/<box>", root boxes with no fleet. |
| +func sourceNames(srcs []edgeDaySource) []string { |
| + var out []string |
| + for _, s := range srcs { |
| + out = append(out, s.Fleet+"/"+s.Day.Box) |
| + } |
| + return out |
| +} |
| + |
| +func TestReadEdgeDaysRootAndFleet(t *testing.T) { |
| + fx := newConsoleFixture(t) |
| + edCreateFleet(t, fx, "f1", "bab") |
| + edUpsert(t, fx.rel, "box-a", edAt, "shop.example.com", usage.EdgeRow{Account: "bab", App: "shop", Requests: 1}) |
| + edUpsert(t, edFleetStore(fx, "f1"), "pi-1", edAt, "shop.example.com", usage.EdgeRow{Account: "bab", App: "shop", Requests: 2}) |
| + |
| + for _, acct := range []string{"bab", ""} { |
| + srcs, unread, err := fx.srv.readEdgeDays(context.Background(), fx.rel, []string{edDate}, acct) |
| + if err != nil { |
| + t.Fatalf("acct %q: %v", acct, err) |
| + } |
| + if len(unread) != 0 { |
| + t.Errorf("acct %q: unreadable fleets %v, want none", acct, unread) |
| + } |
| + if len(srcs) != 2 { |
| + t.Fatalf("acct %q: sources %v, want a root box and a fleet box", acct, sourceNames(srcs)) |
| + } |
| + root, fleet := srcs[0], srcs[1] |
| + if root.Fleet != "" || root.FleetAccount != "" || root.Day.Box != "box-a" || root.Day.Date != edDate { |
| + t.Errorf("acct %q: root source = %+v", acct, root) |
| + } |
| + if fleet.Fleet != "f1" || fleet.FleetAccount != "bab" || fleet.Day.Box != "pi-1" || fleet.Day.Date != edDate { |
| + t.Errorf("acct %q: fleet source = fleet %q account %q box %q date %q, want f1 bab pi-1 %s", |
| + acct, fleet.Fleet, fleet.FleetAccount, fleet.Day.Box, fleet.Day.Date, edDate) |
| + } |
| + if got := fleet.Day.Hours["09"]["shop.example.com"].Requests; got != 2 { |
| + t.Errorf("acct %q: fleet row requests = %d, want 2", acct, got) |
| + } |
| + } |
| +} |
| + |
| +// A fleet box writes what it likes under its own prefix, so a row or a |
| +// tally in its day vouches only for the fleet's owner: one claiming another |
| +// account counts for nobody. A root box's row counts for the account it |
| +// names. |
| +func TestRowCountsRefusesForeignFleetRow(t *testing.T) { |
| + fx := newConsoleFixture(t) |
| + edCreateFleet(t, fx, "f1", "bab") |
| + host := "shop.example.com" |
| + edUpsert(t, edFleetStore(fx, "f1"), "pi-1", edAt, host, usage.EdgeRow{Account: "bdk", App: "shop", Requests: 9}) |
| + edUpsert(t, edFleetStore(fx, "f1"), "pi-2", edAt, host, usage.EdgeRow{Account: "bab", App: "shop", Requests: 9}) |
| + edUpsert(t, fx.rel, "box-a", edAt, host, usage.EdgeRow{Account: "bdk", App: "shop", Requests: 9}) |
| + |
| + srcs, _, err := fx.srv.readEdgeDays(context.Background(), fx.rel, []string{edDate}, "") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if len(srcs) != 3 { |
| + t.Fatalf("sources %v, want box-a, f1/pi-1, f1/pi-2", sourceNames(srcs)) |
| + } |
| + got := map[string][2]bool{} |
| + for _, src := range srcs { |
| + row := src.Day.Hours["09"][host] |
| + tally, ok := src.Day.Guard[usage.GuardKey(host, row.Account, row.App)] |
| + if !ok { |
| + t.Fatalf("%s/%s: no guard tally for %s/%s", src.Fleet, src.Day.Box, row.Account, row.App) |
| + } |
| + got[src.Fleet+"/"+src.Day.Box] = [2]bool{rowCounts(src, row, row.Account, "shop"), tallyCounts(src, tally, row.Account, "shop")} |
| + } |
| + want := map[string][2]bool{ |
| + "/box-a": {true, true}, // a root box vouches for bdk |
| + "f1/pi-1": {false, false}, // bab's fleet claiming bdk/shop |
| + "f1/pi-2": {true, true}, // bab's fleet claiming bab/shop |
| + } |
| + if !reflect.DeepEqual(got, want) { |
| + t.Errorf("rowCounts, tallyCounts by source = %v, want %v", got, want) |
| + } |
| + |
| + // The rule itself, apart from the reader: the app must match too, and |
| + // an empty account is the ops account on either side. |
| + fleet := edgeDaySource{Fleet: "f1", FleetAccount: "bab"} |
| + if rowCounts(fleet, usage.EdgeRow{Account: "bab", App: "other"}, "bab", "shop") { |
| + t.Error("a row for another app counts") |
| + } |
| + if !rowCounts(fleet, usage.EdgeRow{App: "shop"}, release.OpsAccount, "shop") { |
| + t.Error("a row with no account in the ops account's fleet does not count for the ops account") |
| + } |
| + if tallyCounts(edgeDaySource{Fleet: "f1", FleetAccount: "bab"}, usage.GuardTally{Account: "bdk", App: "shop"}, "bdk", "shop") { |
| + t.Error("a foreign tally counts") |
| + } |
| +} |
| + |
| +// A day that does not decode fails the read, on a root box for any reader |
| +// and in the reading account's own fleet: a short total must never look |
| +// complete. |
| +func TestReadEdgeDaysParseErrorFails(t *testing.T) { |
| + fx := newConsoleFixture(t) |
| + edUpsert(t, fx.rel, "box-a", edAt, "shop.example.com", usage.EdgeRow{Account: "bab", App: "shop"}) |
| + edPut(t, fx.rel, usage.EdgeDayKey("box-b", edDate), "{not json") |
| + for _, acct := range []string{"bab", ""} { |
| + srcs, _, err := fx.srv.readEdgeDays(context.Background(), fx.rel, []string{edDate}, acct) |
| + if err == nil || srcs != nil { |
| + t.Errorf("acct %q, malformed root day: sources %v, err %v; want an error and no sources", acct, sourceNames(srcs), err) |
| + } |
| + } |
| + |
| + fx = newConsoleFixture(t) |
| + edCreateFleet(t, fx, "f1", "bab") |
| + edUpsert(t, fx.rel, "box-a", edAt, "shop.example.com", usage.EdgeRow{Account: "bab", App: "shop"}) |
| + edPut(t, fx.rel, "fleets/f1/"+usage.EdgeDayKey("pi-1", edDate), "{not json") |
| + srcs, _, err := fx.srv.readEdgeDays(context.Background(), fx.rel, []string{edDate}, "bab") |
| + if err == nil || srcs != nil { |
| + t.Errorf("malformed day in the account's own fleet: sources %v, err %v; want an error and no sources", sourceNames(srcs), err) |
| + } |
| +} |
| + |
| +// An account's read drops every fleet it does not own before any store |
| +// call: no key of fleet f2 is listed or read, so its malformed day cannot |
| +// fail bab's read, and nothing under the fleets/ root is listed either. |
| +func TestReadEdgeDaysNeverTouchesForeignFleet(t *testing.T) { |
| + fx := edForeignFixture(t) |
| + st := &edKeyLog{Store: fx.rel} |
| + srcs, unread, err := fx.srv.readEdgeDays(context.Background(), st, []string{edDate}, "bab") |
| + if err != nil { |
| + t.Fatalf("bab's read: %v", err) |
| + } |
| + if got, want := sourceNames(srcs), []string{"/box-a", "f1/pi-1"}; !reflect.DeepEqual(got, want) || len(unread) != 0 { |
| + t.Errorf("bab's read = %v, unreadable %v; want %v and none", got, unread, want) |
| + } |
| + for _, s := range st.seen { |
| + _, key, _ := strings.Cut(s, " ") |
| + if strings.HasPrefix(key, "fleets/f2") || key == "fleets/" || key == "fleets" { |
| + t.Errorf("bab's read touched %q", s) |
| + } |
| + } |
| + if len(st.seen) == 0 { |
| + t.Fatal("the key log saw nothing: the read went around the store it was given") |
| + } |
| +} |
| + |
| +// The operator's read reads every fleet. One fleet's unreadable day leaves |
| +// that fleet out and names it; the rest of the answer stands. |
| +func TestReadEdgeDaysOperatorSkipsBadFleet(t *testing.T) { |
| + fx := edForeignFixture(t) |
| + srcs, unread, err := fx.srv.readEdgeDays(context.Background(), fx.rel, []string{edDate}, "") |
| + if err != nil { |
| + t.Fatalf("operator read: %v", err) |
| + } |
| + if got, want := sourceNames(srcs), []string{"/box-a", "f1/pi-1"}; !reflect.DeepEqual(got, want) { |
| + t.Errorf("operator read = %v, want %v", got, want) |
| + } |
| + if !reflect.DeepEqual(unread, []string{"f2"}) { |
| + t.Errorf("unreadable fleets = %v, want [f2]", unread) |
| + } |
| +} |
| + |
| +// The rate-limit GET reads only the fleets the instance's account owns: a |
| +// foreign fleet's malformed day does not fail it. |
| +func TestRateLimitCountsIgnoresForeignFleet(t *testing.T) { |
| + fx, token := rateLimitFixture(t, "code-rl-foreign") |
| + now := time.Now() |
| + edCreateFleet(t, fx, "f1", "bab") |
| + edCreateFleet(t, fx, "f2", "bdk") |
| + rlUpsert(t, fx, "box-a", now, rlHost, usage.EdgeRow{Account: "bab", App: "shop", RateShed: 3, RateCeiling: 1}) |
| + edPut(t, fx.rel, "fleets/f2/"+usage.EdgeDayKey("pi-2", usage.DayOf(now)), "{not json") |
| + status, _, out := rawReq(t, http.MethodGet, updateURL(fx, "bab", "shop", rlHost)+"/rate-limit", token, "") |
| + if status != http.StatusOK { |
| + t.Fatalf("GET = %d %s, want 200: another account's fleet is not this read's", status, out) |
| + } |
| + var v rlRateLimitView |
| + if err := json.Unmarshal([]byte(out), &v); err != nil { |
| + t.Fatal(err) |
| + } |
| + if v.Counts.Shed != 3 || v.Counts.Ceiling != 1 { |
| + t.Errorf("counts = %+v, want shed 3 ceiling 1", v.Counts) |
| + } |
| +} |
| + |
| +// The rate-limit GET counts the instance's refusals on its account's own |
| +// fleet boxes, and not a row another account's fleet writes in its name. |
| +func TestRateLimitCountsIncludesFleetBoxes(t *testing.T) { |
| + fx, token := rateLimitFixture(t, "code-rl-fleet") |
| + now := time.Now() |
| + edCreateFleet(t, fx, "f1", "bab") |
| + edCreateFleet(t, fx, "f3", "bdk") |
| + if err := usage.UpsertEdgeDay(context.Background(), edFleetStore(fx, "f1"), "pi-1", now, |
| + usage.EdgeFlush{Rows: map[string]usage.EdgeRow{rlHost: {Account: "bab", App: "shop", RateShed: 4}}}); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := usage.UpsertEdgeDay(context.Background(), edFleetStore(fx, "f3"), "pi-1", now, |
| + usage.EdgeFlush{Rows: map[string]usage.EdgeRow{rlHost: {Account: "bab", App: "shop", RateShed: 1000, RateCeiling: 1000}}}); err != nil { |
| + t.Fatal(err) |
| + } |
| + status, _, out := rawReq(t, http.MethodGet, updateURL(fx, "bab", "shop", rlHost)+"/rate-limit", token, "") |
| + if status != http.StatusOK { |
| + t.Fatalf("GET = %d %s", status, out) |
| + } |
| + var v rlRateLimitView |
| + if err := json.Unmarshal([]byte(out), &v); err != nil { |
| + t.Fatal(err) |
| + } |
| + if v.Counts.Shed != 4 || v.Counts.Ceiling != 0 { |
| + t.Errorf("counts = %+v, want shed 4 ceiling 0: bab's fleet row counts, bdk's fleet's claim does not", v.Counts) |
| + } |
| +} |
diff --git a/internal/console/usagedays.go b/internal/console/usagedays.go| index aa2cc0605..e8a30269f 100644 |
| --- a/internal/console/usagedays.go |
| +++ b/internal/console/usagedays.go |
| @@ -98,8 +98,8 @@ type usageDayCache struct { |
| } |
| // usageDayDate is the date a usage day object's key names, for the five |
| -// families the economics sweep reads: metrics.DayKey under the platform |
| -// root or a fleet's prefix, usage.EdgeDayKey, usage.StorageDayKey and |
| +// families the economics sweep reads: metrics.DayKey and usage.EdgeDayKey |
| +// under the platform root or a fleet's prefix, usage.StorageDayKey and |
| // usage.CensusDayKey. Any other key is not a day object (ok false), and is |
| // read through untouched. |
| func usageDayDate(key string) (date string, ok bool) { |
| @@ -124,9 +124,14 @@ func usageDayDate(key string) (date string, ok bool) { |
| if j <= 0 { |
| return "", false |
| } |
| - fleet := fleetRest[:j] |
| - box, ok := daysDirBox(fleetRest[j+1:], "metrics/boxes/") |
| - return date, ok && key == "fleets/"+fleet+"/"+metrics.DayKey(box, date) |
| + fleet, inner := fleetRest[:j], fleetRest[j+1:] |
| + if box, ok := daysDirBox(inner, "metrics/boxes/"); ok { |
| + return date, key == "fleets/"+fleet+"/"+metrics.DayKey(box, date) |
| + } |
| + // A fleet box's edge day, which readEdgeDays reads beside the root |
| + // boxes' (edgedays.go). |
| + box, ok := daysDirBox(inner, usage.EdgeBoxesPrefix) |
| + return date, ok && key == "fleets/"+fleet+"/"+usage.EdgeDayKey(box, date) |
| } |
| if box, ok := daysDirBox(dir, "metrics/boxes/"); ok { |
| return date, key == metrics.DayKey(box, date) |
diff --git a/internal/console/usagedays_test.go b/internal/console/usagedays_test.go| new file mode 100644 |
| index 000000000..1b169ef03 |
| --- /dev/null |
| +++ b/internal/console/usagedays_test.go |
| @@ -0,0 +1,15 @@ |
| +package console |
| + |
| +import "testing" |
| + |
| +// TestUsageDayDateFleetEdgeDay: a fleet box's edge day, written through its |
| +// store rebased under fleets/<fleet>/, is a day object the cache knows, so a |
| +// settled fleet day is kept like a root one. A deeper path is not. |
| +func TestUsageDayDateFleetEdgeDay(t *testing.T) { |
| + if got, ok := usageDayDate("fleets/f1/usage/edge/box-a/days/2026-11-02.json"); !ok || got != "2026-11-02" { |
| + t.Errorf("fleet edge day = %q, %v; want 2026-11-02, true", got, ok) |
| + } |
| + if got, ok := usageDayDate("fleets/f1/usage/edge/box-a/x/days/2026-11-02.json"); ok { |
| + t.Errorf("nested fleet edge path = %q, true; want not a day object", got) |
| + } |
| +} |