carlos / platform Public

Merge origin/main into rootfs-apps-3-release

claude agent, operated by paul@keymail.dev 55687383a10b5145af33f6c776499ef3dcce0484 parent d5a73cdparent 90d36e6
9 files changed, +1,532 −52
  • internal/console/economicspass.go +78 −31
  • internal/console/economicsspeed_test.go +883 −0
  • internal/console/economicsview.go +37 −15
  • internal/console/hotreads.go +19 −1
  • internal/console/server.go +4 −0
  • internal/console/testdata/perf-budgets.txt +2 −2
  • internal/console/usageattrib_tags_test.go +2 −2
  • internal/console/usageattrib_test.go +1 −1
  • internal/console/usagedays.go +506 −0
diff --git a/internal/console/economicspass.go b/internal/console/economicspass.go
index 2ff843954..3b4711d7b 100644
--- a/internal/console/economicspass.go
+++ b/internal/console/economicspass.go
@@ -367,14 +367,26 @@ type usageSweep struct {
// sweep and nothing else is still a covered day, exactly as before this
// function existed, even though the bytes themselves are read again by
// foldStorageAndCensus.
-func (s *Server) sweepUsage(ctx context.Context, from, to time.Time, attrib *usageAttribution) (*usageSweep, error) {
- metricsBoxes, err := s.cfg.Releases.ListDirs(ctx, metricsBoxesPrefix)
- if err != nil {
- return nil, fmt.Errorf("console: sweep usage: %w", err)
- }
- edgeBoxes, err := s.cfg.Releases.ListDirs(ctx, usage.EdgeBoxesPrefix)
- if err != nil {
- return nil, fmt.Errorf("console: sweep usage: %w", err)
+//
+// Every read goes through st: the bucket itself for statementsPass (through
+// the settled-day cache's filling wrapper, usagedays.go), and for the
+// dashboard a concurrent reader over that cache (readEconomicsUsage). Which
+// keys it reads follows from the two box listings and the dates alone,
+// never from a body, which is what lets readConcurrently fetch them ahead.
+func (s *Server) sweepUsage(ctx context.Context, st release.Store, from, to time.Time, attrib *usageAttribution) (*usageSweep, error) {
+ var (
+ metricsBoxes, edgeBoxes []string
+ mErr, eErr error
+ )
+ runConcurrently(
+ func() { metricsBoxes, mErr = st.ListDirs(ctx, metricsBoxesPrefix) },
+ func() { edgeBoxes, eErr = st.ListDirs(ctx, usage.EdgeBoxesPrefix) },
+ )
+ if mErr != nil {
+ return nil, fmt.Errorf("console: sweep usage: %w", mErr)
+ }
+ if eErr != nil {
+ return nil, fmt.Errorf("console: sweep usage: %w", eErr)
}
sweep := &usageSweep{
@@ -418,7 +430,7 @@ func (s *Server) sweepUsage(ctx context.Context, from, to time.Time, attrib *usa
for _, boxPrefix := range metricsBoxes {
box := strings.TrimSuffix(strings.TrimPrefix(boxPrefix, metricsBoxesPrefix), "/")
- raw, _, gerr := s.cfg.Releases.Get(ctx, metrics.DayKey(box, date))
+ raw, _, gerr := st.Get(ctx, metrics.DayKey(box, date))
if gerr != nil {
continue // missing = skip, uncovered by this box
}
@@ -482,7 +494,7 @@ func (s *Server) sweepUsage(ctx context.Context, from, to time.Time, attrib *usa
for _, boxPrefix := range edgeBoxes {
box := strings.TrimSuffix(strings.TrimPrefix(boxPrefix, usage.EdgeBoxesPrefix), "/")
- raw, _, gerr := s.cfg.Releases.Get(ctx, usage.EdgeDayKey(box, date))
+ raw, _, gerr := st.Get(ctx, usage.EdgeDayKey(box, date))
if gerr != nil {
continue // missing = skip, uncovered by this box
}
@@ -520,7 +532,7 @@ func (s *Server) sweepUsage(ctx context.Context, from, to time.Time, attrib *usa
// its bytes are not accumulated: that needs statementsPass's
// ValidAccount guard and pass-scoped dedup logging. Missing = skip,
// uncovered by storage (metrics/edge may still have covered it).
- if raw, _, gerr := s.cfg.Releases.Get(ctx, usage.StorageDayKey(date)); gerr == nil {
+ if raw, _, gerr := st.Get(ctx, usage.StorageDayKey(date)); gerr == nil {
var sd usage.StorageDay
if jerr := json.Unmarshal(raw, &sd); jerr == nil {
covered = true
@@ -559,8 +571,8 @@ func (s *Server) sweepUsage(ctx context.Context, from, to time.Time, attrib *usa
// badStorageKeys dedups a malformed storage-day key's log line at most once
// per key for this ONE CALL — matching the pre-split pass-scoped behaviour,
// since each of statementsPass and buildEconomicsView calls this exactly
-// once per invocation.
-func (s *Server) foldStorageAndCensus(ctx context.Context, from, to time.Time, dst map[string]map[string]float64) error {
+// once per invocation. Its reads go through st, as sweepUsage's do.
+func (s *Server) foldStorageAndCensus(ctx context.Context, st release.Store, from, to time.Time, dst map[string]map[string]float64) error {
touch := func(acct string) map[string]float64 {
mm := dst[acct]
if mm == nil {
@@ -578,7 +590,7 @@ func (s *Server) foldStorageAndCensus(ctx context.Context, from, to time.Time, d
y, mo, _ := d.Date()
daysInMonth := time.Date(y, mo+1, 0, 0, 0, 0, 0, time.UTC).Day()
- if raw, _, gerr := s.cfg.Releases.Get(ctx, usage.StorageDayKey(date)); gerr == nil {
+ if raw, _, gerr := st.Get(ctx, usage.StorageDayKey(date)); gerr == nil {
var sd usage.StorageDay
if jerr := json.Unmarshal(raw, &sd); jerr != nil {
log.Printf("console: fold storage/census: parse %s: %v", usage.StorageDayKey(date), jerr)
@@ -613,7 +625,7 @@ func (s *Server) foldStorageAndCensus(ctx context.Context, from, to time.Time, d
// Census does not gate coverage (sweepUsage's covered-day sources are
// metrics/edge/storage only) but still feeds app_months when present.
- if raw, _, gerr := s.cfg.Releases.Get(ctx, usage.CensusDayKey(date)); gerr == nil {
+ if raw, _, gerr := st.Get(ctx, usage.CensusDayKey(date)); gerr == nil {
var cd usage.CensusDay
if jerr := json.Unmarshal(raw, &cd); jerr != nil {
log.Printf("console: fold storage/census: parse %s: %v", usage.CensusDayKey(date), jerr)
@@ -780,7 +792,27 @@ func hasDeviceTag(tags string) bool {
// statements are a create-OR-REPLACE snapshot of the whole month to
// date, not an append-only ledger, so there is no "as of" boundary to
// honor. Modelling-grade, matching every other meter this pass derives.
-func (s *Server) fleetMeters(ctx context.Context, from, to time.Time) (map[string]map[string]float64, error) {
+//
+// Its reads go through st (see sweepUsage); the registry half is
+// fleetMeterBoxes, so a caller reading concurrently asks the registry once.
+func (s *Server) fleetMeters(ctx context.Context, st release.Store, from, to time.Time) (map[string]map[string]float64, error) {
+ boxes, err := s.fleetMeterBoxes()
+ if err != nil {
+ return nil, err
+ }
+ return fleetMetersFrom(ctx, st, boxes, from, to), nil
+}
+
+// fleetMeterBox is one fleet box fleetMeters reads: its fleet and label,
+// the account it bills and whether it is a device.
+type fleetMeterBox struct {
+ fleet, label, acct string
+ device bool
+}
+
+// fleetMeterBoxes is every box registered to every fleet, ALL statuses (see
+// fleetMeters), in fleet then label order.
+func (s *Server) fleetMeterBoxes() ([]fleetMeterBox, error) {
reg, err := s.openPassRegistry()
if err != nil {
return nil, fmt.Errorf("console: fleet meters: %w", err)
@@ -790,23 +822,33 @@ func (s *Server) fleetMeters(ctx context.Context, from, to time.Time) (map[strin
return nil, fmt.Errorf("console: fleet meters: %w", err)
}
- type boxOwner struct {
- acct string
- device bool
- }
type boxKey struct{ fleet, label string }
- boxes := map[boxKey]boxOwner{}
-
+ byKey := map[boxKey]fleetMeterBox{}
for _, f := range fleets {
fboxes, err := reg.ListFleetBoxes(f.Name)
if err != nil {
return nil, fmt.Errorf("console: fleet meters: list boxes %s: %w", f.Name, err)
}
for _, b := range fboxes {
- boxes[boxKey{fleet: f.Name, label: b.Label}] = boxOwner{acct: f.Account, device: hasDeviceTag(b.Tags)}
+ byKey[boxKey{fleet: f.Name, label: b.Label}] = fleetMeterBox{fleet: f.Name, label: b.Label, acct: f.Account, device: hasDeviceTag(b.Tags)}
}
}
+ boxes := make([]fleetMeterBox, 0, len(byKey))
+ for _, b := range byKey {
+ boxes = append(boxes, b)
+ }
+ sort.Slice(boxes, func(i, j int) bool {
+ if boxes[i].fleet != boxes[j].fleet {
+ return boxes[i].fleet < boxes[j].fleet
+ }
+ return boxes[i].label < boxes[j].label
+ })
+ return boxes, nil
+}
+// fleetMetersFrom is fleetMeters's read over boxes: one Get per box per day
+// in [from, to], through st.
+func fleetMetersFrom(ctx context.Context, st release.Store, boxes []fleetMeterBox, from, to time.Time) map[string]map[string]float64 {
out := map[string]map[string]float64{}
touch := func(acct string) map[string]float64 {
mm := out[acct]
@@ -819,12 +861,12 @@ func (s *Server) fleetMeters(ctx context.Context, from, to time.Time) (map[strin
fromDay := from.UTC().Truncate(24 * time.Hour)
toDay := to.UTC().Truncate(24 * time.Hour)
- for bk, owner := range boxes {
+ for _, bk := range boxes {
meter := usage.MeterFleetBoxHoursServer
- if owner.device {
+ if bk.device {
meter = usage.MeterFleetBoxHoursDevice
}
- fleetStore := release.NewPrefixStore(s.cfg.Releases, "fleets/"+bk.fleet+"/")
+ fleetStore := release.NewPrefixStore(st, "fleets/"+bk.fleet+"/")
for d := fromDay; !d.After(toDay); d = d.AddDate(0, 0, 1) {
date := usage.DayOf(d)
key := metrics.DayKey(bk.label, date)
@@ -838,10 +880,10 @@ func (s *Server) fleetMeters(ctx context.Context, from, to time.Time) (map[strin
jobFailed(ctx, fmt.Errorf("fleet meters: parse fleets/%s/%s: %w", bk.fleet, key, jerr))
continue
}
- touch(owner.acct)[meter] += rollupPresenceHours(roll)
+ touch(bk.acct)[meter] += rollupPresenceHours(roll)
}
}
- return out, nil
+ return out
}
// statementsPass folds the month's metrics, edge and storage days (plus
@@ -892,15 +934,20 @@ func (s *Server) statementsPass(ctx context.Context, now time.Time) error {
month := usage.MonthOf(nowUTC)
monthStart := time.Date(y, mo, 1, 0, 0, 0, 0, time.UTC)
- sweep, err := s.sweepUsage(ctx, monthStart, nowUTC, attrib)
+ // The pass reads every day of the month from the bucket, as it always
+ // has, and leaves each settled day it read in the dashboard's day cache
+ // (usagedays.go): no read of its own is skipped or added, and the next
+ // cold dashboard view finds the month's settled days already held.
+ st := s.usageDayFiller(now)
+ sweep, err := s.sweepUsage(ctx, st, monthStart, nowUTC, attrib)
if err != nil {
return fmt.Errorf("console: statements pass: %w", err)
}
meters := sweep.PerAccount // account -> meter -> value; folded into below
- if err := s.foldStorageAndCensus(ctx, monthStart, nowUTC, meters); err != nil {
+ if err := s.foldStorageAndCensus(ctx, st, monthStart, nowUTC, meters); err != nil {
return fmt.Errorf("console: statements pass: %w", err)
}
- fleetMM, err := s.fleetMeters(ctx, monthStart, nowUTC)
+ fleetMM, err := s.fleetMeters(ctx, st, monthStart, nowUTC)
if err != nil {
return fmt.Errorf("console: statements pass: %w", err)
}
diff --git a/internal/console/economicsspeed_test.go b/internal/console/economicsspeed_test.go
new file mode 100644
index 000000000..1a425457e
--- /dev/null
+++ b/internal/console/economicsspeed_test.go
@@ -0,0 +1,883 @@
+package console
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "maps"
+ "net/http"
+ "reflect"
+ "strings"
+ "sync"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/economics"
+ "github.com/carlosframework/platform/internal/metrics"
+ "github.com/carlosframework/platform/internal/release"
+ "github.com/carlosframework/platform/internal/usage"
+)
+
+// The economics sweep's speed (console-economics-speed): its per-day reads
+// run concurrently, and settled days are kept across views. Every test
+// here runs over newPerfFixture, whose console reads a real S3 store over
+// the fake, and counts what reaches the fake.
+
+// econViewCold forgets LoadEconomics's per-period view cache, so the next
+// view sweeps; the settled-day cache is left as it is.
+func econViewCold(fx *consoleFixture) {
+ c := &fx.srv.economicsCache
+ c.mu.Lock()
+ c.entries = nil
+ c.mu.Unlock()
+}
+
+// econAllCold forgets the view cache and the settled-day cache: a console
+// that has read nothing for the page.
+func econAllCold(fx *consoleFixture) {
+ econViewCold(fx)
+ d := &fx.srv.usageDays
+ d.mu.Lock()
+ d.entries, d.bytes = nil, 0
+ d.mu.Unlock()
+}
+
+// econDates is every date from the first of last month to today, the days
+// any period the page offers can show.
+func econDates(now time.Time) []string {
+ var out []string
+ first, _ := time.Parse("2006-01-02", usageDayFirstKept(now))
+ for d := first; !d.After(now.UTC()); d = d.AddDate(0, 0, 1) {
+ out = append(out, usage.DayOf(d))
+ }
+ return out
+}
+
+// econPeriodDates is the dates period sweeps at now.
+func econPeriodDates(period string, now time.Time) []string {
+ from, to := economicsPeriodBounds(period, now)
+ var out []string
+ for d := from.UTC().Truncate(24 * time.Hour); !d.After(to.UTC().Truncate(24 * time.Hour)); d = d.AddDate(0, 0, 1) {
+ out = append(out, usage.DayOf(d))
+ }
+ return out
+}
+
+// econRollup is a metrics day with one platform unit and one instance
+// whose hour the box tagged with acct, sized by n so that every day adds
+// something different. Every figure is a sum of binary fractions, so a
+// period's totals are exact in any order: the sweep adds a day's units in
+// map order, which varies from run to run.
+func econRollup(box, date, acct string, n int) metrics.DayRollup {
+ cpu := 0.25 * float64(n%4+1)
+ return metrics.DayRollup{V: 1, Box: box, Date: date, Hours: map[string]metrics.HourAgg{
+ "09": {
+ Host: map[string]metrics.Agg{"cpu": {Avg: 0.5, N: 60}},
+ Units: map[string]map[string]metrics.Agg{
+ "caddy.service": {"cpu": {Avg: cpu, N: 60}, "mem_bytes": {Avg: 5e8, N: 60}},
+ "carlos-exec@shop.example.com": {"cpu": {Avg: cpu / 2, N: 60}, "mem_bytes": {Avg: 1e9, N: 60}},
+ },
+ Owned: map[string][]metrics.OwnedAgg{"carlos-exec@shop.example.com": {{
+ Owner: metrics.Owner{Account: acct, App: "kass"},
+ Metrics: map[string]metrics.Agg{"cpu": {Avg: cpu / 2, N: 60}, "mem_bytes": {Avg: 1e9, N: 60}},
+ }}},
+ },
+ }}
+}
+
+// seedEconomicsDays writes, for every date, both platform boxes' rollups,
+// an edge day for box-a, fleet-a's pi-1 rollup, and the storage and
+// census days, straight into the bucket (none of it counted).
+func seedEconomicsDays(t *testing.T, fx *consoleFixture, dates []string) {
+ t.Helper()
+ for i, date := range dates {
+ econPut(t, fx, date, i)
+ }
+}
+
+// econPut writes date's objects, sized by n.
+func econPut(t *testing.T, fx *consoleFixture, date string, n int) {
+ t.Helper()
+ ctx := context.Background()
+ put := func(key string, v any) {
+ t.Helper()
+ raw, err := json.Marshal(v)
+ if err != nil {
+ t.Fatal(err)
+ }
+ _, etag, _ := fx.rel.Get(ctx, key)
+ if _, err := fx.rel.Put(ctx, key, raw, etag); err != nil {
+ t.Fatal(err)
+ }
+ }
+ for _, box := range []string{"box-a", "box-b"} {
+ put(metrics.DayKey(box, date), econRollup(box, date, fx.sqid, n))
+ }
+ put("fleets/fleet-a/"+metrics.DayKey("pi-1", date), metrics.DayRollup{V: 1, Box: "pi-1", Date: date,
+ Hours: map[string]metrics.HourAgg{"10": {Host: map[string]metrics.Agg{"cpu": {Avg: 0.1, N: 15 * (n%4 + 1)}}}}})
+ put(usage.EdgeDayKey("box-a", date), usage.EdgeDay{V: 1, Box: "box-a", Date: date, Hours: map[string]map[string]usage.EdgeRow{
+ "09": {"kass.carlosapp.dev": {Account: fx.sqid, App: "kass", Requests: int64(1000 * (n + 1)), BytesOut: int64(5e8) * int64(n%3+1)}},
+ }})
+ put(usage.StorageDayKey(date), usage.StorageDay{V: 1, Date: date, Apps: map[string]usage.AppStorage{
+ fx.sqid + "/kass": {BucketBytes: int64(1e9) * int64(n%5+1)},
+ }})
+ put(usage.CensusDayKey(date), usage.CensusDay{V: 1, Date: date, Accounts: map[string]usage.CensusAccount{
+ fx.sqid: {Apps: n%3 + 1, Routes: 2},
+ }})
+}
+
+// econReference is the economics sweep as it read before
+// console-economics-speed: sweepUsage, foldStorageAndCensus and fleetMeters
+// one read after another straight from the bucket, fleet meters merged in
+// as buildEconomicsView merges them.
+type econRef struct {
+ meters map[string]map[string]float64
+ boxes map[string]economics.BoxLoad
+ covered, period int
+ err error
+}
+
+func econReference(t *testing.T, fx *consoleFixture, period string, now time.Time) econRef {
+ t.Helper()
+ ctx := context.Background()
+ from, to := economicsPeriodBounds(period, now)
+ attrib, _, err := fx.srv.loadAttributionForEconomics()
+ if err != nil {
+ t.Fatal(err)
+ }
+ st := fx.srv.cfg.Releases
+ sweep, err := fx.srv.sweepUsage(ctx, st, from, to, attrib)
+ if err != nil {
+ return econRef{err: err}
+ }
+ if err := fx.srv.foldStorageAndCensus(ctx, st, from, to, sweep.PerAccount); err != nil {
+ return econRef{err: err}
+ }
+ fleet, err := fx.srv.fleetMeters(ctx, st, from, to)
+ if err != nil {
+ t.Fatal(err)
+ }
+ for acct, mm := range fleet {
+ dst := sweep.PerAccount[acct]
+ if dst == nil {
+ dst = map[string]float64{}
+ sweep.PerAccount[acct] = dst
+ }
+ for m, v := range mm {
+ dst[m] += v
+ }
+ }
+ return econRef{meters: sweep.PerAccount, boxes: sweep.PerBox, covered: sweep.CoveredDays, period: sweep.PeriodDays}
+}
+
+// econMatches compares a view with the reference: every meter of every
+// account, exactly, every box's load, and the coverage.
+func econMatches(t *testing.T, label string, v *EconomicsView, ref econRef) {
+ t.Helper()
+ var pl economicsPayload
+ if err := json.Unmarshal([]byte(v.DataJSON), &pl); err != nil {
+ t.Fatal(err)
+ }
+ for acct, mm := range pl.Meters {
+ want := ref.meters[acct]
+ if len(want) == 0 && len(mm) == 0 {
+ continue
+ }
+ if !reflect.DeepEqual(mm, want) {
+ t.Errorf("%s: account %s meters\n got %v\n want %v", label, acct, mm, want)
+ }
+ }
+ for acct, mm := range ref.meters {
+ if _, ok := pl.Meters[acct]; !ok && len(mm) > 0 {
+ t.Errorf("%s: account %s missing from the view", label, acct)
+ }
+ }
+ if len(ref.meters) == 0 {
+ t.Errorf("%s: the reference read no usage: the seeds missed", label)
+ }
+ if !reflect.DeepEqual(pl.BoxLoads, ref.boxes) {
+ t.Errorf("%s: box loads\n got %v\n want %v", label, pl.BoxLoads, ref.boxes)
+ }
+ if v.CoveredDays != ref.covered || v.PeriodDays != ref.period {
+ t.Errorf("%s: coverage %d/%d, want %d/%d", label, v.CoveredDays, v.PeriodDays, ref.covered, ref.period)
+ }
+}
+
+// econView asks for the page (so the view is the one the route renders)
+// and returns the view it rendered from.
+func econView(t *testing.T, fx *consoleFixture, c *http.Client, path, period string) *EconomicsView {
+ t.Helper()
+ u := fx.ts.URL + path
+ if period != "" {
+ u += "?period=" + period
+ }
+ if st, _, body := get(t, c, u); st != http.StatusOK {
+ t.Fatalf("%s = %d:\n%s", u, st, body)
+ }
+ v, err := fx.srv.LoadEconomics(context.Background(), period)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return v
+}
+
+// econDayGets is the day objects a recorder saw read, by key.
+func econDayGets(rec *s3Recorder) map[string]int {
+ out := map[string]int{}
+ for _, q := range rec.all() {
+ if q.Method == http.MethodGet && q.Key != "" {
+ if _, ok := usageDayDate(q.Key); ok {
+ out[q.Key]++
+ }
+ }
+ }
+ return out
+}
+
+// TestEconomicsViewsMatchTheSequentialSweep: over a seeded period, every
+// period's view is the sweep read one object after another from the bucket:
+// cold with nothing held, cold again with the settled days held, and cold
+// after the economics pass filled the cache.
+func TestEconomicsViewsMatchTheSequentialSweep(t *testing.T) {
+ perfCaptureLogs(t)
+ fx, _ := newPerfFixture(t)
+ c := signInPaul(t, fx)
+ seedEconomicsDays(t, fx, econDates(time.Now()))
+ for _, period := range []string{"mtd", "last", "7d"} {
+ ref := econReference(t, fx, period, time.Now())
+ if ref.err != nil {
+ t.Fatal(ref.err)
+ }
+ econAllCold(fx)
+ econMatches(t, period+" (nothing held)", econView(t, fx, c, "/fleet/economics", period), ref)
+ econViewCold(fx)
+ econMatches(t, period+" (settled days held)", econView(t, fx, c, "/fleet/economics/accounts", period), ref)
+ econAllCold(fx)
+ if err := fx.srv.statementsPass(context.Background(), time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ econMatches(t, period+" (after the pass)", econView(t, fx, c, "/fleet/economics", period), ref)
+ }
+}
+
+// TestEconomicsColdViewReadsOnlyUnsettledDays: the first cold view reads
+// every day of the period once; a second cold view reads today's and
+// yesterday's objects again and no settled day; and after the economics
+// pass, a cold month-to-date view on a console that had read nothing reads
+// only the unsettled days too.
+func TestEconomicsColdViewReadsOnlyUnsettledDays(t *testing.T) {
+ perfCaptureLogs(t)
+ fx, lat := newPerfFixture(t)
+ c := signInPaul(t, fx)
+ now := time.Now()
+ seedEconomicsDays(t, fx, econDates(now))
+ rec := recordS3(lat, nil)
+ // Per day: both platform boxes' rollups, box-a's edge day, pi-1's
+ // rollup, and the storage and census days.
+ const perDay = 6
+ for _, period := range []string{"mtd", "last", "7d"} {
+ dates := econPeriodDates(period, now)
+ unsettled := 0
+ for _, d := range dates {
+ if !usageDaySettled(d, now) {
+ unsettled++
+ }
+ }
+ econAllCold(fx)
+ rec.reset()
+ econView(t, fx, c, "/fleet/economics", period)
+ gets := econDayGets(rec)
+ if len(gets) != perDay*len(dates) {
+ t.Errorf("%s first cold view: %d day objects read, want %d (%d days)", period, len(gets), perDay*len(dates), len(dates))
+ }
+ for k, n := range gets {
+ if n > 1 {
+ t.Errorf("%s first cold view: %s read %d times", period, k, n)
+ }
+ }
+ econViewCold(fx)
+ rec.reset()
+ econView(t, fx, c, "/fleet/economics", period)
+ gets = econDayGets(rec)
+ for k := range gets {
+ if date, _ := usageDayDate(k); usageDaySettled(date, now) {
+ t.Errorf("%s second cold view: read settled %s again", period, k)
+ }
+ }
+ if len(gets) != perDay*unsettled {
+ t.Errorf("%s second cold view: %d day objects read, want %d (%d unsettled days):\n%v", period, len(gets), perDay*unsettled, unsettled, gets)
+ }
+ rec.reset()
+ econView(t, fx, c, "/fleet/economics/accounts", period)
+ if n := len(rec.all()); n != 0 {
+ t.Errorf("%s warm view: %d S3 requests, want 0", period, n)
+ }
+ }
+
+ econAllCold(fx)
+ if err := fx.srv.statementsPass(context.Background(), now); err != nil {
+ t.Fatal(err)
+ }
+ rec.reset()
+ econView(t, fx, c, "/fleet/economics", "mtd")
+ for k := range econDayGets(rec) {
+ if date, _ := usageDayDate(k); usageDaySettled(date, now) {
+ t.Errorf("cold view after the pass: read settled %s, which the pass had read", k)
+ }
+ }
+}
+
+// TestEconomicsRereadsUnsettledAndChangedDays: a change to today's or
+// yesterday's objects shows on the next cold view; a settled day is kept as
+// read until the economics pass reads it again, and the pass's copy shows
+// on the next cold view.
+func TestEconomicsRereadsUnsettledAndChangedDays(t *testing.T) {
+ perfCaptureLogs(t)
+ fx, _ := newPerfFixture(t)
+ c := signInPaul(t, fx)
+ now := time.Now()
+ dates := econDates(now)
+ seedEconomicsDays(t, fx, dates)
+ // "last" and "mtd" between them cover yesterday, today and settled
+ // days; each view is compared with the sequential sweep.
+ check := func(label string) {
+ t.Helper()
+ for _, period := range []string{"mtd", "last"} {
+ econViewCold(fx)
+ econMatches(t, label+" "+period, econView(t, fx, c, "/fleet/economics", period), econReference(t, fx, period, now))
+ }
+ }
+ check("before any change")
+
+ today, yesterday := dates[len(dates)-1], dates[len(dates)-2]
+ econPut(t, fx, today, 101)
+ econPut(t, fx, yesterday, 102)
+ check("today and yesterday changed")
+
+ // A settled day changed in the bucket (which its writers never do) is
+ // kept as read until the economics pass reads it again. The pass reads
+ // month to date, so take this month's first day when it is settled, and
+ // otherwise last month's, read by the pass as it ran at that month's end.
+ settled, period, passAt := dates[len(dates)-1][:8]+"01", "mtd", now
+ if !usageDaySettled(settled, now) {
+ settled, period = dates[0], "last"
+ d, _ := time.Parse("2006-01-02", settled)
+ passAt = time.Date(d.Year(), d.Month()+1, 0, 23, 0, 0, 0, time.UTC)
+ }
+ view := func() *EconomicsView {
+ t.Helper()
+ econViewCold(fx)
+ return econView(t, fx, c, "/fleet/economics", period)
+ }
+ before := view()
+ econPut(t, fx, settled, 103)
+ if after := view(); after.DataJSON != before.DataJSON {
+ t.Errorf("settled %s changed in the bucket: the cold view re-read it, want it kept until the pass reads it", settled)
+ }
+ if err := fx.srv.statementsPass(context.Background(), passAt); err != nil {
+ t.Fatal(err)
+ }
+ after := view()
+ if after.DataJSON == before.DataJSON {
+ t.Errorf("settled %s: the view after the pass still shows the copy from before it", settled)
+ }
+ econMatches(t, "after the pass read changed "+settled, after, econReference(t, fx, period, now))
+}
+
+// TestEconomicsOversizedUsageHoldsTheWindow: a box that writes many usage
+// objects far over the read cap costs a cold view no more than
+// readConcurrency times the cap held at once, however large the objects;
+// each is read no further than one byte past the cap and skipped as an
+// unreadable day is. A settled one is remembered as over the cap, so the
+// next cold view does not read it again, and the answer is the sequential
+// sweep's over the objects within the cap.
+func TestEconomicsOversizedUsageHoldsTheWindow(t *testing.T) {
+ perfCaptureLogs(t)
+ fx, lat := newPerfFixture(t)
+ c := signInPaul(t, fx)
+ ctx := context.Background()
+ now := time.Now()
+ seedEconomicsDays(t, fx, econDates(now))
+ prev := usageDayReadCap
+ usageDayReadCap = 64 << 10
+ t.Cleanup(func() { usageDayReadCap = prev })
+ ref := econReference(t, fx, "last", now)
+ if ref.err != nil {
+ t.Fatal(ref.err)
+ }
+ // Sixteen times the cap each, three windows' worth.
+ huge := int(16 * usageDayReadCap)
+ var floods []string
+ for _, date := range econPeriodDates("last", now) {
+ if len(floods) == 3*readConcurrency {
+ break
+ }
+ if !usageDaySettled(date, now) {
+ continue
+ }
+ raw, err := json.Marshal(econRollup("flood", date, fx.sqid, len(floods)))
+ if err != nil {
+ t.Fatal(err)
+ }
+ body := append(raw, []byte(strings.Repeat(" ", huge-len(raw)))...)
+ key := metrics.DayKey("flood", date)
+ if _, err := fx.rel.Put(ctx, key, body, ""); err != nil {
+ t.Fatal(err)
+ }
+ floods = append(floods, key)
+ }
+
+ from, to := economicsPeriodBounds("last", now)
+ attrib, _, err := fx.srv.loadAttributionForEconomics()
+ if err != nil {
+ t.Fatal(err)
+ }
+ // The console's bucket, instrumented: every read must stream (its Get
+ // fails the test), and each stream counts what it gave and its Close.
+ bucket := fx.srv.cfg.Releases
+ instrument := func(label string) *streamCountStore {
+ st := &streamCountStore{Store: bucket, t: t, label: label, consumed: map[string]int64{}}
+ fx.srv.cfg.Releases = st
+ return st
+ }
+ t.Cleanup(func() { fx.srv.cfg.Releases = bucket })
+ checkStreams := func(st *streamCountStore, keys []string) {
+ t.Helper()
+ for _, k := range keys {
+ if n := st.read(k); n > usageDayReadCap+1 || n == 0 {
+ t.Errorf("%s: over-cap %s gave %d bytes of its stream, want at most the cap and one byte (%d)", st.label, k, n, usageDayReadCap+1)
+ }
+ }
+ if opened, closed := st.counts(); opened == 0 || closed != opened {
+ t.Errorf("%s: %d streams opened, %d closed", st.label, opened, closed)
+ }
+ }
+
+ // The page's store streams a usage day itself (release.Opener), and
+ // stops one byte past the cap.
+ direct := instrument("a streaming open")
+ rc, _, err := release.OpenObjectStreaming(ctx, fx.srv.usageDayReader(now), floods[0])
+ if err != nil {
+ t.Fatalf("the page store does not stream a usage day: %v", err)
+ }
+ if _, err := io.Copy(io.Discard, rc); !errors.Is(err, errUsageDayTooLarge) {
+ t.Errorf("streaming over-cap %s: %v, want the cap's error", floods[0], err)
+ }
+ rc.Close()
+ checkStreams(direct, floods[:1])
+ econAllCold(fx)
+
+ // The concurrent page read.
+ page := instrument("the page read")
+ got, held := fx.srv.readEconomicsUsage(ctx, from, to, attrib, now)
+ if got.err != nil {
+ t.Fatal(got.err)
+ }
+ checkStreams(page, floods)
+
+ // The economics pass's sequential read, as statementsPass makes it.
+ pass := instrument("the pass read")
+ fill := fx.srv.usageDayFiller(now)
+ if sweep, err := fx.srv.sweepUsage(ctx, fill, from, to, attrib); err != nil {
+ t.Fatal(err)
+ } else if _, ok := sweep.PerBox["flood"]; ok {
+ t.Errorf("the pass counted an over-cap rollup")
+ }
+ checkStreams(pass, floods)
+ fx.srv.cfg.Releases = bucket
+ if bound := int64(readConcurrency) * usageDayReadCap; held.Peak > bound {
+ t.Errorf("the sweep held %d bytes at once, over %d (%d bodies at the cap)", held.Peak, bound, readConcurrency)
+ }
+ if held.Largest > usageDayReadCap {
+ t.Errorf("the sweep held a %d-byte body, over the %d-byte cap", held.Largest, usageDayReadCap)
+ }
+ if _, ok := got.sweep.PerBox["flood"]; ok {
+ t.Errorf("an over-cap rollup was counted: %v", got.sweep.PerBox["flood"])
+ }
+ for _, k := range floods {
+ e, ok := fx.srv.usageDays.get(k, now)
+ if !ok || !errors.Is(e.absent, errUsageDayTooLarge) || e.body != nil {
+ t.Errorf("%s: cache entry %v (held %v), want it remembered as over the cap, no body", k, e.absent, ok)
+ }
+ }
+ if _, bytes := fx.srv.usageDays.held(); bytes > usageDayCacheMaxBody {
+ t.Errorf("the cache holds %d bytes after a sweep of over-cap days", bytes)
+ }
+
+ rec := recordS3(lat, nil)
+ econViewCold(fx)
+ econMatches(t, "over-cap days", econView(t, fx, c, "/fleet/economics", "last"), ref)
+ gets := econDayGets(rec)
+ for _, k := range floods {
+ if gets[k] != 0 {
+ t.Errorf("cold view: over-cap %s read again %d times, want it remembered", k, gets[k])
+ }
+ }
+}
+
+// streamCountStore is a bucket every read of which must stream: its Get
+// fails the test, and each reader Open hands out counts the bytes it gave
+// and whether it was closed.
+type streamCountStore struct {
+ release.Store
+ t *testing.T
+ label string
+
+ mu sync.Mutex
+ consumed map[string]int64
+ opened, closed int
+}
+
+func (s *streamCountStore) Get(ctx context.Context, key string) ([]byte, string, error) {
+ s.t.Errorf("%s: Get(%s): a usage read buffered the object rather than streaming it", s.label, key)
+ return s.Store.Get(ctx, key)
+}
+
+func (s *streamCountStore) Open(ctx context.Context, key string) (io.ReadCloser, string, error) {
+ rc, etag, err := release.OpenObjectStreaming(ctx, s.Store, key)
+ if err != nil {
+ return nil, "", err
+ }
+ s.mu.Lock()
+ s.opened++
+ s.mu.Unlock()
+ return &countedStream{rc: rc, s: s, key: key}, etag, nil
+}
+
+func (s *streamCountStore) read(key string) int64 {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ return s.consumed[key]
+}
+
+func (s *streamCountStore) counts() (opened, closed int) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ return s.opened, s.closed
+}
+
+type countedStream struct {
+ rc io.ReadCloser
+ s *streamCountStore
+ key string
+ closed bool
+}
+
+func (c *countedStream) Read(p []byte) (int, error) {
+ n, err := c.rc.Read(p)
+ c.s.mu.Lock()
+ c.s.consumed[c.key] += int64(n)
+ c.s.mu.Unlock()
+ return n, err
+}
+
+func (c *countedStream) Close() error {
+ c.s.mu.Lock()
+ if !c.closed {
+ c.closed = true
+ c.s.closed++
+ }
+ c.s.mu.Unlock()
+ return c.rc.Close()
+}
+
+// TestEconomicsSweepPastItsDeadlineIsNotPublished: the scenario, its
+// listing and the bills answer at once while one usage day is held past
+// the sweep's deadline. The view fails with the deadline, as the reads one
+// after another did, and nothing is cached: the next view sweeps again.
+func TestEconomicsSweepPastItsDeadlineIsNotPublished(t *testing.T) {
+ perfCaptureLogs(t)
+ fx, lat := newPerfFixture(t)
+ c := signInPaul(t, fx)
+ now := time.Now()
+ dates := econDates(now)
+ seedEconomicsDays(t, fx, dates)
+ prev := economicsSweepTimeout
+ economicsSweepTimeout = 500 * time.Millisecond
+ t.Cleanup(func() { economicsSweepTimeout = prev })
+ held := metrics.DayKey("box-a", dates[len(dates)-1])
+ hold := make(chan struct{})
+ t.Cleanup(func() { close(hold) })
+ var metadata atomic.Int32
+ lat.Fake().OnRequest(func(r *http.Request) (int, <-chan struct{}) {
+ _, key, _ := strings.Cut(strings.TrimPrefix(r.URL.Path, "/"), "/")
+ if key == held {
+ return 0, hold
+ }
+ if strings.HasPrefix(key, "economics/") || r.URL.Query().Get("prefix") == economics.ScenariosPrefix {
+ metadata.Add(1)
+ }
+ return 0, nil
+ })
+ t.Cleanup(func() { lat.Fake().OnRequest(nil) })
+
+ econAllCold(fx)
+ start := time.Now()
+ _, err := fx.srv.LoadEconomics(context.Background(), "mtd")
+ if !errors.Is(err, context.DeadlineExceeded) {
+ t.Fatalf("LoadEconomics = %v, want the deadline", err)
+ }
+ if took := time.Since(start); took > 5*time.Second {
+ t.Errorf("the failed sweep took %v", took)
+ }
+ if metadata.Load() == 0 {
+ t.Errorf("no scenario or bill read: the test held the wrong request")
+ }
+ e := fx.srv.economicsCacheEntry("mtd")
+ e.mu.Lock()
+ cached := !e.at.IsZero() || e.view != nil
+ e.mu.Unlock()
+ if cached {
+ t.Errorf("a sweep past its deadline was cached")
+ }
+ if st, _, _ := get(t, c, fx.ts.URL+"/fleet/economics"); st != http.StatusInternalServerError {
+ t.Errorf("page = %d, want 500 while the day is held", st)
+ }
+}
+
+// TestEconomicsLateWriteAcrossTheMonthEnd: a device asleep across the month
+// end wakes on the 2nd and writes the 31st's last hours, and a box that had
+// written nothing for the 31st writes it. The console had already read the
+// 31st (settled since the 2nd began) and kept it. The hourly pass reads only
+// the new month, so the kept copy stands until it is usageDayMaxAge old;
+// the first sweep after that reads the 31st again and counts the late
+// hours.
+func TestEconomicsLateWriteAcrossTheMonthEnd(t *testing.T) {
+ perfCaptureLogs(t)
+ fx, _ := newPerfFixture(t)
+ ctx := context.Background()
+ woke := time.Date(2026, 11, 2, 10, 0, 0, 0, time.UTC)
+ const oct31 = "2026-10-31"
+ if !usageDaySettled(oct31, woke) {
+ t.Fatalf("%s is not settled at %v", oct31, woke)
+ }
+ hour := func(h int) time.Time { return time.Date(2026, 10, 31, h, 0, 0, 0, time.UTC) }
+ agg := metrics.HourAgg{Host: map[string]metrics.Agg{"cpu": {Avg: 0.5, N: 60}},
+ Units: map[string]map[string]metrics.Agg{"caddy.service": {"cpu": {Avg: 0.5, N: 60}}}}
+ if err := metrics.UpsertRollup(ctx, fx.rel, "box-a", hour(21), agg); err != nil {
+ t.Fatal(err)
+ }
+ attrib, _, err := fx.srv.loadAttributionForEconomics()
+ if err != nil {
+ t.Fatal(err)
+ }
+ hours := func(at time.Time) (a, b float64) {
+ t.Helper()
+ from, to := economicsPeriodBounds("last", at)
+ got, _ := fx.srv.readEconomicsUsage(ctx, from, to, attrib, at)
+ if got.err != nil {
+ t.Fatal(got.err)
+ }
+ return got.sweep.PerBox["box-a"].Hours, got.sweep.PerBox["box-b"].Hours
+ }
+ if a, b := hours(woke); a != 1 || b != 0 {
+ t.Fatalf("before the late writes: box-a %v hours, box-b %v, want 1 and 0", a, b)
+ }
+ // On the 2nd, the device writes the 31st's hours 22 and 23, and box-b
+ // its whole 31st.
+ for _, h := range []int{22, 23} {
+ if err := metrics.UpsertRollup(ctx, fx.rel, "box-a", hour(h), agg); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if err := metrics.UpsertRollup(ctx, fx.rel, "box-b", hour(12), agg); err != nil {
+ t.Fatal(err)
+ }
+ later := woke.Add(time.Hour)
+ if err := fx.srv.statementsPass(ctx, later); err != nil {
+ t.Fatal(err)
+ }
+ if a, b := hours(later); a != 1 || b != 0 {
+ t.Errorf("an hour later: box-a %v hours, box-b %v, want the kept 1 and 0 (within usageDayMaxAge)", a, b)
+ }
+ aged := woke.Add(usageDayMaxAge)
+ if a, b := hours(aged); a != 3 || b != 1 {
+ t.Errorf("usageDayMaxAge later: box-a %v hours, box-b %v, want the late writes, 3 and 1", a, b)
+ }
+}
+
+// TestEconomicsFailedReadsMatchTheSequentialSweep: a day object the bucket
+// refuses is skipped, as it was when the reads ran in sequence, and is not
+// remembered as absent: once the bucket answers, the next cold view reads
+// it. A refused box listing or bill fails the view, and when both fail the
+// listing's error is the one returned, as before.
+func TestEconomicsFailedReadsMatchTheSequentialSweep(t *testing.T) {
+ perfCaptureLogs(t)
+ fx, lat := newPerfFixture(t)
+ c := signInPaul(t, fx)
+ now := time.Now()
+ dates := econDates(now)
+ seedEconomicsDays(t, fx, dates)
+ refused := map[string]bool{
+ metrics.DayKey("box-a", dates[0]): true, // settled
+ usage.StorageDayKey(dates[1]): true, // settled, read twice per view
+ usage.EdgeDayKey("box-a", dates[len(dates)-1]): true, // today
+ }
+ failing := true
+ rec := recordS3(lat, func(q s3Req) bool { return failing && q.Method == http.MethodGet && refused[q.Key] })
+
+ for _, period := range []string{"last", "mtd"} {
+ ref := econReference(t, fx, period, now)
+ if ref.err != nil {
+ t.Fatal(ref.err)
+ }
+ econAllCold(fx)
+ econMatches(t, period+" (refused)", econView(t, fx, c, "/fleet/economics", period), ref)
+ econViewCold(fx)
+ econMatches(t, period+" (refused, settled days held)", econView(t, fx, c, "/fleet/economics", period), ref)
+ }
+ failing = false
+ rec.reset()
+ for _, period := range []string{"last", "mtd"} {
+ econViewCold(fx)
+ econMatches(t, period+" (answered)", econView(t, fx, c, "/fleet/economics", period), econReference(t, fx, period, now))
+ }
+ if n := econDayGets(rec)[metrics.DayKey("box-a", dates[0])]; n == 0 {
+ t.Errorf("the refused settled day was not read once the bucket answered")
+ }
+
+ // A refused listing or bill fails the view; the listing's error first.
+ month := usage.MonthOf(now.UTC())
+ for _, tc := range []struct {
+ name string
+ refuse func(q s3Req) bool
+ errPart string
+ }{
+ {"box listing", func(q s3Req) bool { return q.Key == "" && q.Prefix == metricsBoxesPrefix }, "sweep usage"},
+ {"bill", func(q s3Req) bool { return q.Key == economics.BillKey(month) }, "bill " + month},
+ {"listing and bill", func(q s3Req) bool {
+ return (q.Key == "" && q.Prefix == metricsBoxesPrefix) || q.Key == economics.BillKey(month)
+ }, "sweep usage"},
+ } {
+ recordS3(lat, tc.refuse)
+ econAllCold(fx)
+ _, err := fx.srv.LoadEconomics(context.Background(), "mtd")
+ if err == nil || !strings.Contains(err.Error(), "console: load economics: ") || !strings.Contains(err.Error(), tc.errPart) {
+ t.Errorf("%s refused: LoadEconomics = %v, want a load economics error naming %q", tc.name, err, tc.errPart)
+ }
+ econAllCold(fx)
+ if st, _, _ := get(t, c, fx.ts.URL+"/fleet/economics"); st != http.StatusInternalServerError {
+ t.Errorf("%s refused: page = %d, want 500", tc.name, st)
+ }
+ }
+ recordS3(lat, nil)
+}
+
+// TestEconomicsColdViewCounts pins the S3 requests a cold view makes over
+// the walk's own fixture (no usage seeded), and logs its time with the
+// walk's latency: nothing held, then the settled days held. Per day: both
+// platform boxes' rollups, pi-1's rollup, and the storage and census days
+// (five); per view: the two box listings, the active scenario, the
+// scenario listing and two bills (six).
+func TestEconomicsColdViewCounts(t *testing.T) {
+ perfCaptureLogs(t)
+ fx, lat := newPerfFixture(t)
+ c := signInPaul(t, fx)
+ now := time.Now()
+ for _, route := range []string{"/fleet/economics", "/fleet/economics/accounts"} {
+ for _, period := range []string{"mtd", "last"} {
+ dates := econPeriodDates(period, now)
+ unsettled := 0
+ for _, d := range dates {
+ if !usageDaySettled(d, now) {
+ unsettled++
+ }
+ }
+ path := route + "?period=" + period
+ for _, pass := range []struct {
+ name string
+ cold func(*consoleFixture)
+ want int
+ }{
+ {"nothing held", econAllCold, 6 + 5*len(dates)},
+ {"settled days held", econViewCold, 6 + 5*unsettled},
+ {"warm", func(*consoleFixture) {}, 0},
+ } {
+ pass.cold(fx)
+ lat.Enable(true)
+ r := perfOnce(fx, lat, c, perfTarget{Path: path, Expect: http.StatusOK}, func() { lat.Enable(false) })
+ if r.err != nil || r.status != http.StatusOK {
+ t.Fatalf("%s: %v %d", path, r.err, r.status)
+ }
+ if r.s3 != int64(pass.want) {
+ t.Errorf("%s (%s): %d S3 requests, want %d", path, pass.name, r.s3, pass.want)
+ }
+ t.Logf("%s (%s, %d days): %d S3 requests, first byte %v", path, pass.name, len(dates), r.s3, r.ttfb.Round(time.Millisecond))
+ }
+ }
+ }
+}
+
+// TestUsageDayDate: the cache knows exactly the five day-object families
+// the sweep reads, by their writers' key functions.
+func TestUsageDayDate(t *testing.T) {
+ const d = "2026-10-03"
+ for _, key := range []string{
+ metrics.DayKey("box-a", d), "fleets/fleet-a/" + metrics.DayKey("pi-1", d),
+ usage.EdgeDayKey("box-a", d), usage.StorageDayKey(d), usage.CensusDayKey(d),
+ } {
+ if got, ok := usageDayDate(key); !ok || got != d {
+ t.Errorf("usageDayDate(%q) = %q, %v; want %q", key, got, ok, d)
+ }
+ }
+ for _, key := range []string{
+ "metrics/boxes/box-a/raw/2026-10-03-09.json", "economics/bills/2026-10.json", "usage/storage/x/2026-10-03.json",
+ "fleets/metrics/boxes/pi/days/" + d + ".json", "metrics/boxes//days/" + d + ".json", "usage/census/2026-13-03.json",
+ "status/boxes/box-a.json",
+ } {
+ if got, ok := usageDayDate(key); ok {
+ t.Errorf("usageDayDate(%q) = %q, true; want not a day object", key, got)
+ }
+ }
+}
+
+// TestUsageDayCacheBounds: days outside the offered periods are dropped,
+// unsettled days and failed reads are never kept, and past the byte budget
+// the oldest days go first.
+func TestUsageDayCacheBounds(t *testing.T) {
+ now := time.Date(2026, 10, 27, 12, 0, 0, 0, time.UTC)
+ for date, want := range map[string]bool{"2026-10-25": true, "2026-10-26": false, "2026-10-27": false, "2026-09-01": true} {
+ if got := usageDaySettled(date, now); got != want {
+ t.Errorf("settled(%s) at %v = %v, want %v", date, now, got, want)
+ }
+ }
+ var c usageDayCache
+ c.put("usage/census/2026-08-31.json", "2026-08-31", []byte("{}"), "e", nil, now)
+ if n, _ := c.held(); n != 0 {
+ t.Errorf("kept a day before last month")
+ }
+ c.put("usage/census/2026-09-01.json", "2026-09-01", []byte("{}"), "e", nil, now)
+ c.put("usage/census/2026-09-02.json", "2026-09-02", nil, "", fmt.Errorf("refused"), now)
+ if n, _ := c.held(); n != 1 {
+ t.Errorf("held %d entries, want the one read (a refused read is not kept)", n)
+ }
+ c.prune(time.Date(2026, 11, 1, 0, 0, 0, 0, time.UTC))
+ if n, b := c.held(); n != 0 || b != 0 {
+ t.Errorf("after the month turned: %d entries, %d bytes, want none", n, b)
+ }
+ body := make([]byte, usageDayCacheMaxBody)
+ days := int(usageDayCacheMaxBytes/usageDayCacheMaxBody) + 3
+ start := time.Date(2026, 9, 1, 0, 0, 0, 0, time.UTC)
+ keys := map[string]string{}
+ for i := range days {
+ date := usage.DayOf(start.Add(time.Duration(i) * 24 * time.Hour / 2)) // two keys a day
+ key := fmt.Sprintf("metrics/boxes/b%d/days/%s.json", i, date)
+ keys[key] = date
+ c.put(key, date, body, "e", nil, now)
+ }
+ if _, b := c.held(); b > usageDayCacheMaxBytes {
+ t.Errorf("holds %d bytes, over the %d budget", b, usageDayCacheMaxBytes)
+ }
+ oldestKept := "9999"
+ for k := range maps.Keys(c.entries) {
+ oldestKept = min(oldestKept, c.entries[k].date)
+ }
+ for k, date := range keys {
+ if _, ok := c.get(k, now); !ok && date > oldestKept {
+ t.Errorf("dropped %s (%s) while keeping older %s", k, date, oldestKept)
+ }
+ }
+}
diff --git a/internal/console/economicsview.go b/internal/console/economicsview.go
index 24ff37471..9cf334bb5 100644
--- a/internal/console/economicsview.go
+++ b/internal/console/economicsview.go
@@ -34,9 +34,13 @@ import (
const (
economicsCacheTTL = 60 * time.Second
economicsStaleServeCeiling = 2 * time.Minute
- economicsSweepTimeout = 15 * time.Second
)
+// economicsSweepTimeout bounds one buildEconomicsView; a sweep that runs
+// out of it fails rather than publishing what it had read. A variable only
+// so a test can run out of it quickly.
+var economicsSweepTimeout = 15 * time.Second
+
// EconomicsView is one priced period, ready to render.
type EconomicsView struct {
GeneratedAt time.Time
@@ -414,13 +418,35 @@ func (s *Server) buildEconomicsView(ctx context.Context, period string) (*Econom
return nil, fmt.Errorf("console: load economics: %w", err)
}
- sweep, err := s.sweepUsage(sweepCtx, from, to, attrib)
- if err != nil {
- return nil, fmt.Errorf("console: load economics: %w", err)
- }
- if err := s.foldStorageAndCensus(sweepCtx, from, to, sweep.PerAccount); err != nil {
+ // The period's usage days, the active scenario, the scenario names and
+ // the bills are read at once; their errors are then taken in the order
+ // they were met when the reads ran one after another, so a failed view
+ // fails with the same error.
+ var (
+ used economicsUsage
+ sc economics.Scenario
+ scenarioWarning string
+ scenarioNames []string
+ namesErr error
+ bills []economics.Bill
+ billsErr error
+ )
+ runConcurrently(
+ func() { used, _ = s.readEconomicsUsage(sweepCtx, from, to, attrib, now) },
+ func() { sc, scenarioWarning = s.loadActiveScenario(sweepCtx) },
+ func() { scenarioNames, namesErr = s.listScenarioNames(sweepCtx) },
+ func() { bills, billsErr = s.loadRecentBills(sweepCtx, now) },
+ )
+ if used.err != nil {
+ return nil, fmt.Errorf("console: load economics: %w", used.err)
+ }
+ // Every read above that met the deadline failed, and the ones that
+ // skip a failure (the fleet meters, the scenario) would leave a partial
+ // view: a view past its deadline is never published or cached.
+ if err := sweepCtx.Err(); err != nil {
return nil, fmt.Errorf("console: load economics: %w", err)
}
+ sweep := used.sweep
// Fleet meters (Task 3's fleetMeters) fold into sweep.PerAccount exactly
// like statementsPass's own union merge (economicspass.go) — an account
@@ -440,7 +466,7 @@ func (s *Server) buildEconomicsView(ctx context.Context, period string) (*Econom
// TWO banners for the SAME missing registry (loadAttributionForEconomics's
// and this one, since fleetMeters opens that identical registry) — see
// the warning=="" guard below, which keeps it to one banner, one cause.
- if fleetMM, ferr := s.fleetMeters(sweepCtx, from, to); ferr != nil {
+ if fleetMM, ferr := used.fleet, used.fleetErr; ferr != nil {
log.Printf("console: load economics: fleet meters unavailable: %v", ferr)
// Suppress a second banner when routes are ALREADY degraded
// (warning != "" here can only mean loadAttributionForEconomics found no
@@ -464,11 +490,8 @@ func (s *Server) buildEconomicsView(ctx context.Context, period string) (*Econom
}
}
- sc, scenarioWarning := s.loadActiveScenario(sweepCtx)
-
- scenarioNames, err := s.listScenarioNames(sweepCtx)
- if err != nil {
- return nil, fmt.Errorf("console: load economics: %w", err)
+ if namesErr != nil {
+ return nil, fmt.Errorf("console: load economics: %w", namesErr)
}
// Union of accounts to price: every account with usage this period plus
@@ -619,9 +642,8 @@ func (s *Server) buildEconomicsView(ctx context.Context, period string) (*Econom
}
sort.Slice(boxRows, func(i, j int) bool { return boxRows[i].Box < boxRows[j].Box })
- bills, err := s.loadRecentBills(sweepCtx, now)
- if err != nil {
- return nil, fmt.Errorf("console: load economics: %w", err)
+ if billsErr != nil {
+ return nil, fmt.Errorf("console: load economics: %w", billsErr)
}
payload := economicsPayload{
diff --git a/internal/console/hotreads.go b/internal/console/hotreads.go
index 61aee5c42..3293de797 100644
--- a/internal/console/hotreads.go
+++ b/internal/console/hotreads.go
@@ -104,6 +104,7 @@ type prefetchStore struct {
mu sync.Mutex
dry bool
lists map[string]listed
+ dirs map[string]listed
mods map[string]listedMod
asked []string
pending map[string]*pendingGet
@@ -159,6 +160,23 @@ func (p *prefetchStore) List(ctx context.Context, prefix string) ([]string, erro
return slices.Clone(l.keys), l.err
}
+// ListDirs is List's twin for a reader that discovers its keys a level at
+// a time (the economics sweep's boxes): each prefix is listed once, by the
+// dry pass, and the real pass gets the same answer.
+func (p *prefetchStore) ListDirs(ctx context.Context, prefix string) ([]string, error) {
+ p.mu.Lock()
+ l, ok := p.dirs[prefix]
+ p.mu.Unlock()
+ if !ok {
+ dirs, err := p.Store.ListDirs(ctx, prefix)
+ l = listed{keys: dirs, err: err}
+ p.mu.Lock()
+ p.dirs[prefix] = l
+ p.mu.Unlock()
+ }
+ return slices.Clone(l.keys), l.err
+}
+
func (p *prefetchStore) ListMod(ctx context.Context, prefix string) ([]release.KeyMod, error) {
p.mu.Lock()
l, ok := p.mods[prefix]
@@ -299,7 +317,7 @@ func readConcurrently[T any](ctx context.Context, st release.Store, dryBody []by
// readConcurrentlyStats is readConcurrently, and what it held.
func readConcurrentlyStats[T any](ctx context.Context, st release.Store, dryBody []byte, limit func(key string) int64, read func(release.Store) T) (T, prefetchStats) {
p := &prefetchStore{Store: st, dryBody: dryBody, limit: limit, dry: true,
- lists: map[string]listed{}, mods: map[string]listedMod{}, pending: map[string]*pendingGet{},
+ lists: map[string]listed{}, dirs: map[string]listed{}, mods: map[string]listedMod{}, pending: map[string]*pendingGet{},
window: make(chan struct{}, readConcurrency)}
read(p)
p.mu.Lock()
diff --git a/internal/console/server.go b/internal/console/server.go
index 1e287daba..2d8d88c22 100644
--- a/internal/console/server.go
+++ b/internal/console/server.go
@@ -1165,6 +1165,10 @@ type Server struct {
// keyed by period so a cold sweep for one period never blocks a caller
// asking for another.
economicsCache economicsCache
+ // usageDays holds the settled usage day objects the economics sweep
+ // reads (usagedays.go), so a cold view reads only today and yesterday;
+ // the hourly economics pass fills it as it reads.
+ usageDays usageDayCache
// storeSizer is the storage pass's test seam for sizing a provisioned
// tenant object store: nil means "use the real S3 sizer"
// (sizeProvisionedStore, economicspass.go); tests inject a fake so a
diff --git a/internal/console/testdata/perf-budgets.txt b/internal/console/testdata/perf-budgets.txt
index 9c400c386..075ffb746 100644
--- a/internal/console/testdata/perf-budgets.txt
+++ b/internal/console/testdata/perf-budgets.txt
@@ -74,7 +74,7 @@ GET /a/{sqid}/settings calls 2: the account telemetry settings and the storage e
GET /a/{sqid}/trash over: reads each trashed app's deleted.json marker (1 S3 call warm and cold per app)
GET /fleet over: the dashboard reads status/fleet.json, lists and reads every box report once each, and for a store operator lists and reads the storage entitlements, the same reads Boxes makes, all at once; operator pages are seldom viewed and carry no cache, and its SQLite reads add no remote call (12 S3 calls warm and cold, median about 133 ms, inside the budget; kept out of the timed walk, whose eleven views of it would cost 1.5 s of the walk's 10 s)
GET /fleet/boxes over: lists and reads every box report, reads status/fleet.json, and lists and reads the storage entitlements, all at once; operator pages are seldom viewed and carry no cache (12 S3 calls warm and cold, median about 133 ms, inside the budget; kept out of the timed walk as Dashboard is)
-GET /fleet/economics over: the cold view sweeps usage for every day of the period (162 S3 calls, about 4.1 s); warm views come from the 60 s cache (0 S3 calls)
-GET /fleet/economics/accounts over: shares /fleet/economics's sweep cache, so its own cold view is that same sweep (0 S3 calls warm)
+GET /fleet/economics over: a cold view reads the period's usage days ten at a time, each no further than 8 MiB, and keeps the settled ones, every day before yesterday, for up to 6 h (console-economics-speed); month to date on the 27th, five objects a day and six more: 141 S3 calls, about 400 ms, with nothing held (was 168 one after another, about 4.3 s); 16 S3 calls, about 110 ms, once a view or the hourly economics pass has read the settled days; warm views come from the 60 s cache (0 S3 calls)
+GET /fleet/economics/accounts over: shares /fleet/economics's sweep and its settled days, so its own cold view is that same sweep (141 S3 calls with nothing held, 16 with the settled days held, on the 27th); 0 S3 calls warm
GET /fleet/metrics over: a cold view reads every box's metrics hours for two days (about 120 S3 calls, counted in Overview's cold view); warm views are cached (0 S3 calls), and the walk never sees it cold: the app pages before it fill that cache and perfColdReset leaves it
GET /fleet/store over: lists the storage entitlements and the storage usage days and reads each pending application (3 S3 calls warm and cold, median about 80 ms)
diff --git a/internal/console/usageattrib_tags_test.go b/internal/console/usageattrib_tags_test.go
index d025d349c..73d74f09e 100644
--- a/internal/console/usageattrib_tags_test.go
+++ b/internal/console/usageattrib_tags_test.go
@@ -64,7 +64,7 @@ func TestUsageTaggedCustomDomainCounted(t *testing.T) {
if err != nil {
t.Fatal(err)
}
- sweep, err := tb.fx.srv.sweepUsage(context.Background(), hours[0], hours[3], attrib)
+ sweep, err := tb.fx.srv.sweepUsage(context.Background(), tb.fx.srv.cfg.Releases, hours[0], hours[3], attrib)
if err != nil {
t.Fatal(err)
}
@@ -140,7 +140,7 @@ func TestUsageTaggedReusedHostname(t *testing.T) {
if err != nil {
t.Fatal(err)
}
- sweep, err := fx.srv.sweepUsage(ctx, era[0], era[1].Add(time.Hour), attrib)
+ sweep, err := fx.srv.sweepUsage(ctx, fx.srv.cfg.Releases, era[0], era[1].Add(time.Hour), attrib)
if err != nil {
t.Fatal(err)
}
diff --git a/internal/console/usageattrib_test.go b/internal/console/usageattrib_test.go
index 7838ffe91..53dd83c5f 100644
--- a/internal/console/usageattrib_test.go
+++ b/internal/console/usageattrib_test.go
@@ -287,7 +287,7 @@ func TestUsageReusedHostname(t *testing.T) {
if err != nil {
t.Fatal(err)
}
- sweep, err := fx.srv.sweepUsage(ctx, era[0], era[3], attrib)
+ sweep, err := fx.srv.sweepUsage(ctx, fx.srv.cfg.Releases, era[0], era[3], attrib)
if err != nil {
t.Fatal(err)
}
diff --git a/internal/console/usagedays.go b/internal/console/usagedays.go
new file mode 100644
index 000000000..353bfafba
--- /dev/null
+++ b/internal/console/usagedays.go
@@ -0,0 +1,506 @@
+package console
+
+import (
+ "bytes"
+ "context"
+ "errors"
+ "fmt"
+ "io"
+ "log"
+ "os"
+ "strings"
+ "sync"
+ "time"
+
+ "github.com/carlosframework/platform/internal/metrics"
+ "github.com/carlosframework/platform/internal/release"
+ "github.com/carlosframework/platform/internal/usage"
+)
+
+// The economics sweep's per-day usage objects (console-economics-speed).
+// /fleet/economics prices a period by reading every day of it: each box's
+// metrics rollup and edge day, each fleet box's rollup, and the day's
+// storage and census objects. An operator page is viewed seldom, so nearly
+// every view missed the 60 s view cache and read the whole period one
+// object after another. Two changes:
+//
+// - A view reads the period's objects concurrently (readConcurrently,
+// hotreads.go): readConcurrency at a time, with no more than that many
+// bodies held at once, and the same answer, since the sweep's own code
+// decides on exactly the bytes it read before.
+// - Settled days are kept across views. A day's objects stop changing a
+// known time after the day ends (usageDaySettled), so a day before that
+// horizon is read once and kept for up to usageDayMaxAge; today and
+// yesterday are read on every cold view.
+//
+// Every usage object is read streaming and no further than usageDayReadCap
+// and one byte (a box writes what it likes under its own prefix): an object
+// over the cap is skipped as an unreadable day is, and logged.
+//
+// The hourly economics pass (statementsPass) already reads every day of the
+// month to date from the bucket. It keeps reading them all, and leaves each
+// settled day it read in the same cache (usageDayFiller), so the page's
+// next cold view finds the month's settled days held and reads only today
+// and yesterday. That adds no request.
+
+// The cache's bounds. A body over usageDayCacheMaxBody is read on every
+// view and never kept; the whole cache holds at most usageDayCacheMaxBytes,
+// counting usageDayEntryOverhead and the key for every entry, a remembered
+// absence included. Past the budget the oldest days go first: month to
+// date, the page's default, is the last to lose its days. An entry is
+// trusted for usageDayMaxAge after it was read, then read again.
+const (
+ usageDayCacheMaxBody = 1 << 20
+ usageDayCacheMaxBytes = 64 << 20
+ usageDayEntryOverhead = 64
+ usageDayMaxAge = 6 * time.Hour
+)
+
+// usageDayReadCap is the most bytes the console reads of one usage day
+// object; past it the object is skipped. A day rollup indented as the box
+// agent writes it is about 23 KB per instance (cpu and memory, tagged with
+// its tenant) and an edge day about 5 KB per host, so 8 MiB holds a box
+// running some 350 instances, or serving some 1,600 hosts, all day: well
+// past any box today. Ten reads at a time (readConcurrency) hold at most
+// 80 MiB. A variable only so a test can show the bound with small objects.
+var usageDayReadCap int64 = 8 << 20
+
+// errUsageDayTooLarge is the read error of a usage day object over
+// usageDayReadCap. The sweep skips it as it skips any day it cannot read.
+var errUsageDayTooLarge = errors.New("console: usage day object over the read cap")
+
+// usageDayEntry is one settled day object read at at: its body and ETag,
+// or the error the read gave and will give again for the same object (it
+// does not exist, os.ErrNotExist, or it is over the cap,
+// errUsageDayTooLarge), returned again as it was.
+type usageDayEntry struct {
+ date string
+ at time.Time
+ body []byte
+ etag string
+ absent error
+}
+
+func (e usageDayEntry) size(key string) int64 {
+ return int64(len(key) + len(e.body) + len(e.etag) + usageDayEntryOverhead)
+}
+
+// usageDayCache holds settled day objects by key, for the days the page
+// can show: the first of last month (the "last" period's first day; "7d"
+// never reaches further back) up to the day before yesterday. Days that
+// leave that window are dropped by prune, which every view and every pass
+// runs first.
+type usageDayCache struct {
+ mu sync.Mutex
+ entries map[string]usageDayEntry
+ bytes int64
+}
+
+// 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
+// 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) {
+ rest, ok := strings.CutSuffix(key, ".json")
+ if !ok {
+ return "", false
+ }
+ i := strings.LastIndexByte(rest, '/')
+ if i < 0 {
+ return "", false
+ }
+ date = rest[i+1:]
+ if _, err := time.Parse("2006-01-02", date); err != nil {
+ return "", false
+ }
+ if key == usage.StorageDayKey(date) || key == usage.CensusDayKey(date) {
+ return date, true
+ }
+ dir := rest[:i]
+ if fleetRest, ok := strings.CutPrefix(dir, "fleets/"); ok {
+ j := strings.IndexByte(fleetRest, '/')
+ 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)
+ }
+ if box, ok := daysDirBox(dir, "metrics/boxes/"); ok {
+ return date, key == metrics.DayKey(box, date)
+ }
+ if box, ok := daysDirBox(dir, usage.EdgeBoxesPrefix); ok {
+ return date, key == usage.EdgeDayKey(box, date)
+ }
+ return "", false
+}
+
+// daysDirBox is the box of a "<prefix><box>/days" directory.
+func daysDirBox(dir, prefix string) (string, bool) {
+ rest, ok := strings.CutPrefix(dir, prefix)
+ if !ok {
+ return "", false
+ }
+ box, ok := strings.CutSuffix(rest, "/days")
+ return box, ok && box != "" && !strings.Contains(box, "/")
+}
+
+// usageDaySettled reports whether date's objects have stopped changing by
+// now: true from the start of the second UTC day after it (date+2 00:00),
+// so today and yesterday are never settled. The writers bound a day's last
+// write well inside that:
+//
+// - A box's metrics rollup (and a fleet box's, the same agent under its
+// fleet's prefix) is written when an hour closes: metricsFlush rolls up
+// every hour older than the current one still in its buffer
+// (internal/host/metrics_loop.go:221-245), and that buffer holds at most
+// samplerMaxBuf (120) one-minute samples, about two hours of a running
+// box (metrics_loop.go:44, the cap enforced in tick, :148-152). The
+// restart repair backfillPrevHourRollup rolls up only the hour before
+// the process started (metrics_loop.go:291-322). So the last write to a
+// day lands about two hours after it ends, plus a five-minute flush.
+// The cap counts samples, not their age: a box suspended with samples
+// in its buffer (a device asleep across a month end, say) writes them
+// to their old day when it wakes, however late. usageDayMaxAge is what
+// brings such a write to the page.
+// - A box's edge day takes deltas for the day the flush runs in, never an
+// earlier one (usage.UpsertEdgeDay, internal/usage/edge.go:117-122,
+// called every five minutes with time.Now(), internal/host/usage_loop.go).
+// - The storage and census days are create-only (usage.CreateDayObject)
+// and written only for the day the pass runs in
+// (internal/console/economicspass.go censusPass and storagePass).
+//
+// A day becomes settled at least 24 hours after its end, past all of these
+// with a day's margin for clock skew and retries. A late write past that
+// (a suspended box, a box whose clock was wrong) is not caught by the
+// horizon: a kept day is read again once it is usageDayMaxAge old, and the
+// hourly pass reads every day of the month to date again, so such a write
+// shows within six hours, within an hour for this month's days. The sweep
+// lists only the box prefixes, never the day objects, so there is no
+// listing ETag to check a kept day against without a request.
+func usageDaySettled(date string, now time.Time) bool {
+ d, err := time.Parse("2006-01-02", date)
+ if err != nil {
+ return false
+ }
+ today := now.UTC().Truncate(24 * time.Hour)
+ return !d.After(today.AddDate(0, 0, -2))
+}
+
+// usageDayFirstKept is the oldest date the cache keeps at now: the first of
+// last month, the oldest day any period the page offers starts on.
+func usageDayFirstKept(now time.Time) string {
+ now = now.UTC()
+ first := time.Date(now.Year(), now.Month(), 1, 0, 0, 0, 0, time.UTC)
+ return usage.DayOf(first.AddDate(0, -1, 0))
+}
+
+// get is key's entry, when it was read less than usageDayMaxAge before now.
+func (c *usageDayCache) get(key string, now time.Time) (usageDayEntry, bool) {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ e, ok := c.entries[key]
+ if !ok || now.Sub(e.at) >= usageDayMaxAge {
+ return usageDayEntry{}, false
+ }
+ return e, true
+}
+
+// put keeps one settled read, made at now: a body no larger than
+// usageDayCacheMaxBody (put keeps it; the caller must not change it), a
+// not-found or an object over the read cap. Any other error says nothing
+// about the day and changes nothing; tooBig (a body read whole but too
+// large to keep) drops a copy held from before. Past the budget, the
+// oldest days are dropped first, which may be this one.
+func (c *usageDayCache) put(key, date string, body []byte, etag string, err error, now time.Time) {
+ var e usageDayEntry
+ switch {
+ case err == nil:
+ e = usageDayEntry{date: date, at: now, body: body, etag: etag}
+ case errors.Is(err, errUsageDayTooBigToKeep):
+ c.mu.Lock()
+ c.dropLocked(key)
+ c.mu.Unlock()
+ return
+ case errors.Is(err, os.ErrNotExist), errors.Is(err, errUsageDayTooLarge):
+ e = usageDayEntry{date: date, at: now, absent: err}
+ default:
+ return
+ }
+ if date < usageDayFirstKept(now) {
+ return
+ }
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ if c.entries == nil {
+ c.entries = map[string]usageDayEntry{}
+ }
+ c.dropLocked(key)
+ c.entries[key] = e
+ c.bytes += e.size(key)
+ for c.bytes > usageDayCacheMaxBytes {
+ oldest := ""
+ for k, o := range c.entries {
+ if oldest == "" || o.date < c.entries[oldest].date || (o.date == c.entries[oldest].date && k < oldest) {
+ oldest = k
+ }
+ }
+ c.dropLocked(oldest)
+ }
+}
+
+func (c *usageDayCache) dropLocked(key string) {
+ if e, ok := c.entries[key]; ok {
+ c.bytes -= e.size(key)
+ delete(c.entries, key)
+ }
+}
+
+// prune drops the days no period the page offers can show any more.
+func (c *usageDayCache) prune(now time.Time) {
+ first := usageDayFirstKept(now)
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ for k, e := range c.entries {
+ if e.date < first {
+ c.dropLocked(k)
+ }
+ }
+}
+
+// held is the cache's entry count and bytes, for the tests.
+func (c *usageDayCache) held() (n int, bytes int64) {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ return len(c.entries), c.bytes
+}
+
+// usageDayStore reads usage day objects through the settled-day cache.
+// Every other request passes through to the store untouched, Open included.
+//
+// A usage day object is read streaming (Open) and no further than
+// usageDayReadCap and one byte. While it is read, a copy is kept of a body
+// no larger than usageDayCacheMaxBody for the cache; a larger one is only
+// passed on. So one read holds at most the body its reader takes, plus a
+// copy of at most usageDayCacheMaxBody.
+//
+// A page view's store (use true) answers a settled day from the cache when
+// it holds a read younger than usageDayMaxAge, and keeps each settled day it
+// reads. Today's and yesterday's storage days are read once per view rather
+// than twice (sweepUsage reads them for coverage and foldStorageAndCensus
+// for bytes): at most two bodies, each no larger than usageDayCacheMaxBody,
+// held for the view.
+//
+// The economics pass's store (use false) reads everything from the bucket
+// and keeps each settled day it read, replacing what was held: so a day the
+// pass has read is never older than the pass.
+type usageDayStore struct {
+ release.Store
+ cache *usageDayCache
+ now time.Time
+ use bool
+
+ mu sync.Mutex
+ view map[string]fetched
+}
+
+// errUsageDayTooBigToKeep is what a read leaves for the cache when it read
+// a body whole that is too large to keep: drop any copy held from before.
+var errUsageDayTooBigToKeep = errors.New("console: usage day object too large to keep")
+
+// usageDayReader is a page view's store over the cache, at now.
+func (s *Server) usageDayReader(now time.Time) *usageDayStore {
+ s.usageDays.prune(now)
+ return &usageDayStore{Store: s.cfg.Releases, cache: &s.usageDays, now: now, use: true, view: map[string]fetched{}}
+}
+
+// usageDayFiller is the economics pass's store: it reads the bucket and
+// fills the cache.
+func (s *Server) usageDayFiller(now time.Time) *usageDayStore {
+ s.usageDays.prune(now)
+ return &usageDayStore{Store: s.cfg.Releases, cache: &s.usageDays, now: now}
+}
+
+// usageDayLimit is readConcurrently's limit for the economics sweep: the
+// read cap for a usage day object, none for anything else.
+func usageDayLimit(key string) int64 {
+ if _, ok := usageDayDate(key); ok {
+ return usageDayReadCap
+ }
+ return 0
+}
+
+// Get is Open read whole: for a usage day object, no further than the cap.
+func (d *usageDayStore) Get(ctx context.Context, key string) ([]byte, string, error) {
+ if _, ok := usageDayDate(key); !ok {
+ return d.Store.Get(ctx, key)
+ }
+ rc, etag, err := d.open(ctx, key)
+ if err != nil {
+ return nil, "", err
+ }
+ defer rc.Close()
+ body, err := io.ReadAll(rc)
+ if err != nil {
+ return nil, "", err
+ }
+ return body, etag, nil
+}
+
+// Open streams key (release.Opener). A usage day object comes from the
+// cache when it holds it, and otherwise from the store through a
+// usageDayRead.
+func (d *usageDayStore) Open(ctx context.Context, key string) (io.ReadCloser, string, error) {
+ return d.open(ctx, key)
+}
+
+// open is Open, under a name of its own: the claim authority census
+// (claim_authority_census_test.go) reviews every call of a method named
+// Open, and this one opens nothing but a read.
+func (d *usageDayStore) open(ctx context.Context, key string) (io.ReadCloser, string, error) {
+ date, ok := usageDayDate(key)
+ if !ok {
+ return release.OpenObject(ctx, d.Store, key)
+ }
+ settled := usageDaySettled(date, d.now)
+ if settled && d.use {
+ if e, hit := d.cache.get(key, d.now); hit {
+ if e.absent != nil {
+ return nil, "", e.absent
+ }
+ return io.NopCloser(bytes.NewReader(e.body)), e.etag, nil
+ }
+ }
+ once := d.use && !settled && key == usage.StorageDayKey(date)
+ if once {
+ d.mu.Lock()
+ f, seen := d.view[key]
+ d.mu.Unlock()
+ if seen {
+ if f.err != nil {
+ return nil, "", f.err
+ }
+ return io.NopCloser(bytes.NewReader(f.body)), f.etag, nil
+ }
+ }
+ // keep takes what a finished read leaves behind: a body small enough to
+ // keep, or an error that will be the same next time.
+ keep := func(body []byte, etag string, err error) {
+ if settled {
+ d.cache.put(key, date, body, etag, err, d.now)
+ }
+ if once && (err == nil || errors.Is(err, os.ErrNotExist) || errors.Is(err, errUsageDayTooLarge)) {
+ d.mu.Lock()
+ d.view[key] = fetched{body: body, etag: etag, err: err}
+ d.mu.Unlock()
+ }
+ }
+ rc, etag, err := release.OpenObject(ctx, d.Store, key)
+ if err != nil {
+ keep(nil, "", err)
+ return nil, "", err
+ }
+ return &usageDayRead{ctx: ctx, rc: rc, key: key, etag: etag, keeping: settled || once, keep: keep}, etag, nil
+}
+
+// usageDayRead is one usage day object streaming from the store. It never
+// asks for more than one byte past usageDayReadCap, and fails with
+// errUsageDayTooLarge once that byte has come. While the body is no larger
+// than usageDayCacheMaxBody it keeps a copy for the cache. When the read
+// ends, at the end of the body or at the cap, it hands keep the copy or
+// the error, once.
+type usageDayRead struct {
+ ctx context.Context
+ rc io.ReadCloser
+ key string
+ etag string
+ n int64
+ copy []byte
+ keeping bool
+ done bool
+ keep func(body []byte, etag string, err error)
+}
+
+func (r *usageDayRead) Read(p []byte) (int, error) {
+ if r.n > usageDayReadCap {
+ return 0, fmt.Errorf("%s: %w", r.key, errUsageDayTooLarge)
+ }
+ if room := usageDayReadCap + 1 - r.n; int64(len(p)) > room {
+ p = p[:room]
+ }
+ n, err := r.rc.Read(p)
+ r.n += int64(n)
+ if r.keeping {
+ if int64(len(r.copy)+n) > usageDayCacheMaxBody {
+ r.keeping, r.copy = false, nil
+ } else {
+ r.copy = append(r.copy, p[:n]...)
+ }
+ }
+ if r.n > usageDayReadCap {
+ tooLarge := fmt.Errorf("%s: %w", r.key, errUsageDayTooLarge)
+ if !r.done {
+ r.done = true
+ log.Printf("console: sweep usage: %s is over %d bytes; skipped like an unreadable day", r.key, usageDayReadCap)
+ jobFailed(r.ctx, fmt.Errorf("sweep usage: %w", tooLarge))
+ r.keep(nil, "", tooLarge)
+ }
+ return n, tooLarge
+ }
+ if err == io.EOF && !r.done {
+ r.done = true
+ if r.keeping {
+ if r.copy == nil {
+ r.copy = []byte{}
+ }
+ r.keep(r.copy, r.etag, nil)
+ } else {
+ r.keep(nil, "", errUsageDayTooBigToKeep)
+ }
+ }
+ return n, err
+}
+
+func (r *usageDayRead) Close() error { return r.rc.Close() }
+
+// economicsUsage is what the dashboard reads per day for one period: the
+// sweep with storage and census folded in (or the error either returned),
+// and the fleet meters (or the error that degrades them to a warning).
+type economicsUsage struct {
+ sweep *usageSweep
+ err error
+ fleet map[string]map[string]float64
+ fleetErr error
+}
+
+// readEconomicsUsage is buildEconomicsView's per-day read: sweepUsage,
+// foldStorageAndCensus and fleetMeters, in that order, over a page view's
+// cache store, read concurrently. The registry is asked once, before.
+func (s *Server) readEconomicsUsage(ctx context.Context, from, to time.Time, attrib *usageAttribution, now time.Time) (economicsUsage, prefetchStats) {
+ boxes, boxesErr := s.fleetMeterBoxes()
+ st := s.usageDayReader(now)
+ // "{}" decodes to an empty rollup, edge, storage and census day, which
+ // every reader here takes without a word.
+ out, held := readConcurrentlyStats(ctx, st, []byte("{}"), usageDayLimit, func(rs release.Store) economicsUsage {
+ sweep, err := s.sweepUsage(ctx, rs, from, to, attrib)
+ if err != nil {
+ return economicsUsage{err: err}
+ }
+ if err := s.foldStorageAndCensus(ctx, rs, from, to, sweep.PerAccount); err != nil {
+ return economicsUsage{err: err}
+ }
+ out := economicsUsage{sweep: sweep, fleetErr: boxesErr}
+ if boxesErr == nil {
+ out.fleet = fleetMetersFrom(ctx, rs, boxes, from, to)
+ }
+ return out
+ })
+ // The sweep skips a day it cannot read, and a read cut off by the
+ // deadline is one: a sweep that ran out of time is a failed sweep, never
+ // partial totals.
+ if err := ctx.Err(); err != nil && out.err == nil {
+ out = economicsUsage{err: fmt.Errorf("console: sweep usage: %w", err)}
+ }
+ return out, held
+}