console: the operator dashboard
GET /fleet is now the dashboard (opdashboard.go, ops_dashboard.html), the approved mockup top to bottom: the needs-attention callout judged from the very Boxes rows the page renders, the headline band, 30 days of new people with a hidden table, newest people, latest activity, boxes with a memory meter, and the background jobs. It reads what Boxes reads, each once (8 S3 calls, over: record rewritten); SQLite failures empty their section and a bucket failure degrades, never a 500. The walk now runs over populated operator tables (seedOperatorScale).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
17 files changed,
+1,416
−19
.amadan/test-weights.tsv+1 −0approved_operator_pages_copy_test.go+9 −0internal/console/accountfleet.go+1 −1internal/console/claim_invariant_fixtures_test.go+1 −1internal/console/claim_invariant_probes_read_test.go+1 −1internal/console/economicspass.go+1 −1internal/console/fleets.go+1 −1internal/console/jobs_test.go+15 −1internal/console/opdashboard.go+405 −0internal/console/opdashboard_test.go+856 −0internal/console/opshell_test.go+0 −1internal/console/perfquickwins_test.go+2 −0internal/console/perfwalk_test.go+3 −0internal/console/server.go+7 −11internal/console/static/ops.css+33 −0internal/console/templates/ops_dashboard.html+79 −0internal/console/testdata/perf-budgets.txt+1 −1
diff --git a/.amadan/test-weights.tsv b/.amadan/test-weights.tsv| index 4a665b859..1533968c1 100644 |
| --- a/.amadan/test-weights.tsv |
| +++ b/.amadan/test-weights.tsv |
| @@ -40,6 +40,7 @@ github.com/carlosframework/platform TestDBForwardPullSavesNothingForABadAnswer 1 |
| github.com/carlosframework/platform TestPlan13NoDirectPlacementEngineComparison 1.70 |
| github.com/carlosframework/platform TestE2EDBThroughConsole 1.49 |
| github.com/carlosframework/platform TestWatchRolloutListFailuresTimeOutNamingTheList 1.20 |
| +github.com/carlosframework/platform/internal/console TestDashboardRemoteReadsAreTheDeclaredOnes 1.11 |
| github.com/carlosframework/platform TestAuthLoginDenied 1.00 |
| github.com/carlosframework/platform TestDBForwardPullOnAQueryOnlyConsole 0.97 |
| github.com/carlosframework/platform TestDeployWatchReadsTheConsolesList 0.90 |
diff --git a/approved_operator_pages_copy_test.go b/approved_operator_pages_copy_test.go| index 35947eef5..d52f150e6 100644 |
| --- a/approved_operator_pages_copy_test.go |
| +++ b/approved_operator_pages_copy_test.go |
| @@ -59,6 +59,15 @@ var operatorPagesCopyBuilt = []string{ |
| "OPS-149", "OPS-150", "OPS-151", "OPS-152", "OPS-153", |
| // Task 8: Boxes. |
| "OPS-137", "OPS-146", "OPS-147", |
| + // Task 9: the dashboard. OPS-8 and OPS-32 are above. |
| + "OPS-20", "OPS-21", "OPS-22", "OPS-23", "OPS-24", "OPS-25", "OPS-26", "OPS-27", |
| + "OPS-28", "OPS-29", "OPS-30", "OPS-31", |
| + "OPS-33", "OPS-34", "OPS-35", "OPS-36", "OPS-37", "OPS-38", "OPS-39", "OPS-40", |
| + "OPS-41", "OPS-42", "OPS-43", "OPS-44", "OPS-45", "OPS-46", "OPS-47", "OPS-48", |
| + "OPS-49", "OPS-50", "OPS-51", "OPS-52", "OPS-53", "OPS-54", "OPS-55", "OPS-56", |
| + "OPS-57", "OPS-58", "OPS-59", "OPS-60", "OPS-61", "OPS-62", "OPS-63", "OPS-64", |
| + "OPS-65", "OPS-66", "OPS-67", "OPS-68", "OPS-69", "OPS-70", "OPS-71", "OPS-72", |
| + "OPS-73", "OPS-74", "OPS-75", "OPS-76", |
| } |
| // operatorPagesBuiltRows is entryBuiltRows for operatorPagesCopyBuilt. |
diff --git a/internal/console/accountfleet.go b/internal/console/accountfleet.go| index 27d9a51bf..da3644d7c 100644 |
| --- a/internal/console/accountfleet.go |
| +++ b/internal/console/accountfleet.go |
| @@ -4,7 +4,7 @@ package console |
| // "where does this account's work actually run?". |
| // |
| // It is a DIFFERENT page from the two that already carry the word fleet: |
| -// handleFleet (/fleet) is the operator's global platform status page, and |
| +// handleDashboard (/fleet) is the operator's dashboard, and |
| // handleFleetPage (/a/{sqid}/fleets/{fleet}) is one of this account's own |
| // fleets in detail. This one sits between them — member-readable, account |
| // scoped, and the only place the shared platform fleet and the account's own |
diff --git a/internal/console/claim_invariant_fixtures_test.go b/internal/console/claim_invariant_fixtures_test.go| index 756574d35..d0acefbff 100644 |
| --- a/internal/console/claim_invariant_fixtures_test.go |
| +++ b/internal/console/claim_invariant_fixtures_test.go |
| @@ -888,7 +888,7 @@ var claimFixtures = map[string]claimFixture{ |
| "route GET /auth/confirm": claimRead("the retired confirmation link: renders the expired message for any token"), |
| "route GET /auth/email/link": claimNonApp("an emailed link's confirm page: sets the login-CSRF nonce cookie; spends nothing"), |
| "route GET /auth/signin": claimNonApp("starts an OAuth flow: the auth cookie and its PKCE state"), |
| - "route GET /fleet": claimRead("operator fleet view"), |
| + "route GET /fleet": claimRead("operator dashboard: SQLite counts, fleet.json, box snapshots, the storage queue"), |
| "route GET /fleet/boxes": claimRead("operator boxes view: fleet.json, box snapshots, the storage queue"), |
| "route GET /fleet/economics": claimRead("operator economics view"), |
| "route GET /fleet/economics/accounts": claimRead("operator per-account economics table"), |
diff --git a/internal/console/claim_invariant_probes_read_test.go b/internal/console/claim_invariant_probes_read_test.go| index 6ad520beb..877928f83 100644 |
| --- a/internal/console/claim_invariant_probes_read_test.go |
| +++ b/internal/console/claim_invariant_probes_read_test.go |
| @@ -168,7 +168,7 @@ var claimReadProbes = map[string]claimProbe{ |
| "route GET /settings": claimPageRead(nil, "/settings", "<h1>Your settings</h1>"), |
| "route GET /auth/cli": claimPageRead(nil, "/auth/cli", "<h1>Approve a terminal</h1>"), |
| "route GET /invite/{token}": claimInvitePageProbe(), |
| - "route GET /fleet": claimPageRead(nil, "/fleet", "<h1>Boxes</h1>"), |
| + "route GET /fleet": claimPageRead(nil, "/fleet", "<h1>Dashboard</h1>"), |
| "route GET /fleet/boxes": claimPageRead(nil, "/fleet/boxes", "<h1>Boxes</h1>"), |
| "route GET /fleet/economics": claimPageRead(nil, "/fleet/economics", "<h1>Fleet economics</h1>"), |
| "route GET /fleet/economics/accounts": claimPageRead(nil, "/fleet/economics/accounts", "<h1>Fleet economics: accounts</h1>"), |
diff --git a/internal/console/economicspass.go b/internal/console/economicspass.go| index 5ec8daf33..512ee2ed2 100644 |
| --- a/internal/console/economicspass.go |
| +++ b/internal/console/economicspass.go |
| @@ -1122,7 +1122,7 @@ func (s *Server) putActiveScenario(ctx context.Context, name string) error { |
| // would leak that this path exists to someone who merely guessed it. Method |
| // check comes before EVERYTHING else, including the session gate: a |
| // wrong-method request must be indistinguishable from an unknown route |
| -// regardless of who's asking. Past that, gate is handleFleet's exact shape |
| +// regardless of who's asking. Past that, gate is operatorOnly's exact shape |
| // — session -> IsOperator -> a bare http.NotFound byte-identical with an |
| // unknown route — BEFORE the CSRF check, per the console security rule: |
| // role existence must never be probeable, and a CSRF rejection would leak |
diff --git a/internal/console/fleets.go b/internal/console/fleets.go| index eb01067c6..faf38c467 100644 |
| --- a/internal/console/fleets.go |
| +++ b/internal/console/fleets.go |
| @@ -1071,7 +1071,7 @@ func (s *Server) ownerFleet(w http.ResponseWriter, r *http.Request) (addr, raw s |
| // that errors is logged and degrades to "nothing to show" for that section |
| // (warn carries the first one, for a flash banner) — this page must never |
| // 500 because one of three independent reads had a bad moment, the same |
| -// posture HostRows (view.go) and handleFleet already take. |
| +// posture HostRows (view.go) and handleBoxes already take. |
| func (s *Server) loadFleetPage(ctx context.Context, reg consoleRegistry, acct *Account, fleet *registry.Fleet) (boxes []fleetPageBox, apps []fleetPagePlacedApp, warn string) { |
| regBoxes, err := reg.ListFleetBoxes(fleet.Name) |
| if err != nil { |
diff --git a/internal/console/jobs_test.go b/internal/console/jobs_test.go| index 64036800f..64c39e291 100644 |
| --- a/internal/console/jobs_test.go |
| +++ b/internal/console/jobs_test.go |
| @@ -539,7 +539,7 @@ func runWorkerUntilRan(t *testing.T, fx *consoleFixture, name string) JobStatus |
| // TestSwallowedAlertFailureShowsAsFailed: the alert pass logs an unparsable |
| // alert object and steps over it, returning nil; the job still shows Failed, |
| -// naming the key. |
| +// naming the key, and the dashboard says so (OPS-31). |
| func TestSwallowedAlertFailureShowsAsFailed(t *testing.T) { |
| fx := newConsoleFixture(t) |
| if err := fx.st.SetOperator("paul@keymail.dev", true); err != nil { |
| @@ -555,6 +555,20 @@ func TestSwallowedAlertFailureShowsAsFailed(t *testing.T) { |
| if !strings.Contains(st.Err, "alerts/boxes/box-1.json") { |
| t.Errorf("alert checks error %q does not name the unparsable key", st.Err) |
| } |
| + |
| + // The second half (Task 9): the dashboard lists the failed job, with |
| + // its link to Boxes' jobs table, and its jobs table shows it Failed. |
| + c := signInOperator(t, fx) |
| + label := jobLabels["StartAlertWatcher"] |
| + body := dashGet(t, fx, c) |
| + item := `<code>` + label + `</code> failed on its last run. <a href="/fleet/boxes#jobs">Background jobs</a>` |
| + if !strings.Contains(strings.Join(dashItems(t, body), "\n"), item) { |
| + t.Errorf("the dashboard's callout has no %s:\n%s", item, dashCallout(t, body)) |
| + } |
| + jobs := dashCut(t, body, `id="jobs"`, "</main>") |
| + if !strings.Contains(jobs, "<span>"+label+`</span><span><span rst-status rst-tone="negative">Failed</span>`) { |
| + t.Errorf("the dashboard's jobs table does not show %s Failed:\n%s", label, jobs) |
| + } |
| } |
| // TestWorkerRunsReachTheRegistry: a worker started the way cmd/console |
diff --git a/internal/console/opdashboard.go b/internal/console/opdashboard.go| new file mode 100644 |
| index 000000000..b0b7aaa42 |
| --- /dev/null |
| +++ b/internal/console/opdashboard.go |
| @@ -0,0 +1,405 @@ |
| +package console |
| + |
| +import ( |
| + "fmt" |
| + "log" |
| + "math" |
| + "net/http" |
| + "sort" |
| + "strings" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/status" |
| +) |
| + |
| +// The dashboard (/fleet, spec 2026-10-25 Part 3): who is using the |
| +// platform, what they are doing, and whether everything is running. It |
| +// reads SQLite for the people, accounts and activity, the job registry and |
| +// the alert projection in memory, and the same bucket objects Boxes reads |
| +// (opboxes.go), each once per view. |
| + |
| +// dashSummaryOld is the age past which fleet.json no longer describes the |
| +// boxes: three missed snapshot periods, the boxes' own staleness rule. |
| +const dashSummaryOld = 3 * status.SnapshotPeriod |
| + |
| +// The words the dashboard computes (copy record OPS-21 to OPS-76). |
| +const ( |
| + dashAllClear = "Everything is running." |
| + dashOneThing = "1 thing needs attention" |
| + dashThings = "%d things need attention" |
| + dashWordHealth = "Healthy" |
| + dashWordBusy = "Busy" |
| + dashWordSilent = "Silent" |
| + dashWordStale = "Stale" |
| + dashUnknown = "unknown" |
| +) |
| + |
| +// attentionItem is one line of the needs-attention callout: Lead, then Code |
| +// (a box, service, rule or job name, shown as code) when set, then Tail, |
| +// then a link to where it can be seen. |
| +type attentionItem struct{ Lead, Code, Tail, Href, Link string } |
| + |
| +// attentionInput is everything the callout is judged from. Boxes is the |
| +// very slice the Boxes table renders (dashBoxes), so the two never |
| +// disagree about a box. |
| +type attentionInput struct { |
| + Fleet *status.Fleet |
| + FleetErr error |
| + Boxes []dashBox |
| + Now time.Time |
| + Alerts []FiringAlert |
| + AlertsKnown bool |
| + StorePending *int |
| + Jobs []JobStatus |
| +} |
| + |
| +// attnCode is an item whose format holds one %s, the code: the text before |
| +// it is Lead and the text after it, formatted with rest, is Tail. |
| +func attnCode(format, code, href, link string, rest ...any) attentionItem { |
| + lead, tail, _ := strings.Cut(format, "%s") |
| + if len(rest) > 0 { |
| + tail = fmt.Sprintf(tail, rest...) |
| + } |
| + return attentionItem{Lead: lead, Code: code, Tail: tail, Href: href, Link: link} |
| +} |
| + |
| +// attentionItems is the callout's list and tone: one item per Silent row of |
| +// Boxes, an old summary, a summary that could not be read, each down |
| +// service, each firing alert (once the projection is known), the storage |
| +// queue when it is waiting, and each job whose last run failed. The tone is |
| +// negative when a service is down, warning for anything else, positive for |
| +// nothing. No fleet.json yet is not an item: Boxes says so. |
| +func attentionItems(in attentionInput) (items []attentionItem, tone string) { |
| + boxes := opRailLabel("boxes") |
| + for _, b := range in.Boxes { |
| + if b.Status.Label == dashWordSilent { |
| + items = append(items, attnCode("Box %s has stopped reporting.", b.Label, "/fleet/boxes#box-"+b.Label, boxes)) |
| + } |
| + } |
| + down := false |
| + if in.FleetErr != nil { |
| + items = append(items, attentionItem{Lead: "Could not read the fleet summary."}) |
| + } else if in.Fleet != nil { |
| + if age := in.Now.Sub(in.Fleet.GeneratedAt); age > dashSummaryOld { |
| + items = append(items, attentionItem{ |
| + Lead: fmt.Sprintf("The fleet summary is %s old. Box readings may be out of date.", humanAge(age)), |
| + Href: "/fleet/boxes", Link: boxes, |
| + }) |
| + } |
| + for _, svc := range in.Fleet.Services { |
| + if !svc.Up { |
| + down = true |
| + items = append(items, attnCode("%s is down.", svc.Name, "/fleet/boxes", boxes)) |
| + } |
| + } |
| + } |
| + if in.AlertsKnown { |
| + for _, a := range in.Alerts { |
| + items = append(items, attnCode("Alert %s is firing on %s.", a.Rule, "/fleet/metrics", opRailLabel("metrics"), a.Box)) |
| + } |
| + } |
| + if n := in.StorePending; n != nil && *n > 0 { |
| + lead := fmt.Sprintf("%d storage requests are waiting for approval.", *n) |
| + if *n == 1 { |
| + lead = "1 storage request is waiting for approval." |
| + } |
| + items = append(items, attentionItem{Lead: lead, Href: "/fleet/store", Link: opRailLabel("store")}) |
| + } |
| + var failed []string |
| + for _, j := range in.Jobs { |
| + if j.State == JobFailed { |
| + label, ok := jobLabels[j.Name] |
| + if !ok { |
| + label = j.Name |
| + } |
| + failed = append(failed, label) |
| + } |
| + } |
| + sort.Strings(failed) |
| + for _, label := range failed { |
| + items = append(items, attnCode("%s failed on its last run.", label, "/fleet/boxes#jobs", "Background jobs")) |
| + } |
| + switch { |
| + case down: |
| + tone = "negative" |
| + case len(items) > 0: |
| + tone = "warning" |
| + default: |
| + tone = "positive" |
| + } |
| + return items, tone |
| +} |
| + |
| +// dashBar is one day of the new-people chart: its count and its height |
| +// bucket, 0 to 20 (co-h, styled by ops.css). |
| +type dashBar struct { |
| + Day time.Time |
| + N, H int |
| +} |
| + |
| +// dashBars is the chart's bars, in days' order. A bar's height is |
| +// round(20 × n / max), at least 1 for a day with anyone, and 0 for every |
| +// day when nobody joined in the window. |
| +func dashBars(days []DayCount) []dashBar { |
| + top := 0 |
| + for _, d := range days { |
| + top = max(top, d.N) |
| + } |
| + out := make([]dashBar, len(days)) |
| + for i, d := range days { |
| + out[i] = dashBar{Day: d.Day, N: d.N} |
| + if top > 0 && d.N > 0 { |
| + out[i].H = max(int(math.Round(20*float64(d.N)/float64(top))), 1) |
| + } |
| + } |
| + return out |
| +} |
| + |
| +// dashDelta is a week-on-week change: a rise is positive, a fall or no |
| +// change neutral (fewer sign-ups is not an error). |
| +func dashDelta(now, prev int) (text, tone string) { |
| + switch d := now - prev; { |
| + case d > 0: |
| + return fmt.Sprintf("+%s from last week", opNumber(d)), "positive" |
| + case d < 0: |
| + return fmt.Sprintf("−%s from last week", opNumber(-d)), "neutral" |
| + default: |
| + return "same as last week", "neutral" |
| + } |
| +} |
| + |
| +// dashStats is the headline band: People (the lead), new people and new |
| +// accounts this week against last, apps, and deploys today. |
| +func dashStats(c OperatorCounts) []opStat { |
| + people := opStat{Label: "People", Value: opNumber(c.People), Lead: true, |
| + Note: fmt.Sprintf("%s active in the last 30 days", opNumber(c.Active30))} |
| + newPeople := opStat{Label: "New people this week", Value: opNumber(c.NewPeople7)} |
| + newPeople.Delta, newPeople.Tone = dashDelta(c.NewPeople7, c.NewPeoplePrev7) |
| + newAccounts := opStat{Label: "New accounts this week", Value: opNumber(c.NewAccounts7)} |
| + newAccounts.Delta, newAccounts.Tone = dashDelta(c.NewAccounts7, c.NewAccountsPrev7) |
| + apps := opStat{Label: "Apps", Value: opNumber(c.Apps), Delta: "none new this week", Tone: "neutral"} |
| + if c.NewApps7 > 0 { |
| + apps.Delta, apps.Tone = fmt.Sprintf("+%s this week", opNumber(c.NewApps7)), "positive" |
| + } |
| + deploys := opStat{Label: "Deploys today", Value: opNumber(c.DeploysToday)} |
| + if c.DeploysToday > 0 { |
| + deploys.Note = fmt.Sprintf("across %s apps", opNumber(c.DeployApps)) |
| + if c.DeployApps == 1 { |
| + deploys.Note = "across 1 app" |
| + } |
| + } |
| + return []opStat{people, newPeople, newAccounts, apps, deploys} |
| +} |
| + |
| +// dashBox is one row of the dashboard's Boxes table. Meter is nil for a |
| +// silent box or one with no metrics block; LastSeen is zero for a box no |
| +// report was read for. |
| +type dashBox struct { |
| + Label, Region string |
| + Status opPill |
| + Meter *opMeter |
| + LastSeen time.Time |
| +} |
| + |
| +// Unknown is the word for a reading the row does not have (OPS-76). |
| +func (dashBox) Unknown() string { return dashUnknown } |
| + |
| +// dashLoadPill is a reporting box's status from its fleet.json load word. |
| +func dashLoadPill(load *string) opPill { |
| + if load != nil { |
| + switch *load { |
| + case "busy": |
| + return opPill{Label: dashWordBusy, Tone: "warning"} |
| + case "critical": |
| + return opPill{Label: dashWordBusy, Tone: "negative"} |
| + } |
| + } |
| + return opPill{Label: dashWordHealth, Tone: "positive"} |
| +} |
| + |
| +// dashSummaryStale is whether f is too old to describe the boxes. |
| +func dashSummaryStale(f *status.Fleet, now time.Time) bool { |
| + return f != nil && now.Sub(f.GeneratedAt) > dashSummaryOld |
| +} |
| + |
| +// dashBoxes is the Boxes table: one row per HostRow, in label order, joined |
| +// by label with fleet.json's box for its load word, plus a row for any box |
| +// fleet.json lists that no report was read for (Silent, no meter, no last |
| +// report). Every row is Stale when fleet.json itself is old (stale is then |
| +// true); otherwise a stale HostRow is Silent, a busy or critical load is |
| +// Busy, and the rest are Healthy. Staleness is judged against now. |
| +func dashBoxes(f *status.Fleet, hosts []HostRow, now time.Time) (rows []dashBox, stale bool) { |
| + stale = dashSummaryStale(f, now) |
| + byLabel := map[string]*status.FleetBox{} |
| + if f != nil { |
| + for i := range f.Boxes { |
| + byLabel[f.Boxes[i].Label] = &f.Boxes[i] |
| + } |
| + } |
| + seen := map[string]bool{} |
| + for _, h := range hosts { |
| + seen[h.Label] = true |
| + row := dashBox{Label: h.Label, Region: h.Region, LastSeen: h.LastSeen} |
| + var load *string |
| + if fb := byLabel[h.Label]; fb != nil { |
| + load = fb.Load |
| + if row.Region == "" { |
| + row.Region = fb.Region |
| + } |
| + } |
| + if h.Stale { |
| + row.Status = opPill{Label: dashWordSilent, Tone: "negative"} |
| + } else { |
| + row.Status = dashLoadPill(load) |
| + if p := memUsedPercent(h.Metrics); p >= 0 { |
| + row.Meter = &opMeter{Percent: p, Text: fmt.Sprintf("%d%%", p)} |
| + } |
| + } |
| + rows = append(rows, row) |
| + } |
| + if f != nil { |
| + for _, fb := range f.Boxes { |
| + if !seen[fb.Label] { |
| + rows = append(rows, dashBox{Label: fb.Label, Region: fb.Region, Status: opPill{Label: dashWordSilent, Tone: "negative"}}) |
| + } |
| + } |
| + } |
| + return dashFinish(rows, stale), stale |
| +} |
| + |
| +// dashFleetBoxes is the Boxes table when the box reports could not be |
| +// listed: fleet.json's rows alone, Silent where fleet.json says the box is |
| +// stale, else by its load word, with no meter and no last report. |
| +func dashFleetBoxes(f *status.Fleet, now time.Time) []dashBox { |
| + if f == nil { |
| + return nil |
| + } |
| + rows := make([]dashBox, 0, len(f.Boxes)) |
| + for _, fb := range f.Boxes { |
| + row := dashBox{Label: fb.Label, Region: fb.Region, Status: dashLoadPill(fb.Load)} |
| + if fb.Stale { |
| + row.Status = opPill{Label: dashWordSilent, Tone: "negative"} |
| + } |
| + rows = append(rows, row) |
| + } |
| + return dashFinish(rows, dashSummaryStale(f, now)) |
| +} |
| + |
| +// dashFinish sorts rows by label, names an empty region unknown, and marks |
| +// every row Stale under an old summary. |
| +func dashFinish(rows []dashBox, stale bool) []dashBox { |
| + sort.SliceStable(rows, func(i, j int) bool { return rows[i].Label < rows[j].Label }) |
| + for i := range rows { |
| + if rows[i].Region == "" { |
| + rows[i].Region = dashUnknown |
| + } |
| + if stale { |
| + rows[i].Status = opPill{Label: dashWordStale, Tone: "warning"} |
| + } |
| + } |
| + return rows |
| +} |
| + |
| +// dashView is the dashboard's data (page.Dash). |
| +type dashView struct { |
| + Attention []attentionItem |
| + Tone string |
| + Stats []opStat |
| + Bars []dashBar |
| + Newest []PersonRow |
| + Activity []FeedRow |
| + Boxes []dashBox |
| + HasFleet bool |
| + Jobs []opJobRow |
| +} |
| + |
| +// Title is the callout's heading. |
| +func (d *dashView) Title() string { |
| + switch len(d.Attention) { |
| + case 0: |
| + return dashAllClear |
| + case 1: |
| + return dashOneThing |
| + default: |
| + return fmt.Sprintf(dashThings, len(d.Attention)) |
| + } |
| +} |
| + |
| +// Icon is the callout's icon slug for its tone. |
| +func (d *dashView) Icon() string { |
| + switch d.Tone { |
| + case "negative": |
| + return "circle-x" |
| + case "warning": |
| + return "triangle-alert" |
| + default: |
| + return "circle-check" |
| + } |
| +} |
| + |
| +// handleDashboard serves the dashboard at /fleet, for signed-in operators |
| +// only, behind operatorOnly's 404-to-everyone gate. A failed SQLite read |
| +// leaves its section empty and a failed bucket read degrades (an item in |
| +// the callout, or Boxes from fleet.json alone); neither is a 500. |
| +func (s *Server) handleDashboard(w http.ResponseWriter, r *http.Request) { |
| + addr, raw, ok := s.operatorOnly(w, r) |
| + if !ok { |
| + return |
| + } |
| + ctx := r.Context() |
| + now := s.now() |
| + p := s.opPage(addr, raw, "dashboard") |
| + d := &dashView{} |
| + |
| + if c, err := s.store.OperatorCounts(now); err != nil { |
| + log.Printf("console: dashboard counts: %v", err) |
| + } else { |
| + d.Stats = dashStats(c) |
| + } |
| + if days, err := s.store.NewPeoplePerDay(now, 30); err != nil { |
| + log.Printf("console: dashboard new people per day: %v", err) |
| + } else { |
| + d.Bars = dashBars(days) |
| + } |
| + if people, err := s.store.NewestPeople(5); err != nil { |
| + log.Printf("console: dashboard newest people: %v", err) |
| + } else { |
| + d.Newest = people |
| + } |
| + if feed, err := s.store.ActivityFeed(ActivityFilter{}, 0, 10); err != nil { |
| + log.Printf("console: dashboard activity: %v", err) |
| + } else { |
| + d.Activity = feed |
| + } |
| + |
| + f, fleetErr := s.opFleetJSON(ctx, &p) |
| + if fleetErr != nil { |
| + log.Printf("console: dashboard fleet view: %v", fleetErr) |
| + f = nil |
| + } |
| + d.HasFleet = f != nil |
| + if hosts, err := s.opHostRows(ctx, &p); err != nil { |
| + log.Printf("console: dashboard fleet hosts: %v", err) |
| + d.Boxes = dashFleetBoxes(f, now) |
| + } else { |
| + d.Boxes, _ = dashBoxes(f, hosts, now) |
| + } |
| + for i := range d.Boxes { |
| + if _, name := s.boxRegion(d.Boxes[i].Label); name != "" { |
| + d.Boxes[i].Region = name |
| + } |
| + } |
| + pending, err := s.opStorePending(ctx, &p) |
| + if err != nil { |
| + log.Printf("console: dashboard storage queue: %v", err) |
| + } |
| + alerts, known := s.alertsNow.Firing() |
| + jobs := s.jobs.Snapshot() |
| + d.Attention, d.Tone = attentionItems(attentionInput{ |
| + Fleet: f, FleetErr: fleetErr, Boxes: d.Boxes, Now: now, |
| + Alerts: alerts, AlertsKnown: known, StorePending: pending, Jobs: jobs, |
| + }) |
| + d.Jobs = opJobRows(jobs) |
| + p.Dash = d |
| + s.render(w, http.StatusOK, "ops_dashboard", p) |
| +} |
diff --git a/internal/console/opdashboard_test.go b/internal/console/opdashboard_test.go| new file mode 100644 |
| index 000000000..00c24c6b1 |
| --- /dev/null |
| +++ b/internal/console/opdashboard_test.go |
| @@ -0,0 +1,856 @@ |
| +package console |
| + |
| +import ( |
| + "context" |
| + "database/sql" |
| + "errors" |
| + "fmt" |
| + "html" |
| + "net/http" |
| + "regexp" |
| + "strconv" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/metrics" |
| + "github.com/carlosframework/platform/internal/objstore" |
| + "github.com/carlosframework/platform/internal/status" |
| +) |
| + |
| +// The dashboard at /fleet (opdashboard.go, templates/ops_dashboard.html). |
| + |
| +// opFleetKey is the fleet summary's key in the deployment bucket. |
| +const opFleetKey = "status/fleet.json" |
| + |
| +// operatorWorld is what seedOperatorWorld seeded that the tests name. |
| +type operatorWorld struct { |
| + c *http.Client |
| + shop, notes *Account |
| +} |
| + |
| +// seedOperatorWorld signs Paul in as an operator and a store operator and |
| +// seeds the world the operator pages show (shared with Tasks 10, 11 and 14): |
| +// |
| +// - eight people under example.com, joined over 30 days: two today, the |
| +// rest 2, 5, 9, 21, 25 and 29 days ago, none 10 to 20 days ago; three of |
| +// them seen today. Paul joined 45 days ago, outside the chart. |
| +// - accounts shop (ann, with cat a member) and notes (ben), minted the way |
| +// the console mints them, each with an app of its name; |
| +// - activity: a promote today on each app, a sign-in, an invite; |
| +// - the two boxes of seedHostBoxes (ada-stargazing fresh, grace-kayaking |
| +// dark for an hour); |
| +// - box-1 publishing disk firing, read by one alert pass, and a stale |
| +// alert_seen firing row for a cleared box-2/mem (history, not state); |
| +// - a failed run of StartEconomicsPass, and one pending storage |
| +// application. |
| +func seedOperatorWorld(t *testing.T, fx *consoleFixture) operatorWorld { |
| + t.Helper() |
| + ctx := context.Background() |
| + c := signInOperator(t, fx) |
| + now := time.Now() |
| + if _, err := fx.st.db.Exec(`UPDATE users SET created_at = ? WHERE address = ?`, |
| + now.Add(-45*24*time.Hour).Unix(), "paul@keymail.dev"); err != nil { |
| + t.Fatal(err) |
| + } |
| + day := 24 * time.Hour |
| + people := []struct { |
| + addr string |
| + joined time.Time |
| + seen bool |
| + }{ |
| + {"ann@example.com", now.Add(-10 * time.Second), true}, |
| + {"ben@example.com", now.Add(-20 * time.Second), true}, |
| + {"cat@example.com", now.Add(-2 * day), true}, |
| + {"dan@example.com", now.Add(-5 * day), false}, |
| + {"eve@example.com", now.Add(-9 * day), false}, |
| + {"fay@example.com", now.Add(-21 * day), false}, |
| + {"gus@example.com", now.Add(-25 * day), false}, |
| + {"hal@example.com", now.Add(-29 * day), false}, |
| + } |
| + for _, p := range people { |
| + if _, err := fx.st.EnsureUser(p.addr, p.joined); err != nil { |
| + t.Fatal(err) |
| + } |
| + if p.seen { |
| + if err := fx.st.TouchLastSeen(p.addr, now); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + } |
| + shop, err := fx.srv.mintAccount(ctx, "shop", "ann@example.com") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + notes, err := fx.srv.mintAccount(ctx, "notes", "ben@example.com") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := fx.st.AddMember(shop.ID, "cat@example.com", RoleMember, now); err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, a := range []struct { |
| + acct *Account |
| + app, user string |
| + }{{shop, "shop", "ann@example.com"}, {notes, "notes", "ben@example.com"}} { |
| + if _, err := fx.st.CreateAppIn(a.acct.ID, a.app, a.user, now); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + for _, r := range []struct { |
| + acct int64 |
| + app, who, act string |
| + detail string |
| + }{ |
| + {shop.ID, "shop", "ann@example.com", "promote", "Made v2 live"}, |
| + {notes.ID, "notes", "ben@example.com", "promote", "Made v1 live"}, |
| + {0, "", "cat@example.com", "signin", "Signed in"}, |
| + {shop.ID, "", "ann@example.com", "invite-sent", "Invited dan@example.com"}, |
| + } { |
| + if err := fx.st.RecordActivity(r.acct, r.app, r.who, Activity{Action: r.act, Detail: r.detail}, now.Add(-5*time.Second)); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + |
| + seedHostBoxes(t, fx) |
| + |
| + if err := fx.st.SetGrantToken("paul@keymail.dev", "grant-p", now); err != nil { |
| + t.Fatal(err) |
| + } |
| + fx.srv.sendApp = func(context.Context, string, string, string, string) (string, error) { return "msg-1", nil } |
| + publishAlert(t, fx.rel, boxAlert("box-1", "disk", metrics.RuleState{Firing: true, Value: 0.95, FiredAt: alertNowFiredAt})) |
| + if err := fx.srv.alertPass(ctx); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := fx.st.SetAlertSeen("box-2", "mem", "paul@keymail.dev", true); err != nil { |
| + t.Fatal(err) |
| + } |
| + |
| + _ = fx.srv.jobs.Run(ctx, "StartEconomicsPass", func(context.Context) error { |
| + return errors.New("could not read usage for 24 Oct") |
| + }) |
| + // newPerfFixture has already seeded this one pending application. |
| + if _, _, err := fx.rel.Get(ctx, objstore.EntitlementKey(fx.sqid)); err != nil { |
| + putEntitlement(t, fx, fx.sqid, &objstore.Entitlement{Applied: &objstore.Applied{By: "paul@keymail.dev", At: now, Note: "for uploads"}}) |
| + } |
| + return operatorWorld{c: c, shop: shop, notes: notes} |
| +} |
| + |
| +// dashGet is GET /fleet as c, which must answer 200. |
| +func dashGet(t *testing.T, fx *consoleFixture, c *http.Client) string { |
| + t.Helper() |
| + status, _, body := get(t, c, fx.ts.URL+"/fleet") |
| + if status != http.StatusOK { |
| + t.Fatalf("/fleet = %d:\n%s", status, body) |
| + } |
| + return body |
| +} |
| + |
| +// dashCut is body from the first start to the first end after it (or the |
| +// end of body); it fails the test when start is absent. |
| +func dashCut(t *testing.T, body, start, end string) string { |
| + t.Helper() |
| + i := strings.Index(body, start) |
| + if i < 0 { |
| + t.Fatalf("no %q in:\n%s", start, body) |
| + } |
| + rest := body[i:] |
| + if j := strings.Index(rest[len(start):], end); j >= 0 { |
| + return rest[:len(start)+j] |
| + } |
| + return rest |
| +} |
| + |
| +// dashCallout is the needs-attention callout. |
| +func dashCallout(t *testing.T, body string) string { |
| + t.Helper() |
| + return dashCut(t, body, "<div rst-callout", "<div rst-stats") |
| +} |
| + |
| +var dashItem = regexp.MustCompile(`(?s)<li>(.*?)</li>`) |
| + |
| +// dashItems is the callout's list items. |
| +func dashItems(t *testing.T, body string) []string { |
| + t.Helper() |
| + var out []string |
| + for _, m := range dashItem.FindAllStringSubmatch(dashCallout(t, body), -1) { |
| + out = append(out, m[1]) |
| + } |
| + return out |
| +} |
| + |
| +// dashSection is a section from its <h2> to the next section head. |
| +func dashSection(t *testing.T, body, h2 string) string { |
| + t.Helper() |
| + return dashCut(t, body, "<h2>"+h2+"</h2>", "<div rst-box-head") |
| +} |
| + |
| +// dashRows is a list section's rows, the head row first. |
| +func dashRows(section string) []string { |
| + parts := strings.Split(section, "<div rst-lrow") |
| + if len(parts) < 2 { |
| + return nil |
| + } |
| + return parts[1:] |
| +} |
| + |
| +// TestAttentionItemsEachCondition: not acceptance, table-driven over |
| +// attentionItems, the callout's rule. |
| +func TestAttentionItemsEachCondition(t *testing.T) { |
| + now := time.Date(2026, 10, 26, 12, 0, 0, 0, time.UTC) |
| + fresh := &status.Fleet{GeneratedAt: now.Add(-time.Minute)} |
| + one, three := 1, 3 |
| + silent := dashBox{Label: "box-1", Status: opPill{Label: "Silent", Tone: "negative"}} |
| + healthy := dashBox{Label: "box-2", Status: opPill{Label: "Healthy", Tone: "positive"}} |
| + staleFleet := &status.Fleet{GeneratedAt: now.Add(-time.Minute), Boxes: []status.FleetBox{{Label: "box-2", Stale: true}}} |
| + down := &status.Fleet{GeneratedAt: now.Add(-time.Minute)} |
| + down.Services = append(down.Services, struct { |
| + Name string `json:"name"` |
| + Up bool `json:"up"` |
| + }{Name: "relay", Up: false}, struct { |
| + Name string `json:"name"` |
| + Up bool `json:"up"` |
| + }{Name: "edge", Up: true}) |
| + for _, tc := range []struct { |
| + name string |
| + in attentionInput |
| + want []attentionItem |
| + tone string |
| + title string |
| + }{ |
| + {"nothing wrong", attentionInput{Fleet: fresh, Boxes: []dashBox{healthy}, Now: now, AlertsKnown: true}, nil, "positive", "Everything is running."}, |
| + {"a silent box", attentionInput{Fleet: fresh, Boxes: []dashBox{silent, healthy}, Now: now}, |
| + []attentionItem{{Lead: "Box ", Code: "box-1", Tail: " has stopped reporting.", Href: "/fleet/boxes#box-box-1", Link: "Boxes"}}, "warning", "1 thing needs attention"}, |
| + {"fleet.json's stale flag alone", attentionInput{Fleet: staleFleet, Boxes: []dashBox{healthy}, Now: now}, nil, "positive", "Everything is running."}, |
| + {"an old summary", attentionInput{Fleet: &status.Fleet{GeneratedAt: now.Add(-20 * time.Minute)}, Now: now}, |
| + []attentionItem{{Lead: "The fleet summary is 20m old. Box readings may be out of date.", Href: "/fleet/boxes", Link: "Boxes"}}, "warning", "1 thing needs attention"}, |
| + {"a read failure", attentionInput{FleetErr: errors.New("403"), Now: now}, |
| + []attentionItem{{Lead: "Could not read the fleet summary."}}, "warning", "1 thing needs attention"}, |
| + {"a down service", attentionInput{Fleet: down, Now: now}, |
| + []attentionItem{{Code: "relay", Tail: " is down.", Href: "/fleet/boxes", Link: "Boxes"}}, "negative", "1 thing needs attention"}, |
| + {"a firing alert", attentionInput{Fleet: fresh, Now: now, AlertsKnown: true, Alerts: []FiringAlert{{Box: "box-1", Rule: "disk"}}}, |
| + []attentionItem{{Lead: "Alert ", Code: "disk", Tail: " is firing on box-1.", Href: "/fleet/metrics", Link: "Metrics"}}, "warning", "1 thing needs attention"}, |
| + {"alerts not known yet", attentionInput{Fleet: fresh, Now: now, Alerts: []FiringAlert{{Box: "box-1", Rule: "disk"}}}, nil, "positive", "Everything is running."}, |
| + {"one storage request", attentionInput{Fleet: fresh, Now: now, StorePending: &one}, |
| + []attentionItem{{Lead: "1 storage request is waiting for approval.", Href: "/fleet/store", Link: "Storage requests"}}, "warning", "1 thing needs attention"}, |
| + {"three storage requests", attentionInput{Fleet: fresh, Now: now, StorePending: &three}, |
| + []attentionItem{{Lead: "3 storage requests are waiting for approval.", Href: "/fleet/store", Link: "Storage requests"}}, "warning", "1 thing needs attention"}, |
| + {"no storage count", attentionInput{Fleet: fresh, Now: now}, nil, "positive", "Everything is running."}, |
| + {"a failed job", attentionInput{Fleet: fresh, Now: now, Jobs: []JobStatus{{Name: "StartEconomicsPass", State: JobFailed, Err: "x"}, {Name: "StartAlertWatcher", State: JobOK}}}, |
| + []attentionItem{{Code: "Economics", Tail: " failed on its last run.", Href: "/fleet/boxes#jobs", Link: "Background jobs"}}, "warning", "1 thing needs attention"}, |
| + {"no fleet.json yet", attentionInput{Now: now}, nil, "positive", "Everything is running."}, |
| + {"two things", attentionInput{Fleet: down, Boxes: []dashBox{silent}, Now: now}, |
| + []attentionItem{ |
| + {Lead: "Box ", Code: "box-1", Tail: " has stopped reporting.", Href: "/fleet/boxes#box-box-1", Link: "Boxes"}, |
| + {Code: "relay", Tail: " is down.", Href: "/fleet/boxes", Link: "Boxes"}, |
| + }, "negative", "2 things need attention"}, |
| + } { |
| + t.Run(tc.name, func(t *testing.T) { |
| + items, tone := attentionItems(tc.in) |
| + if fmt.Sprint(items) != fmt.Sprint(tc.want) || tone != tc.tone { |
| + t.Fatalf("items %+v tone %q, want %+v tone %q", items, tone, tc.want, tc.tone) |
| + } |
| + if got := (&dashView{Attention: items}).Title(); got != tc.title { |
| + t.Errorf("title %q, want %q", got, tc.title) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// TestDashboardNeedsAttentionFromRealRows: on the seeded world the callout |
| +// lists the dark box, the alert, the storage request and the failed job, |
| +// each with its link; an operator who is not a store operator sees three. |
| +func TestDashboardNeedsAttentionFromRealRows(t *testing.T) { |
| + fx := newConsoleFixture(t) |
| + w := seedOperatorWorld(t, fx) |
| + body := dashGet(t, fx, w.c) |
| + callout := dashCallout(t, body) |
| + for _, want := range []string{`rst-tone="warning"`, "<strong>4 things need attention</strong>"} { |
| + if !strings.Contains(callout, want) { |
| + t.Errorf("the callout has no %s:\n%s", want, callout) |
| + } |
| + } |
| + want := []string{ |
| + `Box <code>grace-kayaking</code> has stopped reporting. <a href="/fleet/boxes#box-grace-kayaking">Boxes</a>`, |
| + `Alert <code>disk</code> is firing on box-1. <a href="/fleet/metrics">Metrics</a>`, |
| + `1 storage request is waiting for approval. <a href="/fleet/store">Storage requests</a>`, |
| + `<code>Economics</code> failed on its last run. <a href="/fleet/boxes#jobs">Background jobs</a>`, |
| + } |
| + if got := dashItems(t, body); strings.Join(got, "\n") != strings.Join(want, "\n") { |
| + t.Fatalf("items:\n%s\nwant:\n%s", strings.Join(got, "\n"), strings.Join(want, "\n")) |
| + } |
| + |
| + fx.srv.cfg.StoreOperators = nil |
| + body = dashGet(t, fx, w.c) |
| + if !strings.Contains(dashCallout(t, body), "<strong>3 things need attention</strong>") { |
| + t.Errorf("a non-store operator's callout:\n%s", dashCallout(t, body)) |
| + } |
| + for _, it := range dashItems(t, body) { |
| + if strings.Contains(it, "storage") { |
| + t.Errorf("a non-store operator sees %q", it) |
| + } |
| + } |
| +} |
| + |
| +// TestDashboardIgnoresAlertHistory: the callout's alerts come from the |
| +// projection, never alert_seen; before the first pass there are none. |
| +func TestDashboardIgnoresAlertHistory(t *testing.T) { |
| + fx := newConsoleFixture(t) |
| + w := seedOperatorWorld(t, fx) |
| + for _, it := range dashItems(t, dashGet(t, fx, w.c)) { |
| + if strings.Contains(it, "box-2") || strings.Contains(it, "mem") { |
| + t.Errorf("an item names the cleared alert: %s", it) |
| + } |
| + } |
| + |
| + fresh := newConsoleFixture(t) |
| + c := signInOperator(t, fresh) |
| + publishAlert(t, fresh.rel, boxAlert("box-1", "disk", metrics.RuleState{Firing: true, FiredAt: alertNowFiredAt})) |
| + if err := fresh.st.SetAlertSeen("box-1", "disk", "paul@keymail.dev", true); err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, it := range dashItems(t, dashGet(t, fresh, c)) { |
| + if strings.Contains(it, "Alert ") { |
| + t.Errorf("an alert item before any pass: %s", it) |
| + } |
| + } |
| +} |
| + |
| +// TestDashboardAllClear: nothing wrong is a positive callout with no list. |
| +func TestDashboardAllClear(t *testing.T) { |
| + fx := newConsoleFixture(t) |
| + c := signInOperator(t, fx) |
| + callout := dashCallout(t, dashGet(t, fx, c)) |
| + for _, want := range []string{`rst-tone="positive"`, "<strong>Everything is running.</strong>"} { |
| + if !strings.Contains(callout, want) { |
| + t.Errorf("the callout has no %s:\n%s", want, callout) |
| + } |
| + } |
| + if strings.Contains(callout, "<ul") { |
| + t.Errorf("an all-clear callout has a list:\n%s", callout) |
| + } |
| +} |
| + |
| +// dashStatOf is the stat band's cell labelled label. |
| +func dashStatOf(t *testing.T, body, label string) string { |
| + t.Helper() |
| + return html.UnescapeString(dashCut(t, dashCut(t, body, "<div rst-stats", "<div rst-box-head"), "<span rst-stat-label>"+label+"</span>", "<div rst-stat")) |
| +} |
| + |
| +// TestDashboardCountsFromFixtureRows: the band's numbers are the seeded |
| +// rows' counts. |
| +func TestDashboardCountsFromFixtureRows(t *testing.T) { |
| + fx := newConsoleFixture(t) |
| + w := seedOperatorWorld(t, fx) |
| + body := dashGet(t, fx, w.c) |
| + for label, wants := range map[string][]string{ |
| + "People": {"<span rst-stat-num>9</span>", "<span rst-stat-note>4 active in the last 30 days</span>"}, |
| + "New people this week": {"<span rst-stat-num>4</span>", `<span rst-stat-delta rst-tone="positive">+3 from last week</span>`}, |
| + "New accounts this week": {"<span rst-stat-delta"}, |
| + "Apps": {`<span rst-stat-delta rst-tone="positive">+`}, |
| + "Deploys today": {"<span rst-stat-num>2</span>", "<span rst-stat-note>across 2 apps</span>"}, |
| + } { |
| + cell := dashStatOf(t, body, label) |
| + for _, want := range wants { |
| + if !strings.Contains(cell, want) { |
| + t.Errorf("%s: no %s in %s", label, want, cell) |
| + } |
| + } |
| + } |
| + if !strings.Contains(body, `<div rst-stat="lead"><span rst-stat-label>People</span>`) { |
| + t.Error("People is not the lead stat") |
| + } |
| +} |
| + |
| +var ( |
| + dashBarSpan = regexp.MustCompile(`<span co-bar co-h="(\d+)"></span>`) |
| + dashDayRow = regexp.MustCompile(`<tr><td>([^<]+)</td><td>(\d+)</td></tr>`) |
| + dashCaption = "<caption>New people each day, last 30 days</caption>" |
| +) |
| + |
| +// TestDashboardSeriesHasThirtyDaysWithZerosFilled: 30 bars, oldest first; |
| +// the hidden table says the same per day, zeros included. |
| +func TestDashboardSeriesHasThirtyDaysWithZerosFilled(t *testing.T) { |
| + fx := newConsoleFixture(t) |
| + w := seedOperatorWorld(t, fx) |
| + body := dashGet(t, fx, w.c) |
| + bars := dashBarSpan.FindAllStringSubmatch(body, -1) |
| + if len(bars) != 30 { |
| + t.Fatalf("%d bars, want 30", len(bars)) |
| + } |
| + table := dashCut(t, body, dashCaption, "</table>") |
| + rows := dashDayRow.FindAllStringSubmatch(table, -1) |
| + if len(rows) != 30 { |
| + t.Fatalf("the hidden table has %d rows, want 30:\n%s", len(rows), table) |
| + } |
| + today := opMidnight(time.Now()) |
| + for k := 10; k <= 20; k++ { |
| + r := rows[29-k] |
| + if r[2] != "0" { |
| + t.Errorf("%d days ago (%s) says %s, want 0", k, r[1], r[2]) |
| + } |
| + } |
| + if rows[29][1] != today.Format("2 Jan") || rows[29][2] != "2" { |
| + t.Errorf("the last row is %s %s, want today (%s) and 2", rows[29][1], rows[29][2], today.Format("2 Jan")) |
| + } |
| + tallest := 0 |
| + for i, b := range bars { |
| + h, _ := strconv.Atoi(b[1]) |
| + tallest = max(tallest, h) |
| + if rows[i][2] != "0" && h == 0 { |
| + t.Errorf("day %s has %s people and a co-h=0 bar", rows[i][1], rows[i][2]) |
| + } |
| + } |
| + if tallest != 20 { |
| + t.Errorf("the tallest bar is co-h=%d, want 20", tallest) |
| + } |
| + axis := dashCut(t, body, "<div co-bars-axis", "</div>") |
| + if !strings.Contains(axis, "<span>"+rows[0][1]+"</span>") || !strings.Contains(axis, "<span>Today</span>") { |
| + t.Errorf("the axis is %s, want the first day and Today", axis) |
| + } |
| +} |
| + |
| +// TestAttentionAndBoxesAgreeAcrossTheFifteenMinuteLine: the Boxes rows and |
| +// the callout judge a box by one clock (s.now()) in one pass. Direct seams, |
| +// an injected clock; no claim about reads, since every GET reads again. |
| +func TestAttentionAndBoxesAgreeAcrossTheFifteenMinuteLine(t *testing.T) { |
| + fx := newConsoleFixture(t) |
| + c := signInOperator(t, fx) |
| + ctx := context.Background() |
| + t0 := time.Now().UTC().Truncate(time.Second) |
| + fx.srv.opNow = func() time.Time { return t0 } |
| + if err := status.WriteBox(ctx, fx.rel, status.Box{GeneratedAt: t0.Add(-14 * time.Minute), Label: "ada-stargazing", Region: "eu-west-1"}); err != nil { |
| + t.Fatal(err) |
| + } |
| + f, err := status.BuildFleet(ctx, fx.rel, nil, t0.Add(-2*time.Minute), status.SnapshotPeriod) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if len(f.Boxes) != 1 || f.Boxes[0].Stale { |
| + t.Fatalf("fleet.json boxes = %+v, want ada-stargazing not stale", f.Boxes) |
| + } |
| + if err := status.PublishFleet(ctx, fx.rel, f); err != nil { |
| + t.Fatal(err) |
| + } |
| + // Present only in HostRows: written after fleet.json was built. |
| + if err := status.WriteBox(ctx, fx.rel, status.Box{GeneratedAt: t0.Add(-2 * time.Hour), Label: "grace-kayaking", Region: "eu-west-2"}); err != nil { |
| + t.Fatal(err) |
| + } |
| + boxRow := func(body, label string) string { |
| + t.Helper() |
| + for _, r := range dashRows(dashSection(t, body, "Boxes")) { |
| + if strings.Contains(r, ">"+label+"</a>") { |
| + return r |
| + } |
| + } |
| + t.Fatalf("no Boxes row for %s", label) |
| + return "" |
| + } |
| + item := func(label string) string { |
| + return `Box <code>` + label + `</code> has stopped reporting. <a href="/fleet/boxes#box-` + label + `">Boxes</a>` |
| + } |
| + |
| + body := dashGet(t, fx, c) |
| + if r := boxRow(body, "ada-stargazing"); !strings.Contains(r, ">Healthy</span>") { |
| + t.Errorf("at t0 the row is not Healthy: %s", r) |
| + } |
| + if r := boxRow(body, "grace-kayaking"); !strings.Contains(r, ">Silent</span>") { |
| + t.Errorf("the HostRows-only dark box is not Silent: %s", r) |
| + } |
| + items := strings.Join(dashItems(t, body), "\n") |
| + if strings.Contains(items, "ada-stargazing") || !strings.Contains(items, item("grace-kayaking")) { |
| + t.Errorf("at t0 the callout is:\n%s", items) |
| + } |
| + |
| + fx.srv.opNow = func() time.Time { return t0.Add(2 * time.Minute) } |
| + body = dashGet(t, fx, c) |
| + if r := boxRow(body, "ada-stargazing"); !strings.Contains(r, ">Silent</span>") { |
| + t.Errorf("at t0+2m the row is not Silent: %s", r) |
| + } |
| + items = strings.Join(dashItems(t, body), "\n") |
| + for _, label := range []string{"ada-stargazing", "grace-kayaking"} { |
| + if !strings.Contains(items, item(label)) { |
| + t.Errorf("at t0+2m the callout has no item for %s:\n%s", label, items) |
| + } |
| + } |
| + if !strings.Contains(dashCallout(t, body), `rst-tone="warning"`) { |
| + t.Errorf("at t0+2m the callout is not warning:\n%s", dashCallout(t, body)) |
| + } |
| + if strings.Contains(items, "The fleet summary is") { |
| + t.Errorf("a 4-minute-old summary is called old:\n%s", items) |
| + } |
| +} |
| + |
| +// TestDashboardBoxStatuses: not acceptance, over dashBoxes. |
| +func TestDashboardBoxStatuses(t *testing.T) { |
| + now := time.Date(2026, 10, 26, 12, 0, 0, 0, time.UTC) |
| + word := func(s string) *string { return &s } |
| + mem := &status.BoxMetrics{MemTotalBytes: pi64(4 << 30), MemAvailBytes: pi64(1 << 30)} |
| + f := &status.Fleet{GeneratedAt: now.Add(-time.Minute), Boxes: []status.FleetBox{ |
| + {Label: "box-1", Region: "eu-west-1", Load: word("comfortable")}, |
| + {Label: "box-2", Region: "eu-west-1", Load: word("busy")}, |
| + {Label: "box-3", Region: "eu-west-1", Load: word("critical")}, |
| + {Label: "box-4", Region: "", Load: word("comfortable")}, |
| + {Label: "box-5", Region: "eu-west-1", Load: word("comfortable")}, |
| + }} |
| + hosts := []HostRow{ |
| + {Label: "box-1", Region: "eu-west-1", LastSeen: now, Metrics: mem}, |
| + {Label: "box-2", Region: "eu-west-1", LastSeen: now, Metrics: mem}, |
| + {Label: "box-3", Region: "eu-west-1", LastSeen: now}, |
| + {Label: "box-4", Region: "", LastSeen: now.Add(-time.Hour), Stale: true}, |
| + } |
| + rows, stale := dashBoxes(f, hosts, now) |
| + if stale { |
| + t.Fatal("a one-minute-old summary is stale") |
| + } |
| + want := []struct { |
| + label, word, tone, region string |
| + meter bool |
| + }{ |
| + {"box-1", "Healthy", "positive", "eu-west-1", true}, |
| + {"box-2", "Busy", "warning", "eu-west-1", true}, |
| + {"box-3", "Busy", "negative", "eu-west-1", false}, |
| + {"box-4", "Silent", "negative", "unknown", false}, |
| + {"box-5", "Silent", "negative", "eu-west-1", false}, |
| + } |
| + if len(rows) != len(want) { |
| + t.Fatalf("rows = %+v", rows) |
| + } |
| + for i, w := range want { |
| + r := rows[i] |
| + if r.Label != w.label || r.Status.Label != w.word || r.Status.Tone != w.tone || r.Region != w.region || (r.Meter != nil) != w.meter { |
| + t.Errorf("row %d = %+v, want %+v", i, r, w) |
| + } |
| + } |
| + if rows[0].Meter.Percent != 75 || rows[0].Meter.Text != "75%" { |
| + t.Errorf("box-1's meter = %+v, want 75 and 75%%", rows[0].Meter) |
| + } |
| + if !rows[4].LastSeen.IsZero() { |
| + t.Errorf("a box only fleet.json lists has a last report: %v", rows[4].LastSeen) |
| + } |
| + |
| + old := *f |
| + old.GeneratedAt = now.Add(-16 * time.Minute) |
| + rows, stale = dashBoxes(&old, hosts, now) |
| + if !stale { |
| + t.Fatal("a 16-minute-old summary is not stale") |
| + } |
| + for _, r := range rows { |
| + if r.Status.Label != "Stale" { |
| + t.Errorf("%s is %q under an old summary, want Stale", r.Label, r.Status.Label) |
| + } |
| + } |
| +} |
| + |
| +// TestDashboardLatestActivityAndNewestPeople: the newest ten activity rows, |
| +// newest first, and the newest five people with their first account. |
| +func TestDashboardLatestActivityAndNewestPeople(t *testing.T) { |
| + fx := newConsoleFixture(t) |
| + w := seedOperatorWorld(t, fx) |
| + // More rows than the dashboard shows: the newest ten are these six and |
| + // four of the seeded ones. |
| + for i := 0; i < 6; i++ { |
| + if err := fx.st.RecordActivity(w.shop.ID, "shop", "ann@example.com", Activity{Action: "rename", Detail: fmt.Sprintf("Change %d", i)}, time.Now()); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + body := dashGet(t, fx, w.c) |
| + |
| + feed, err := fx.st.ActivityFeed(ActivityFilter{}, 0, 10) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + rows := dashRows(dashSection(t, body, "Latest activity")) |
| + if len(rows) != len(feed)+1 || len(feed) != 10 { |
| + t.Fatalf("%d activity rows for a feed of %d (want 10):\n%s", len(rows)-1, len(feed), dashSection(t, body, "Latest activity")) |
| + } |
| + if !strings.Contains(rows[0], "<span>When</span><span>Who</span><span>What</span><span>App</span>") { |
| + t.Errorf("activity head: %s", rows[0]) |
| + } |
| + for i, f := range feed { |
| + r := rows[i+1] |
| + if !strings.Contains(r, "<span>"+f.Address+"</span>") || !strings.Contains(r, "<span>"+f.Detail+"</span>") { |
| + t.Errorf("activity row %d is not feed row %d (%s %s): %s", i+1, f.ID, f.Address, f.Detail, r) |
| + } |
| + } |
| + if !strings.Contains(rows[1], "Change 5") { |
| + t.Errorf("the newest row is not the last written: %s", rows[1]) |
| + } |
| + var signin, promotes string |
| + for _, r := range rows[1:] { |
| + if strings.Contains(r, "<span>Signed in</span>") { |
| + signin = r |
| + } |
| + if strings.Contains(r, " live</span>") { |
| + promotes += r |
| + } |
| + } |
| + if !strings.Contains(signin, "cat@example.com") || !strings.Contains(signin, `<span class="rst-cell-mut">none</span>`) { |
| + t.Errorf("the sign-in row has no none for its app: %q", signin) |
| + } |
| + if !strings.Contains(promotes, "<span>notes</span>") || !strings.Contains(promotes, "<span>shop</span>") { |
| + t.Errorf("the promote rows do not name their apps: %s", promotes) |
| + } |
| + |
| + people := dashRows(dashSection(t, body, "Newest people")) |
| + want := [][2]string{ |
| + {"ann@example.com", "<span>shop</span>"}, |
| + {"ben@example.com", "<span>notes</span>"}, |
| + {"cat@example.com", "<span>shop</span>"}, |
| + {"dan@example.com", `<span class="rst-cell-mut">none</span>`}, |
| + {"eve@example.com", `<span class="rst-cell-mut">none</span>`}, |
| + } |
| + if len(people) != len(want)+1 { |
| + t.Fatalf("%d people rows, want 5:\n%s", len(people)-1, dashSection(t, body, "Newest people")) |
| + } |
| + if !strings.Contains(people[0], "<span>Person</span><span>Account</span><span>Joined</span><span>Apps</span>") { |
| + t.Errorf("people head: %s", people[0]) |
| + } |
| + for i, w := range want { |
| + r := people[i+1] |
| + if !strings.Contains(r, `<span class="rst-nm">`+w[0]+`</span>`) || !strings.Contains(r, w[1]) { |
| + t.Errorf("people row %d = %s, want %s with %s", i+1, r, w[0], w[1]) |
| + } |
| + } |
| + if !strings.Contains(dashCut(t, body, "<h2>Newest people</h2>", "</div>"), `<a rst-btn="ghost" href="/fleet/people">All people</a>`) { |
| + t.Error("Newest people has no All people link") |
| + } |
| + if !strings.Contains(dashCut(t, body, "<h2>Latest activity</h2>", "</div>"), `<a rst-btn="ghost" href="/fleet/activity">All activity</a>`) { |
| + t.Error("Latest activity has no All activity link") |
| + } |
| +} |
| + |
| +// TestDashboardEmptyLists: a deployment nobody has used shows the empty |
| +// lines, not empty cards. |
| +func TestDashboardEmptyLists(t *testing.T) { |
| + fx := newConsoleFixture(t) |
| + c := signInOperator(t, fx) |
| + if _, err := fx.st.db.Exec(`DELETE FROM audit`); err != nil { |
| + t.Fatal(err) |
| + } |
| + body := dashGet(t, fx, c) |
| + for _, want := range []string{"Nothing has happened yet.", "No box has published a reading yet."} { |
| + if !strings.Contains(body, want) { |
| + t.Errorf("no %q in:\n%s", want, body) |
| + } |
| + } |
| +} |
| + |
| +// TestDashboardReadFailuresDegrade: a refused fleet.json read is a callout |
| +// item, a refused box listing leaves the Boxes section on fleet.json's |
| +// rows; neither is a 500. |
| +func TestDashboardReadFailuresDegrade(t *testing.T) { |
| + fx, lat := newPerfFixture(t) |
| + c := signInOperator(t, fx) |
| + rec := recordS3(lat, func(q s3Req) bool { return q.Key == opFleetKey }) |
| + body := dashGet(t, fx, c) |
| + if rec.touching(opFleetKey) == 0 { |
| + t.Fatal("the view never read status/fleet.json") |
| + } |
| + if !strings.Contains(strings.Join(dashItems(t, body), "\n"), "Could not read the fleet summary.") { |
| + t.Errorf("no read-failure item:\n%s", dashCallout(t, body)) |
| + } |
| + |
| + rec = recordS3(lat, func(q s3Req) bool { return q.Key == "" && strings.HasPrefix(q.Prefix, "status/boxes/") }) |
| + body = dashGet(t, fx, c) |
| + if rec.listings("status/boxes/") == 0 { |
| + t.Fatal("the view never listed status/boxes/") |
| + } |
| + boxes := dashSection(t, body, "Boxes") |
| + rows := dashRows(boxes) |
| + if len(rows) < 2 || !strings.Contains(boxes, ">ada-stargazing</a>") { |
| + t.Fatalf("with the listing refused the Boxes section does not show fleet.json's rows:\n%s", boxes) |
| + } |
| + for _, r := range rows[1:] { |
| + if strings.Contains(r, "<meter") || !strings.Contains(r, `<span class="rst-cell-mut">unknown</span>`) { |
| + t.Errorf("a row read only from fleet.json shows a reading it does not have: %s", r) |
| + } |
| + } |
| +} |
| + |
| +// TestDashboardBoxesKeepTheMockupColumns: Box, Status, Region, Load as a |
| +// meter, Last report, per box. |
| +func TestDashboardBoxesKeepTheMockupColumns(t *testing.T) { |
| + fx := newConsoleFixture(t) |
| + w := seedOperatorWorld(t, fx) |
| + body := dashGet(t, fx, w.c) |
| + section := dashSection(t, body, "Boxes") |
| + if !strings.Contains(dashCut(t, body, "<h2>Boxes</h2>", "</div>"), `<a rst-btn="ghost" href="/fleet/boxes">All boxes</a>`) { |
| + t.Error("Boxes has no All boxes link") |
| + } |
| + rows := dashRows(section) |
| + if len(rows) != 3 { |
| + t.Fatalf("%d Boxes rows, want the head and 2:\n%s", len(rows), section) |
| + } |
| + if !strings.Contains(rows[0], "<span>Box</span><span>Status</span><span>Region</span><span>Load</span><span>Last report</span>") { |
| + t.Errorf("Boxes head: %s", rows[0]) |
| + } |
| + fresh, dark := rows[1], rows[2] |
| + for _, want := range []string{ |
| + `<a class="rst-nm" href="/fleet/boxes#box-ada-stargazing">ada-stargazing</a>`, |
| + `<span rst-status rst-tone="positive">Healthy</span>`, |
| + "<span>eu-west-1</span>", |
| + `<meter rst-meter-bar value="50"`, "<span rst-meter-num>50%</span>", |
| + " ago</span>", |
| + } { |
| + if !strings.Contains(fresh, want) { |
| + t.Errorf("the fresh box's row has no %s: %s", want, fresh) |
| + } |
| + } |
| + for _, want := range []string{ |
| + `>grace-kayaking</a>`, |
| + `<span rst-status rst-tone="negative">Silent</span>`, |
| + `<span class="rst-cell-mut">unknown</span>`, |
| + "1h0m ago</span>", |
| + } { |
| + if !strings.Contains(dark, want) { |
| + t.Errorf("the dark box's row has no %s: %s", want, dark) |
| + } |
| + } |
| + if strings.Contains(dark, "<meter") { |
| + t.Errorf("the dark box's row has a meter: %s", dark) |
| + } |
| +} |
| + |
| +// TestDashboardRemoteReadsAreTheDeclaredOnes: /fleet reads fleet.json, the |
| +// box reports and (for a store operator) the storage queue, each once, and |
| +// no more than /fleet/boxes does. |
| +func TestDashboardRemoteReadsAreTheDeclaredOnes(t *testing.T) { |
| + fx, lat := newPerfFixture(t) |
| + w := seedOperatorWorld(t, fx) |
| + rec := recordS3(lat, nil) |
| + declared := func(q s3Req, store bool) bool { |
| + switch { |
| + case q.Key == opFleetKey: |
| + return true |
| + case q.Key == "" && q.Prefix == "status/boxes/", strings.HasPrefix(q.Key, "status/boxes/"): |
| + return true |
| + case store && (q.Key == "" && q.Prefix == "store/entitlements/" || strings.HasPrefix(q.Key, "store/entitlements/")): |
| + return true |
| + } |
| + return false |
| + } |
| + view := func(path string, store bool) []s3Req { |
| + t.Helper() |
| + rec.reset() |
| + status, _, body := get(t, w.c, fx.ts.URL+path) |
| + if status != http.StatusOK { |
| + t.Fatalf("%s = %d:\n%s", path, status, body) |
| + } |
| + return rec.all() |
| + } |
| + dash := view("/fleet", true) |
| + seen := map[s3Req]bool{} |
| + storage := 0 |
| + for _, q := range dash { |
| + if !declared(q, true) { |
| + t.Errorf("/fleet made an undeclared request %+v", q) |
| + } |
| + if seen[q] { |
| + t.Errorf("/fleet requested %+v twice", q) |
| + } |
| + seen[q] = true |
| + if strings.HasPrefix(q.Key, "store/") || strings.HasPrefix(q.Prefix, "store/") { |
| + storage++ |
| + } |
| + } |
| + if storage == 0 { |
| + t.Error("a store operator's dashboard never read the storage queue") |
| + } |
| + if boxes := view("/fleet/boxes", true); len(dash) > len(boxes) { |
| + t.Errorf("/fleet made %d requests, /fleet/boxes %d", len(dash), len(boxes)) |
| + } |
| + |
| + fx.srv.cfg.StoreOperators = nil |
| + for _, q := range view("/fleet", false) { |
| + if !declared(q, false) { |
| + t.Errorf("a non-store operator's /fleet made %+v", q) |
| + } |
| + } |
| +} |
| + |
| +// seedOperatorScale fills the operator tables for the walk (perfSeed), so |
| +// every operator screen is measured over populated tables: 300 people |
| +// joined across 60 days (half seen, a third with a session), 60 accounts |
| +// with 2 to 6 members, 1 to 8 apps and a plan row each, and 3,000 audit |
| +// rows over the accounts' actions and deploys. One transaction, straight |
| +// into SQLite, so the walk's setup stays quick; nothing here is remote. |
| +func seedOperatorScale(t *testing.T, fx *consoleFixture) { |
| + t.Helper() |
| + db, ok := fx.st.db.(*sql.DB) |
| + if !ok { |
| + t.Fatalf("store handle is %T", fx.st.db) |
| + } |
| + tx, err := db.Begin() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer tx.Rollback() |
| + prep := func(q string) *sql.Stmt { |
| + st, err := tx.Prepare(q) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return st |
| + } |
| + exec := func(st *sql.Stmt, args ...any) { |
| + if _, err := st.Exec(args...); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + const people, accounts, audits = 300, 60, 3000 |
| + n := time.Now().Unix() |
| + day := int64(24 * 60 * 60) |
| + person := func(i int) string { return fmt.Sprintf("person-%d@example.com", i%people) } |
| + users := prep(`INSERT INTO users (address, created_at, last_seen) VALUES (?, ?, ?)`) |
| + sessions := prep(`INSERT INTO sessions (token_hash, address, created_at, expires_at) VALUES (?, ?, ?, ?)`) |
| + for i := 0; i < people; i++ { |
| + joined := n - int64(i)*60*day/people |
| + seen := int64(0) |
| + if i%2 == 0 { |
| + seen = n - int64(i%30)*day |
| + } |
| + exec(users, person(i), joined, seen) |
| + if i%3 == 0 { |
| + at := n - int64(i%20)*day |
| + exec(sessions, fmt.Sprintf("opscale-%04d", i), person(i), at, at+30*day) |
| + } |
| + } |
| + accts := prep(`INSERT INTO accounts (id, sqid, name, created_at) VALUES (?, ?, ?, ?)`) |
| + members := prep(`INSERT INTO memberships (account_id, address, role, added_at) VALUES (?, ?, ?, ?)`) |
| + plans := prep(`INSERT INTO account_plans (account_id, plan, source, revision, updated_by, updated_at) VALUES (?, ?, ?, ?, ?, ?)`) |
| + id := func(i int) int64 { return int64(9000 + i) } |
| + for i := 0; i < accounts; i++ { |
| + created := n - int64(i)*day |
| + exec(accts, id(i), fmt.Sprintf("opscale%02d", i), fmt.Sprintf("shop-%d", i), created) |
| + for j := 0; j < 2+i%5; j++ { |
| + role := RoleMember |
| + if j == 0 { |
| + role = RoleOwner |
| + } |
| + exec(members, id(i), person(i*5+j), role, created) |
| + } |
| + for j := 0; j < 1+i%8; j++ { |
| + if _, err := insertAppRow(tx, newAppRow{AccountID: id(i), App: fmt.Sprintf("shop-%d-app-%d", i, j), |
| + CreatedBy: person(i * 5), CreatedAt: created + int64(j)*3600}); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + exec(plans, id(i), "free", "operator", 1, "paul@keymail.dev", created) |
| + } |
| + audit := prep(`INSERT INTO audit (account_id, app, address, action, detail, created_at) VALUES (?, ?, ?, ?, ?, ?)`) |
| + kinds := []string{"first-signin", "signin", "invite-sent", "invite-accepted", "account-created", "account-deleted", "promote", "rollback"} |
| + for i := 0; i < audits; i++ { |
| + action, acct, app := kinds[i%len(kinds)], id(i%accounts), "" |
| + switch action { |
| + case "promote", "rollback": |
| + app = fmt.Sprintf("shop-%d-app-0", i%accounts) |
| + case "signin", "first-signin": |
| + acct = 0 |
| + } |
| + exec(audit, acct, app, person(i), action, "detail", n-int64(audits-i)*60) |
| + } |
| + if err := tx.Commit(); err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
diff --git a/internal/console/opshell_test.go b/internal/console/opshell_test.go| index a5cd17dad..221a645ad 100644 |
| --- a/internal/console/opshell_test.go |
| +++ b/internal/console/opshell_test.go |
| @@ -46,7 +46,6 @@ func operatorScreens(fx *consoleFixture) []string { |
| // opShellPending is the operator screens not yet moved into the shell. |
| // Later tasks delete entries; none adds one. |
| var opShellPending = map[string]bool{ |
| - "/fleet": true, |
| "/fleet/metrics": true, |
| "/fleet/economics": true, |
| "/fleet/economics/accounts": true, |
diff --git a/internal/console/perfquickwins_test.go b/internal/console/perfquickwins_test.go| index a08a77e3d..ede5f1440 100644 |
| --- a/internal/console/perfquickwins_test.go |
| +++ b/internal/console/perfquickwins_test.go |
| @@ -109,6 +109,7 @@ type s3Req struct { |
| Method string |
| Key string // "" for a listing |
| Prefix string // a listing's prefix |
| + Token string // a listing's continuation token: "" on its first page |
| } |
| // recordS3 installs the recorder as the fake's request hook; fail, when |
| @@ -121,6 +122,7 @@ func recordS3(lat *perfLatency, fail func(s3Req) bool) *s3Recorder { |
| q := s3Req{Method: r.Method, Key: key} |
| if key == "" { |
| q.Prefix = r.URL.Query().Get("prefix") |
| + q.Token = r.URL.Query().Get("continuation-token") |
| } |
| rec.mu.Lock() |
| rec.reqs = append(rec.reqs, q) |
diff --git a/internal/console/perfwalk_test.go b/internal/console/perfwalk_test.go| index 7efec4070..3eb9b831f 100644 |
| --- a/internal/console/perfwalk_test.go |
| +++ b/internal/console/perfwalk_test.go |
| @@ -340,6 +340,9 @@ func perfSeed(t *testing.T, fx *consoleFixture, seeds *perfSeeds) { |
| // pass has turned the two newest off (keepFixture's shape). |
| perfSeedLapsed(t, fx, seeds) |
| + // The operator pages' tables, populated (opdashboard_test.go). |
| + seedOperatorScale(t, fx) |
| + |
| // Every object was written seconds ago, and readers that trust an |
| // object's stamp only once it has settled (domains.ClaimCache's |
| // modSettle, two seconds) would re-read them for the first moments of |
diff --git a/internal/console/server.go b/internal/console/server.go| index d0efca5e6..1814f80b4 100644 |
| --- a/internal/console/server.go |
| +++ b/internal/console/server.go |
| @@ -1662,7 +1662,7 @@ func NewServer(cfg Config, st *Store) (*Server, error) { |
| s.registerRoute("GET /auth/stepup/callback", s.handleStepUpCallback) |
| s.registerRoute("GET /auth/confirm", s.handleConfirm) |
| s.registerRoute("POST /auth/signout", s.handleSignout) |
| - s.registerRoute("GET /fleet", s.handleFleet) |
| + s.registerRoute("GET /fleet", s.handleDashboard) |
| s.registerRoute("GET /fleet/boxes", s.handleBoxes) |
| s.registerRoute("GET /fleet/index", s.handleOpIndex) |
| s.registerRoute("GET /fleet/store", s.handleStoreApprovalsPage) |
| @@ -1682,12 +1682,12 @@ func NewServer(cfg Config, st *Store) (*Server, error) { |
| // controls (econlistquery.go) over the same LoadEconomics rows. |
| s.registerRoute("GET /fleet/economics/accounts", s.handleEconomicsAccounts) |
| // Unit economics (Task 12): scenario/bill writes, operator-only, same |
| - // gate shape as handleFleet above. GET /fleet/economics is handled |
| + // gate shape as handleDashboard above. GET /fleet/economics is handled |
| // above by handleEconomics (Task 13). Registered WITHOUT a method |
| // prefix, deliberately: a |
| // "POST /path" pattern answers a GET with 405 + Allow, which leaks that |
| // the route exists to someone who merely guessed the URL — the exact |
| - // probe handleFleet's 404-to-everyone gate exists to prevent. Each |
| + // probe operatorOnly's 404-to-everyone gate exists to prevent. Each |
| // handler below checks r.Method itself, before anything else, so a |
| // wrong-method request is byte-identical to an unknown route. |
| s.registerRoute("/fleet/economics/scenarios", s.handleEconomicsScenarioSave) |
| @@ -2246,6 +2246,9 @@ type page struct { |
| // Jobs is the background jobs table (op_jobs) on Boxes. |
| Jobs []opJobRow |
| + // Dash is the dashboard's data (/fleet, opdashboard.go). |
| + Dash *dashView |
| + |
| // /fleet, below the published boxes table: the per-host PRIVATE detail |
| // read straight out of status/boxes/ (HostRows, view.go). Raw numbers |
| // render here and nowhere public — this page is session-gated to |
| @@ -3448,15 +3451,8 @@ func (s *Server) operatorOnly(w http.ResponseWriter, r *http.Request) (address, |
| return addr, raw, true |
| } |
| -// handleFleet serves /fleet. Its content moved to Boxes (handleBoxes, |
| -// opboxes.go); until the dashboard takes /fleet over it answers what Boxes |
| -// answers, behind the same gate. |
| -func (s *Server) handleFleet(w http.ResponseWriter, r *http.Request) { |
| - s.handleBoxes(w, r) |
| -} |
| - |
| // handleFleetMetrics serves the operator host/process monitoring dashboard — |
| -// same gate as handleFleet, same reasoning: every non-operator path is a |
| +// same gate as handleDashboard, same reasoning: every non-operator path is a |
| // plain http.NotFound so the route's existence is not probeable. |
| func (s *Server) handleFleetMetrics(w http.ResponseWriter, r *http.Request) { |
| addr, raw, ok := s.operatorOnly(w, r) |
diff --git a/internal/console/static/ops.css b/internal/console/static/ops.css| index d40785ccd..126fd5556 100644 |
| --- a/internal/console/static/ops.css |
| +++ b/internal/console/static/ops.css |
| @@ -38,3 +38,36 @@ |
| [co-table] th, [co-table] td { border-block-end: 1px solid var(--rst-line); padding: 0.55rem 1rem; text-align: start; vertical-align: top; white-space: nowrap; } |
| [co-table] th { color: var(--rst-text-faint); font-size: var(--rst-fs-xs); font-weight: 550; letter-spacing: 0.05em; text-transform: uppercase; } |
| [co-table] tr:last-child > td { border-block-end: 0; } |
| + |
| +/* The dashboard's needs-attention list, inside Rastrillo's callout. */ |
| +[co-attention] { margin: 0; padding-inline-start: 1.1rem; } |
| +[co-attention] li { margin: 0.15rem 0; } |
| + |
| +/* The dashboard's new-people chart: one bar per day, oldest first, each |
| + bar's height a bucket of 5% (co-h 0 to 20) set by the server, so the |
| + page carries no inline style. The bars are decoration: a visually hidden |
| + table beside them carries each day's count. */ |
| +[co-bars] { align-items: flex-end; block-size: 4.5rem; display: flex; gap: 4px; padding: 1rem 1.25rem 0.5rem; } |
| +[co-bar] { background: var(--rst-accent); border-radius: 3px 3px 0 0; flex: 1; min-block-size: 3px; opacity: 0.75; } |
| +[co-bars-axis] { color: var(--rst-text-faint); display: flex; font-size: 0.75rem; justify-content: space-between; padding: 0 1.25rem 0.9rem; } |
| +[co-h="0"] { block-size: 0%; } |
| +[co-h="1"] { block-size: 5%; } |
| +[co-h="2"] { block-size: 10%; } |
| +[co-h="3"] { block-size: 15%; } |
| +[co-h="4"] { block-size: 20%; } |
| +[co-h="5"] { block-size: 25%; } |
| +[co-h="6"] { block-size: 30%; } |
| +[co-h="7"] { block-size: 35%; } |
| +[co-h="8"] { block-size: 40%; } |
| +[co-h="9"] { block-size: 45%; } |
| +[co-h="10"] { block-size: 50%; } |
| +[co-h="11"] { block-size: 55%; } |
| +[co-h="12"] { block-size: 60%; } |
| +[co-h="13"] { block-size: 65%; } |
| +[co-h="14"] { block-size: 70%; } |
| +[co-h="15"] { block-size: 75%; } |
| +[co-h="16"] { block-size: 80%; } |
| +[co-h="17"] { block-size: 85%; } |
| +[co-h="18"] { block-size: 90%; } |
| +[co-h="19"] { block-size: 95%; } |
| +[co-h="20"] { block-size: 100%; } |
diff --git a/internal/console/templates/ops_dashboard.html b/internal/console/templates/ops_dashboard.html| new file mode 100644 |
| index 000000000..808a8b381 |
| --- /dev/null |
| +++ b/internal/console/templates/ops_dashboard.html |
| @@ -0,0 +1,79 @@ |
| +{{/* The dashboard (/fleet, opdashboard.go): the approved mockup top to |
| + bottom. The callout, the headline band, the new-people chart, newest |
| + people, latest activity, boxes and background jobs. Every number and |
| + word computed in Go arrives in .Dash. */}} |
| +{{define "ops_dashboard"}}{{template "op_top" .}} |
| +{{template "op_page_header" (opHeader .Title (printf "Who uses %s, what they do, and whether everything is running." .Brand))}} |
| +{{with .Dash}} |
| +<div rst-callout rst-tone="{{.Tone}}"> |
| + <span rst-callout-ic aria-hidden="true">{{icon .Icon}}</span> |
| + <div rst-callout-body> |
| + <strong>{{.Title}}</strong> |
| + {{- if .Attention}} |
| + <ul co-attention> |
| + {{- range .Attention}} |
| + <li>{{.Lead}}{{with .Code}}<code>{{.}}</code>{{end}}{{.Tail}}{{if .Href}} <a href="{{.Href}}">{{.Link}}</a>{{end}}</li> |
| + {{- end}} |
| + </ul> |
| + {{- end}} |
| + </div> |
| +</div> |
| +{{with .Stats}} |
| +<div rst-stats rst-card> |
| + {{- range .}} |
| + {{template "op_stat" .}} |
| + {{- end}} |
| +</div> |
| +{{end}} |
| +<div rst-box-head><h2>New people, last 30 days</h2></div> |
| +<div rst-card> |
| +{{- if .Bars}} |
| + <div co-bars aria-hidden="true"> |
| + {{- range .Bars}}<span co-bar co-h="{{.H}}"></span>{{end}} |
| + </div> |
| + <div co-bars-axis aria-hidden="true"><span>{{(index .Bars 0).Day.Format "2 Jan"}}</span><span>Today</span></div> |
| + <table class="rst-sr-only"> |
| + <caption>New people each day, last 30 days</caption> |
| + <tr><th scope="col">Day</th><th scope="col">New people</th></tr> |
| + {{- range .Bars}} |
| + <tr><td>{{.Day.Format "2 Jan"}}</td><td>{{.N}}</td></tr> |
| + {{- end}} |
| + </table> |
| +{{- end}} |
| +</div> |
| + |
| +<div rst-box-head><h2>Newest people</h2><a rst-btn="ghost" href="/fleet/people">All people</a></div> |
| +{{if .Newest}} |
| +<div rst-card co-cols="people"> |
| + <div rst-lrow="head"><span>Person</span><span>Account</span><span>Joined</span><span>Apps</span></div> |
| + {{- range .Newest}} |
| + <div rst-lrow><span class="rst-nm">{{.Address}}</span>{{if .FirstAccount}}<span>{{.FirstAccount}}</span>{{else}}<span class="rst-cell-mut">none</span>{{end}}<span class="rst-cell-mut" title="{{fmtTime .Joined}}">{{ago .Joined}}</span><span>{{opnum .Apps}}</span></div> |
| + {{- end}} |
| +</div> |
| +{{else}}{{template "op_empty" (opEmpty "" "No one has signed up yet.")}}{{end}} |
| + |
| +<div rst-box-head><h2>Latest activity</h2><a rst-btn="ghost" href="/fleet/activity">All activity</a></div> |
| +{{if .Activity}} |
| +<div rst-card co-cols="activity"> |
| + <div rst-lrow="head"><span>When</span><span>Who</span><span>What</span><span>App</span></div> |
| + {{- range .Activity}} |
| + <div rst-lrow><span class="rst-cell-mut" title="{{fmtTime .At}}">{{ago .At}}</span><span>{{.Address}}</span><span>{{.Detail}}</span>{{if .App}}<span>{{.App}}</span>{{else}}<span class="rst-cell-mut">none</span>{{end}}</div> |
| + {{- end}} |
| +</div> |
| +{{else}}{{template "op_empty" (opEmpty "" "Nothing has happened yet.")}}{{end}} |
| +{{end}} |
| +{{template "ops_dashboard_boxes" .Dash}} |
| +{{template "op_jobs" .Dash.Jobs}} |
| +{{template "op_bottom" .}}{{end}} |
| + |
| +{{/* The dashboard's Boxes section (data *dashView): one row per box, its |
| + status, region, memory in use as a meter, and when it last reported. */}} |
| +{{define "ops_dashboard_boxes"}}<div rst-box-head><h2>Boxes</h2><a rst-btn="ghost" href="/fleet/boxes">All boxes</a></div> |
| +{{if .Boxes}} |
| +<div rst-card co-cols="boxes"> |
| + <div rst-lrow="head"><span>Box</span><span>Status</span><span>Region</span><span>Load</span><span>Last report</span></div> |
| + {{- range .Boxes}} |
| + <div rst-lrow><a class="rst-nm" href="/fleet/boxes#box-{{.Label}}">{{.Label}}</a><span>{{template "op_status" .Status}}</span>{{if eq .Region .Unknown}}<span class="rst-cell-mut">{{.Region}}</span>{{else}}<span>{{.Region}}</span>{{end}}{{with .Meter}}<span>{{template "op_meter" .}}</span>{{else}}<span class="rst-cell-mut">{{.Unknown}}</span>{{end}}{{if .LastSeen.IsZero}}<span class="rst-cell-mut">{{.Unknown}}</span>{{else}}<span class="rst-cell-mut" title="{{fmtTime .LastSeen}}">{{ago .LastSeen}}</span>{{end}}</div> |
| + {{- end}} |
| +</div> |
| +{{else}}{{template "op_empty" (opEmpty "" "No box has published a reading yet.")}}{{end}}{{end}} |
diff --git a/internal/console/testdata/perf-budgets.txt b/internal/console/testdata/perf-budgets.txt| index e97fc0aaa..324f18171 100644 |
| --- a/internal/console/testdata/perf-budgets.txt |
| +++ b/internal/console/testdata/perf-budgets.txt |
| @@ -61,7 +61,7 @@ GET /a/{sqid}/plan/keep over: the lapse inventory lists every app's instance rec |
| GET /a/{sqid}/settings calls 2: the account telemetry settings and the storage entitlement |
| GET /a/{sqid}/{$} over: a warm view reads nothing (0 S3 calls; each app's frame is cached); a cold view reads every app's frame (6 S3 calls per app, about 155 ms for one) |
| GET /a/{sqid}/trash over: reads each trashed app's deleted.json marker (1 S3 call warm and cold per app) |
| -GET /fleet over: lists and reads every box report, reads status/fleet.json, and lists and reads the storage entitlements (8 S3 calls warm and cold, median about 260 ms) |
| +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; operator pages are seldom viewed and carry no cache, and its SQLite reads add no remote call (8 S3 calls warm and cold, median about 270 ms) |
| GET /fleet/boxes over: lists and reads every box report, reads status/fleet.json, and lists and reads the storage entitlements; operator pages are seldom viewed and carry no cache (8 S3 calls warm and cold, median about 260 ms) |
| 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) |