console: /fleet/traffic
Implement Task 7 only: an operator-only traffic page reading console.db, with incident-driven tiles, hourly/daily stacks, explicit gaps and partial bars, retained top lists, and the counting-start date. Keep draft page copy together in trafficPageCopy for Task 6. The tile rule IDs include fleet_5xx and abuse_surge; their deferred Task 5 evaluators are not added. Use a read-only open-incident query because AlertStepInputs prunes flap history. Register the route and rail item, update claim/performance/shot fixtures, and layer the record-write census over rootfs-apps-6. NewServer adds only this GET route; its record-write classification is unchanged. Plan/code drift: trafficChart and buildTrafficChart already belong to Analytics, so the fleet types use fleetTrafficChart and buildFleetTrafficChart. Reuse Analytics axis helpers with SVG geometry and static operator CSS to honor the shell's no-inline-style contract. The performance registry represents zero calls by no exception entry, so document that default and measure all ranges in a dedicated test. Validation: targeted console traffic, operator shell/gates, route census, Perf and owner-metrics tests pass, as does the complete claim mutation invariant. The record-write census passes. Targeted race runs pass in console and provision; go vet on both and gofmt on touched files pass. Two mutations were caught: bypassing operatorOnly and making hostile hostnames into links. Both were restored before final validation. Independent Opus review remains pending; this implementer run is offline.
Co-Authored-By: GPT-6 Astra (codex) <noreply@openai.com>
internal/console/claim_invariant_fixtures_test.go+1 −0internal/console/claim_invariant_probes_read_test.go+1 −0internal/console/opshell.go+1 −0internal/console/opshell_test.go+10 −2internal/console/opshots_test.go+2 −0internal/console/perfwalk_test.go+1 −0internal/console/server.go+4 −0internal/console/static/ops.css+19 −0internal/console/templates/fleet_traffic.html+63 −0internal/console/testdata/claim-routes.txt+1 −0internal/console/testdata/perf-budgets.txt+2 −0internal/console/trafficview.go+323 −0internal/console/trafficview_test.go+307 −0internal/provision/fleet_traffic_census_test.go+28 −0internal/provision/plan9_b8_census_test.go+1 −1
Intent
<task-notification> <task-id>bv62ev73f</task-id> <tool-use-id>toolu_01DCC3hEXHyTWbcmT1fmqDA1</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/1f8653ea-6b78-4712-b1ac-1eb863a870a6/tasks/bv62ev73f.output</output-file> <status>completed</status> <summary>Background command "After build C, launch the Task 2 fix run and wait" completed (exit code 0)</summary> </task-notification>
<task-notification> <task-id>a291e1f8f5d6d1aca</task-id> <tool-use-id>toolu_01MwKL8hEoDSTQYigc2s8ZUa</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/1f8653ea-6b78-4712-b1ac-1eb863a870a6/tasks/a291e1f8f5d6d1aca.output</output-file> <status>completed</status> <summary>Agent "Opus review of Task 2 edge counters" finished</summary> <note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note> <result>**Verdict: APPROVED.** Commit dea05cfe fixes both blocking items (I1, I2), and the M3 strip doesn't touch hop responses. `go test ./internal/edge -run Traffic -count=1` passes (4.7s). | Item | Status | Evidence | |---|---|---| | **I1** path masking under the mutex | Resolved | The 404 path key is now built before the lock (`traffic.go:215-218`). | | **I2** wall-clock flake | Resolved | The counter has a `now` field. Every traffic call site uses `c.now()`: `observeIngress`, `served` (`edge.go`, `assetcatch.go`), guard, rate and plan. `enableTestTraffic` pins it to a fixed time before storing the counter. The only `time.Now()` left in `traffic.go` is in `EnableTraffic`. | | **M1** answers dropped at boundaries | Resolved | The cutoff is now `at < c.first`, so a late answer counts into the open window. `TestTrafficLateCountsRetained` covers all five counting methods. | | **M2** guard counts need the usage meter | Resolved | `guard.go:109-125` no longer returns early without a meter. `TestEdgeTrafficGuardWithoutUsageMeter` covers it. | | **M3** app-forged `X-Carlos-Ref` | Resolved | See below. | | **M4** long requests counted at completion | Partly | See below. | | **M5** per-request allocations | Deferred | Fine as deferred. | | **M6** redundant `hopDoorFrom` check | Resolved | Removed. | | **M7** host test skips the `statusLoop` line | Accepted | Fine as accepted. | **M3: where the strip happens.** The header is deleted in `responseModifier` (`cookiescope.go:94`). That hook is attached only to the five tenant proxy arms (`edge.go:932, 975, 1005, 1021, 1073`). - The backhaul and forward hop proxies don't use `responseModifier`, so the home's block page keeps its header across the hop. `TestEdgeTrafficIngressHomeRefusalKeepsClass` (backhaul) and the new `TestEdgeTrafficForwardGuardKeepsRefusal` cover this. - The forward, fleet and tunnel arms now strip it too. That loses no real block page, because the hub runs the guard itself and the box behind the tunnel skips the guard for tunnelled requests. - `TestEdgeTrafficAppCannotForgeRefusal` checks that an app's own 404 now counts as S404. **M4: why it's only partly fixed.** `answeredAt` (`traffic.go:468, 497-500`) is used as `at`, but windows only move forward and the guard is now `at < first`. So an older `at` only lands in the right window when nothing has moved the window on since the answer. On a busy box, a long stream still counts in the window where it finishes, and a restart still loses streams that are open. `TestTrafficIngressAnswerTime` passes only because nothing else moves the window in that test. Either: - describe the behaviour as "counted at completion", or - count the answer at `WriteHeader`/`Hijack` time. That needs care, because the steering-probe skip is noted after the probe has already written its answer. M4 is Minor and the plan counts by final status, so this doesn't block. **One new small issue.** A request answered before `first` (the counter's partial first window) but finishing later is now dropped, even though the window it finishes in is fully observed. This only affects streams opened in the first five minutes after a start. A one-line fix: when `answeredAt` is earlier than `first`, fall back to `c.now()`.</result> <usage><subagent_tokens>146296</subagent_tokens><tool_uses>6</tool_uses><duration_ms>84821</duration_ms></usage> </task-notification>
One more docs item from platform-86, for your branch, which already edits docs/superpowers/notes/roll-fleet-alerts-1.md. Paul backed up flagship's alert-connectors.key to 1Password on 2026-11-01: item "CARLOS alert-connectors.key (flagship)", vault Carloku, account teamtito.1password.com, stored as base64 of /data/console/alert-connectors.key on the flagship console box. Please add a short 'Back up and restore the connector key' section to the roll notes, and a line in the README's seal-key paragraph. Back up: base64 the file into a 1Password item, one per deployment, and never print the value. Restore: base64 -d into the path, chown carlos:carlos, chmod 600, before the console starts. Back it up again whenever the key is recreated, which the engine logs as 'made a new seal key'. Dev has no backup yet; say it is optional while dev has no Slack or webhook connectors. Don't block on this; fold it into your next commit.
diff --git a/internal/console/claim_invariant_fixtures_test.go b/internal/console/claim_invariant_fixtures_test.go| index b31702bef..8c8e0ee05 100644 |
| --- a/internal/console/claim_invariant_fixtures_test.go |
| +++ b/internal/console/claim_invariant_fixtures_test.go |
| @@ -917,6 +917,7 @@ var claimFixtures = map[string]claimFixture{ |
| "route GET /fleet/metrics": claimRead("operator box metrics"), |
| "route GET /fleet/people": claimRead("operator people and accounts list; SQLite only"), |
| "route GET /fleet/people/{address}": claimRead("operator person page; SQLite only, writes nothing"), |
| + "route GET /fleet/traffic": claimRead("operator traffic page: SQLite traffic hours, windows and open fleet incidents; writes nothing"), |
| "route GET /fleet/protection": claimRead("operator protection page: the edge days of every fleet and the root boxes, read from the bucket; writes nothing"), |
| "route GET /fleet/protection/data": claimRead("the operator protection page as JSON; writes nothing"), |
| "route GET /fleet/store": claimRead("operator entitlement queue page"), |
diff --git a/internal/console/claim_invariant_probes_read_test.go b/internal/console/claim_invariant_probes_read_test.go| index 4ae166633..2361097f7 100644 |
| --- a/internal/console/claim_invariant_probes_read_test.go |
| +++ b/internal/console/claim_invariant_probes_read_test.go |
| @@ -223,6 +223,7 @@ var claimReadProbes = map[string]claimProbe{ |
| "route GET /fleet/metrics": claimPageRead(nil, "/fleet/metrics", "<h1>Metrics</h1>"), |
| "route GET /fleet/people": claimPageRead(nil, "/fleet/people", "<h1>People and accounts</h1>"), |
| "route GET /fleet/people/{address}": claimPageRead(nil, "/fleet/people/paul@keymail.dev", "<h1>paul@keymail.dev</h1>"), |
| + "route GET /fleet/traffic": claimPageRead(nil, "/fleet/traffic", "<h1>Traffic</h1>"), |
| "route GET /fleet/protection": claimPageRead(nil, "/fleet/protection", "<h1>Protection</h1>"), |
| "route GET /fleet/protection/data": claimPageRead(nil, "/fleet/protection/data", `"unreadable_fleets"`), |
| "route GET /fleet/store": claimPageRead(claimWorldApply, "/fleet/store", "<h1>Storage requests</h1>"), |
diff --git a/internal/console/opshell.go b/internal/console/opshell.go| index 0cf2b8282..350fb6b9e 100644 |
| --- a/internal/console/opshell.go |
| +++ b/internal/console/opshell.go |
| @@ -29,6 +29,7 @@ type opRailItem struct { |
| // opRail is the rail, top to bottom. Each label is also its page's <h1>. |
| var opRail = []opRailItem{ |
| {Key: "dashboard", Href: "/fleet", Label: "Dashboard"}, |
| + {Key: "traffic", Href: "/fleet/traffic", Label: trafficPageCopy["title"]}, |
| {Key: "people", Href: "/fleet/people", Label: "People and accounts"}, |
| {Key: "activity", Href: "/fleet/activity", Label: "Activity"}, |
| {Key: "boxes", Href: "/fleet/boxes", Label: "Boxes"}, |
diff --git a/internal/console/opshell_test.go b/internal/console/opshell_test.go| index 3127886d3..274a9e952 100644 |
| --- a/internal/console/opshell_test.go |
| +++ b/internal/console/opshell_test.go |
| @@ -201,8 +201,8 @@ func TestRailHidesStorageFromOtherOperators(t *testing.T) { |
| t.Fatalf("/fleet/index = %d", status) |
| } |
| links := opNavLinks(t, body) |
| - if len(links) != 9 { |
| - t.Fatalf("the rail has %d links, want 9: %+v", len(links), links) |
| + if len(links) != 10 { |
| + t.Fatalf("the rail has %d links, want 10: %+v", len(links), links) |
| } |
| if strings.Contains(body, `href="/fleet/store"`) { |
| t.Fatal("an operator not on StoreOperators is shown /fleet/store") |
| @@ -410,3 +410,11 @@ func TestOpPartialsRender(t *testing.T) { |
| t.Errorf("a list bar with no query: %s", got) |
| } |
| } |
| + |
| +// TestOpShellTrafficRailPosition keeps the traffic screen beside Dashboard, |
| +// where operators find the fleet's health before drilling into people. |
| +func TestOpShellTrafficRailPosition(t *testing.T) { |
| + if len(opRail) < 3 || opRail[0].Key != "dashboard" || opRail[1].Key != "traffic" || opRail[2].Key != "people" { |
| + t.Fatalf("rail order: %+v", opRail) |
| + } |
| +} |
diff --git a/internal/console/opshots_test.go b/internal/console/opshots_test.go| index 2ac5541b8..b555a9a60 100644 |
| --- a/internal/console/opshots_test.go |
| +++ b/internal/console/opshots_test.go |
| @@ -26,6 +26,7 @@ import ( |
| var opShotPages = []struct{ name, path string }{ |
| {"index", "/fleet/index"}, |
| {"dashboard", "/fleet"}, |
| + {"traffic", "/fleet/traffic"}, |
| {"boxes", "/fleet/boxes"}, |
| {"store", "/fleet/store"}, |
| {"people", "/fleet/people"}, |
| @@ -60,6 +61,7 @@ func seedOperatorShotExtras(t *testing.T, fx *consoleFixture) { |
| if err := metrics.WriteRaw(ctx, fx.rel, chunk); err != nil { |
| t.Fatal(err) |
| } |
| + putTrafficViewHour(t, fx.st, trafficViewHour(now.Truncate(time.Hour).Add(-time.Hour))) |
| seedEconomicsGolden(t, fx) |
| month := usage.MonthOf(now) |
| putStoreJSON(t, fx.rel, economics.BillKey(month), economics.Bill{Schema: 1, Month: month, TotalUSD: 12.5, |
diff --git a/internal/console/perfwalk_test.go b/internal/console/perfwalk_test.go| index 03a4c8fbd..02537eb0c 100644 |
| --- a/internal/console/perfwalk_test.go |
| +++ b/internal/console/perfwalk_test.go |
| @@ -586,6 +586,7 @@ func perfOperatorTargets() map[string][]perfTarget { |
| "GET /fleet/people": ok("/fleet/people", "/fleet/people?show=accounts", "/fleet/people?q=person-1", |
| "/fleet/people?show=accounts&q=shop-1", "/fleet/people?page=3"), |
| "GET /fleet/activity": activity, |
| + "GET /fleet/traffic": ok("/fleet/traffic", "/fleet/traffic?range=7d", "/fleet/traffic?range=30d", "/fleet/traffic?range=junk"), |
| // A scale person: an owner with apps, other members and audit rows. |
| "GET /fleet/people/{address}": ok("/fleet/people/person-0@example.com"), |
| } |
diff --git a/internal/console/server.go b/internal/console/server.go| index 7d3a98e94..5eee8e95b 100644 |
| --- a/internal/console/server.go |
| +++ b/internal/console/server.go |
| @@ -1837,6 +1837,8 @@ func NewServer(cfg Config, st *Store) (*Server, error) { |
| s.registerRoute("POST /alerts/snooze/{token}", s.handleAlertSnooze) |
| s.registerRoute("GET /alerts/signing-key", s.handleAlertSigningKey) |
| s.registerRoute("GET /fleet/economics", s.handleEconomics) |
| + // Fleet traffic reads console.db counters and incidents, behind operatorOnly. |
| + s.registerRoute("GET /fleet/traffic", s.handleFleetTraffic) |
| // The operator's Protection page (protectionview.go) and its JSON door: |
| // what the edge guard did across every app. Operators only, as Economics. |
| s.registerRoute("GET /fleet/protection", s.handleFleetProtection) |
| @@ -2694,6 +2696,8 @@ type page struct { |
| Protection *protectionView |
| // FleetProtection is the operator's page of the same name. |
| FleetProtection *fleetProtectionView |
| + // FleetTraffic reads retained ingress counts and open fleet incidents. |
| + FleetTraffic *fleetTrafficView |
| // Action confirm interstitial (confirm.go): what is about to happen, |
| // carried fields and all. Nil everywhere except the confirm page. |
diff --git a/internal/console/static/ops.css b/internal/console/static/ops.css| index 6ba6babb4..4cd0afc54 100644 |
| --- a/internal/console/static/ops.css |
| +++ b/internal/console/static/ops.css |
| @@ -240,3 +240,22 @@ |
| [co-archbox] h4 { font-size: var(--rst-fs-base); } |
| [co-archbox] p { margin-block: var(--rst-sp-1) 0; } |
| [co-fact] + [co-fact]::before { color: var(--rst-text-faint); content: " · "; } |
| + |
| +/* Fleet traffic shares Analytics' axis but keeps geometry in SVG attributes, |
| + as the operator shell has no inline styles. Scroll retains readable hour |
| + columns on a phone; missing columns have no fill and partial ones are pale. */ |
| +[co-traffic-tiles] { display: grid; grid-template-columns: repeat(auto-fit, minmax(12rem, 1fr)); gap: var(--rst-sp-3); } |
| +[co-traffic-chart] { margin-inline: 0; } |
| +[co-traffic-scroll] { overflow-x: auto; } |
| +[co-traffic-chart] svg { display: block; } |
| +[co-traffic-chart] text { fill: var(--rst-text-muted); font: 11px var(--rst-font); } |
| +[co-traffic-chart] line, [co-traffic-chart] .traffic-gap { stroke: var(--rst-line); } |
| +[co-traffic-chart] .traffic-gap { stroke-dasharray: 2 3; } |
| +[co-traffic-chart] .traffic-partial rect { opacity: 0.45; } |
| +[co-traffic-chart] g:focus { outline: 2px solid var(--rst-accent); } |
| +.traffic-served { fill: var(--rst-accent); color: var(--rst-accent); } |
| +.traffic-4xx { fill: var(--rst-text-muted); color: var(--rst-text-muted); } |
| +.traffic-5xx { fill: var(--rst-tone-negative-fg); color: var(--rst-tone-negative-fg); } |
| +.traffic-refused { fill: var(--rst-tone-warning-fg); color: var(--rst-tone-warning-fg); } |
| +[co-traffic-legend] { display: flex; flex-wrap: wrap; gap: var(--rst-sp-3); padding: 0; list-style: none; } |
| +[co-traffic-legend] li::before { content: ""; display: inline-block; background: currentColor; inline-size: 0.75em; block-size: 0.75em; margin-inline-end: 0.3em; } |
diff --git a/internal/console/templates/fleet_traffic.html b/internal/console/templates/fleet_traffic.html| new file mode 100644 |
| index 000000000..e71a07711 |
| --- /dev/null |
| +++ b/internal/console/templates/fleet_traffic.html |
| @@ -0,0 +1,63 @@ |
| +{{/* Fleet traffic reads only console.db. Copy remains in trafficPageCopy until |
| + Task 6 reviews it; box-supplied strings stay ordinary escaped text. */}} |
| +{{define "fleet_traffic"}}{{template "op_top" .}} |
| +{{template "op_page_header" (opHeader .Title "")}} |
| +{{with .FleetTraffic}} |
| +{{template "op_seg_tabs" .Tabs}} |
| +{{if .Err}}<div rst-callout rst-tone="negative"><span rst-callout-ic aria-hidden="true">{{icon "triangle-alert"}}</span><div rst-callout-body><p>{{.Err}}</p></div></div> |
| +{{else}} |
| +<div co-traffic-tiles> |
| +{{range .Tiles}}<section rst-card data-state="{{.State}}"> |
| +<h2>{{.Name}}</h2><span rst-status{{if eq .State "watch"}} rst-tone="warning"{{else}} rst-tone="positive"{{end}}>{{index $.FleetTraffic.Copy .State}}</span> |
| +<p>{{if .Href}}<a href="{{.Href}}">{{.Line}}</a>{{else}}{{.Line}}{{end}}</p> |
| +</section>{{end}} |
| +</div> |
| +{{if .Started}}<p co-note>{{.Started}}</p>{{end}} |
| +<h2 id="traffic-chart">{{index .Copy "chart"}}</h2> |
| +{{if not .HasHours}}<p>{{index .Copy "empty.chart"}}</p>{{end}} |
| +{{template "traffic_chart" .Chart}} |
| +<h2 id="traffic-apps">{{index .Copy "apps"}}</h2> |
| +{{if .Sum.Apps}}<div rst-card class="co-table-wrap"><table co-table aria-labelledby="traffic-apps"> |
| +<tr><th scope="col">{{index .Copy "account"}}</th><th scope="col">{{index .Copy "app"}}</th><th scope="col">{{index .Copy "requests"}}</th><th scope="col">{{index .Copy "errors"}}</th></tr> |
| +{{range .Sum.Apps}}<tr><td>{{.Account}}</td><td>{{.App}}</td><td>{{count .Requests}}</td><td>{{count .S5xx}}</td></tr>{{end}} |
| +</table></div>{{else}}<p>{{index .Copy "empty.list"}}</p>{{end}} |
| +<h2 id="traffic-paths">{{index .Copy "paths"}}</h2> |
| +{{if .Sum.Paths}}<div rst-card class="co-table-wrap"><table co-table aria-labelledby="traffic-paths"> |
| +<tr><th scope="col">{{index .Copy "path"}}</th><th scope="col">{{index .Copy "hits"}}</th></tr> |
| +{{range .Sum.Paths}}<tr><td><a href="/fleet/protection">{{.Key}}</a></td><td>{{count .Hits}}</td></tr>{{end}} |
| +</table></div>{{else}}<p>{{index .Copy "empty.list"}}</p>{{end}} |
| +<h2 id="traffic-sources">{{index .Copy "sources"}}</h2> |
| +{{if .Sum.Sources}}<div rst-card class="co-table-wrap"><table co-table aria-labelledby="traffic-sources"> |
| +<tr><th scope="col">{{index .Copy "client"}}</th><th scope="col">{{index .Copy "country"}}</th><th scope="col">{{index .Copy "hits"}}</th></tr> |
| +{{range .Sum.Sources}}<tr><td><a href="/fleet/protection">{{.Client}}</a></td><td>{{.Country}}</td><td>{{count .Hits}}</td></tr>{{end}} |
| +</table></div>{{else}}<p>{{index .Copy "empty.list"}}</p>{{end}} |
| +<h2 id="traffic-hosts">{{index .Copy "hosts"}}</h2> |
| +{{if .Sum.Hosts}}<div rst-card class="co-table-wrap"><table co-table aria-labelledby="traffic-hosts"> |
| +<tr><th scope="col">{{index .Copy "host"}}</th><th scope="col">{{index .Copy "hits"}}</th></tr> |
| +{{range .Sum.Hosts}}<tr><td>{{.Key}}</td><td>{{count .Hits}}</td></tr>{{end}} |
| +</table></div>{{else}}<p>{{index .Copy "empty.list"}}</p>{{end}} |
| +<h2 id="traffic-rateapps">{{index .Copy "rateapps"}}</h2> |
| +{{if .Sum.RateApps}}<div rst-card class="co-table-wrap"><table co-table aria-labelledby="traffic-rateapps"> |
| +<tr><th scope="col">{{index .Copy "account"}}</th><th scope="col">{{index .Copy "app"}}</th><th scope="col">{{index .Copy "rate.refused"}}</th><th scope="col">{{index .Copy "rate.observed"}}</th></tr> |
| +{{range .Sum.RateApps}}<tr><td>{{.Account}}</td><td>{{.App}}</td><td>{{count .Refused}}</td><td>{{count .Observed}}</td></tr>{{end}} |
| +</table></div>{{else}}<p>{{index .Copy "empty.list"}}</p>{{end}} |
| +{{end}}{{end}}{{template "op_bottom" .}}{{end}} |
| + |
| +{{/* SVG attributes carry measured geometry without inline styles. An absent |
| + column contains its label and a dotted baseline only, never a rectangle. |
| + Focusable columns expose the complete counts without needing JavaScript. */}} |
| +{{define "traffic_chart"}} |
| +<figure co-traffic-chart aria-labelledby="traffic-chart"> |
| +<div co-traffic-scroll> |
| +<svg xmlns="http://www.w3.org/2000/svg" width="{{.Width}}" height="240" viewBox="0 0 {{.Width}} 240" role="group" aria-label="{{index .Copy "chart"}}"> |
| +{{range .Ticks}}<g aria-hidden="true"><line x1="44" x2="{{$.Width}}" y1="{{.Pct}}" y2="{{.Pct}}"/><text x="40" y="{{.Pct}}" text-anchor="end">{{.Label}}</text></g>{{end}} |
| +{{range .Cols}}<g transform="translate({{.X}} 0)" data-gap="{{.Gap}}"{{if and .Partial (not .Gap)}} class="traffic-partial"{{end}} tabindex="0" role="img" aria-label="{{.Label}}"><title>{{.Label}}</title> |
| +{{if .Gap}}<path class="traffic-gap" d="M 0 200 h 18"/> |
| +{{else}}{{range .Segments}}<rect class="traffic-{{.Kind}}" x="0" y="{{.Y}}" width="18" height="{{.Height}}"/>{{end}}{{end}} |
| +</g>{{end}} |
| +{{range .XLabels}}<text x="{{.Col}}" y="225" aria-hidden="true">{{.Label}}</text>{{end}} |
| +</svg> |
| +</div> |
| +<figcaption>{{index .Copy "chart.legend"}}<ul co-traffic-legend><li class="traffic-served">{{index .Copy "served"}}</li><li class="traffic-4xx">{{index .Copy "4xx"}}</li><li class="traffic-5xx">{{index .Copy "5xx"}}</li><li class="traffic-refused">{{index .Copy "refused"}}</li></ul></figcaption> |
| +</figure> |
| +{{end}} |
diff --git a/internal/console/testdata/claim-routes.txt b/internal/console/testdata/claim-routes.txt| index c871c2429..f21ec2b1b 100644 |
| --- a/internal/console/testdata/claim-routes.txt |
| +++ b/internal/console/testdata/claim-routes.txt |
| @@ -144,6 +144,7 @@ route GET /fleet/people/{address} |
| route GET /fleet/protection |
| route GET /fleet/protection/data |
| route GET /fleet/store |
| +route GET /fleet/traffic |
| route GET /healthz |
| route GET /invite/{token} |
| route GET /settings |
diff --git a/internal/console/testdata/perf-budgets.txt b/internal/console/testdata/perf-budgets.txt| index 438ae93d7..058f48f7b 100644 |
| --- a/internal/console/testdata/perf-budgets.txt |
| +++ b/internal/console/testdata/perf-budgets.txt |
| @@ -109,3 +109,5 @@ POST /a/{sqid}/apps/{app}/promote over: promoting v2 to stable reads and writes |
| # /fleet/economics (cold 146 S3 calls, about 410 ms), /fleet/economics/accounts |
| # and /fleet/metrics (cold 98 S3 calls, about 160 ms). |
| + |
| +# GET /fleet/traffic uses the default zero-call budget: every range reads console.db only. |
diff --git a/internal/console/trafficview.go b/internal/console/trafficview.go| new file mode 100644 |
| index 000000000..db7b1417e |
| --- /dev/null |
| +++ b/internal/console/trafficview.go |
| @@ -0,0 +1,323 @@ |
| +package console |
| + |
| +import ( |
| + "database/sql" |
| + "encoding/json" |
| + "fmt" |
| + "log" |
| + "net/http" |
| + "slices" |
| + "strings" |
| + "time" |
| +) |
| + |
| +// trafficPageCopy is the draft deck for Task 6. Keep page labels, evidence, |
| +// accessible chart descriptions and the rail title here so review can replace |
| +// them together. Existing rule titles still come from the alert copy deck. |
| +var trafficPageCopy = map[string]string{ |
| + "title": "Traffic", "range": "Period", "24h": "24 hours", "7d": "7 days", "30d": "30 days", |
| + "healthy": "Healthy", "abuse": "Abuse", "load": "Load", "capacity": "Capacity", |
| + "ok": "OK", "watch": "Watch", "watch.one": "%s: 1 member", "watch.many": "%s: %s members", |
| + "healthy.line": "%s of answered requests were 5xx in the last 24 hours.", |
| + "healthy.noanswers": "No answered requests counted in the last 24 hours.", |
| + "abuse.line": "%s blocked or watched in the last 24 hours.", |
| + "load.line": "No open CPU or memory incidents.", "capacity.line": "No open capacity incidents.", |
| + "empty.counts": "No traffic counted in the last 24 hours.", |
| + "empty.chart": "No traffic counts in this range yet.", "empty.list": "No entries in this range.", |
| + "error": "Traffic could not be read. Try again shortly.", "started": "Counting started %s.", |
| + "chart": "Requests across every edge", "gap": "No data", "partial": "partial", "counting": "still counting", |
| + "served": "served", "4xx": "4xx", "5xx": "5xx", "refused": "blocked or refused", |
| + "chart.count": "%s %s", "chart.column": "%s: %s", "chart.legend": "Served, 4xx, 5xx, and blocked or refused. Gaps have no data; lighter bars are partial.", |
| + "apps": "Busiest apps", "paths": "Probe paths", "sources": "Blocked sources", "hosts": "Unknown hostnames", "rateapps": "Rate-limited apps", |
| + "account": "Account", "app": "App", "requests": "Requests", "errors": "5xx", "path": "Path", "hits": "Hits", |
| + "client": "Client", "country": "Country", "host": "Hostname", "rate.refused": "Refused", "rate.observed": "Observed", |
| + "rule.fleet_5xx": "Fleet 5xx rate", "rule.abuse_surge": "Abuse surge", |
| +} |
| + |
| +// trafficTile carries evidence from the same open incidents the alert engine |
| +// owns; a missing observation never creates or clears a Watch here. |
| +type trafficTile struct{ Key, Name, State, Line, Href string } |
| + |
| +// trafficRuleTitle supplies draft titles only for the two rules Task 5 has not |
| +// registered yet. Task 6 can replace them without changing the tile mapping. |
| +func trafficRuleTitle(rule string) string { |
| + if title := trafficPageCopy["rule."+rule]; title != "" { |
| + return title |
| + } |
| + return alertRuleTitle(rule) |
| +} |
| + |
| +// trafficTiles derives status solely from fleet incidents. The oldest matching |
| +// incident supplies both the evidence and destination, even during a quiet |
| +// flapping hold; measured daily totals only explain tiles with no incident. |
| +func trafficTiles(open []alertIncident, day trafficSum, dayOK bool) []trafficTile { |
| + table := []struct { |
| + key string |
| + rules []string |
| + }{ |
| + {"healthy", []string{"fleet_5xx", "service_down", "box_silent"}}, |
| + {"abuse", []string{"abuse_surge"}}, {"load", []string{"cpu", "mem"}}, |
| + {"capacity", []string{"disk_eta", "disk", "cert_expiring"}}, |
| + } |
| + var tiles []trafficTile |
| + for _, row := range table { |
| + tile := trafficTile{Key: row.key, Name: trafficPageCopy[row.key], State: "ok"} |
| + switch row.key { |
| + case "healthy": |
| + tile.Line = trafficPageCopy["empty.counts"] |
| + if dayOK { |
| + tile.Line = trafficPageCopy["healthy.noanswers"] |
| + if day.Answered() > 0 { |
| + tile.Line = fmt.Sprintf(trafficPageCopy["healthy.line"], fmt.Sprintf("%.2f%%", 100*float64(day.S5xx)/float64(day.Answered()))) |
| + } |
| + } |
| + case "abuse": |
| + tile.Line = trafficPageCopy["empty.counts"] |
| + if dayOK { |
| + tile.Line = fmt.Sprintf(trafficPageCopy["abuse.line"], groupedCount(day.Blocked+day.Watched)) |
| + } |
| + default: |
| + tile.Line = trafficPageCopy[row.key+".line"] |
| + } |
| + var oldest *alertIncident |
| + for i := range open { |
| + in := &open[i] |
| + if in.Scope != alertScopeFleet || !in.ClosedAt.IsZero() || !slices.Contains(row.rules, in.Rule) { |
| + continue |
| + } |
| + if oldest == nil || in.OpenedAt.Before(oldest.OpenedAt) || (in.OpenedAt.Equal(oldest.OpenedAt) && in.ID < oldest.ID) { |
| + oldest = in |
| + } |
| + } |
| + if oldest != nil { |
| + tile.State = "watch" |
| + tile.Href = fmt.Sprintf("/fleet/alerts/history#incident-%d", oldest.ID) |
| + tile.Line = fmt.Sprintf(trafficPageCopy["watch.many"], trafficRuleTitle(oldest.Rule), groupedCount(int64(len(oldest.Members)))) |
| + if len(oldest.Members) == 1 { |
| + tile.Line = fmt.Sprintf(trafficPageCopy["watch.one"], trafficRuleTitle(oldest.Rule)) |
| + } |
| + } |
| + tiles = append(tiles, tile) |
| + } |
| + return tiles |
| +} |
| + |
| +// OpenAlertIncidents is the page's read-only alternative to AlertStepInputs, |
| +// which prunes flap history. It has no history limit, so an old open incident |
| +// cannot vanish behind newer closed incidents and falsely turn a tile OK. |
| +func (s *Store) OpenAlertIncidents(scope string) ([]alertIncident, error) { |
| + rows, err := s.db.Query(`SELECT id, rule, opened_at, members FROM alert_incidents WHERE scope = ? AND closed_at IS NULL ORDER BY opened_at, id`, scope) |
| + if err != nil { |
| + return nil, err |
| + } |
| + defer rows.Close() |
| + var open []alertIncident |
| + for rows.Next() { |
| + in := alertIncident{Scope: scope} |
| + var opened int64 |
| + var members string |
| + if err := rows.Scan(&in.ID, &in.Rule, &opened, &members); err != nil { |
| + return nil, err |
| + } |
| + if err := json.Unmarshal([]byte(members), &in.Members); err != nil { |
| + return nil, fmt.Errorf("alert incident %d members: %w", in.ID, err) |
| + } |
| + in.OpenedAt = alertTime(opened) |
| + open = append(open, in) |
| + } |
| + return open, rows.Err() |
| +} |
| + |
| +// fleetTrafficView keeps the chart, lists and tiles behind one read-error state: |
| +// a broken query must not leave healthy-looking defaults on an operator page. |
| +type fleetTrafficView struct { |
| + Copy map[string]string |
| + Tabs opTabs |
| + Tiles []trafficTile |
| + Chart *fleetTrafficChart |
| + Sum trafficSum |
| + Err, Started string |
| + HasHours bool |
| +} |
| + |
| +// fleetTrafficChart uses Analytics' axis rounding and labels, with SVG geometry |
| +// instead of inline styles, which the operator shell deliberately forbids. |
| +type fleetTrafficChart struct { |
| + Cols []fleetTrafficCol |
| + Ticks []chartTick |
| + XLabels []chartXLabel |
| + Copy map[string]string |
| + Width int |
| +} |
| + |
| +// fleetTrafficCol preserves absent observations separately from measured zero. |
| +// Counts is the ingress partition: served, 4xx, 5xx, refused plus unknown host. |
| +type fleetTrafficCol struct { |
| + Start time.Time |
| + Counts [4]int64 |
| + Gap, Partial, Counting bool |
| + Label string |
| + X int |
| + Segments []fleetTrafficSegment |
| +} |
| + |
| +// fleetTrafficSegment places one stack in chart units; only measured, nonzero |
| +// counts create rectangles, so an absent column never looks like a zero bar. |
| +type fleetTrafficSegment struct { |
| + Kind string |
| + Y, Height float64 |
| +} |
| + |
| +// trafficRange fixes the number of visible UTC buckets, including the current |
| +// one. Invalid query strings share the default range rather than causing 400s. |
| +func trafficRange(rng string, now time.Time) (string, time.Time, time.Duration, int) { |
| + now = now.UTC() |
| + switch rng { |
| + case "7d": |
| + return rng, now.Truncate(time.Hour).Add(-167 * time.Hour), time.Hour, 168 |
| + case "30d": |
| + return rng, now.Truncate(24 * time.Hour).Add(-29 * 24 * time.Hour), 24 * time.Hour, 30 |
| + default: |
| + return "24h", now.Truncate(time.Hour).Add(-23 * time.Hour), time.Hour, 24 |
| + } |
| +} |
| + |
| +// buildFleetTrafficChart lays out every slot, including gaps. Daily bars add |
| +// only hours that arrived and stay partial if even one hour is missing. |
| +func buildFleetTrafficChart(hours []trafficHour, rng string, now time.Time) *fleetTrafficChart { |
| + _, start, step, n := trafficRange(rng, now) |
| + c := &fleetTrafficChart{Copy: trafficPageCopy, Width: n*24 + 72} |
| + byStart := make(map[int64]trafficHour, len(hours)) |
| + for _, h := range hours { |
| + byStart[h.Start.Unix()] = h |
| + } |
| + var peak int64 |
| + for i := 0; i < n; i++ { |
| + at := start.Add(time.Duration(i) * step) |
| + col := fleetTrafficCol{Start: at, Gap: true, Counting: now.Before(at.Add(step)), X: 48 + i*24} |
| + for h := at; h.Before(at.Add(step)); h = h.Add(time.Hour) { |
| + row, ok := byStart[h.Unix()] |
| + if !ok { |
| + col.Partial = true |
| + continue |
| + } |
| + col.Gap = false |
| + col.Partial = col.Partial || row.Partial(now) |
| + col.Counts[0] += row.Sum.S2xx + row.Sum.S3xx |
| + col.Counts[1] += row.Sum.S4xx + row.Sum.S404 |
| + col.Counts[2] += row.Sum.S5xx |
| + col.Counts[3] += row.Sum.Refused + row.Sum.UnknownHost |
| + } |
| + var total int64 |
| + for _, v := range col.Counts { |
| + total += v |
| + } |
| + peak = max(peak, total) |
| + when := at.Format("2006-01-02 15:00 UTC") |
| + if step > time.Hour { |
| + when = at.Format("2006-01-02") |
| + } |
| + var parts []string |
| + if col.Gap { |
| + parts = append(parts, trafficPageCopy["gap"]) |
| + } else { |
| + for j, key := range []string{"served", "4xx", "5xx", "refused"} { |
| + parts = append(parts, fmt.Sprintf(trafficPageCopy["chart.count"], groupedCount(col.Counts[j]), trafficPageCopy[key])) |
| + } |
| + if col.Partial { |
| + parts = append(parts, trafficPageCopy["partial"]) |
| + } |
| + } |
| + if col.Counting { |
| + parts = append(parts, trafficPageCopy["counting"]) |
| + } |
| + col.Label = fmt.Sprintf(trafficPageCopy["chart.column"], when, strings.Join(parts, ", ")) |
| + c.Cols = append(c.Cols, col) |
| + } |
| + top := niceCeil(max(peak, 1)) |
| + for i := range c.Cols { |
| + col := &c.Cols[i] |
| + y := 200.0 |
| + for j, key := range []string{"served", "4xx", "5xx", "refused"} { |
| + if col.Counts[j] == 0 { |
| + continue |
| + } |
| + height := float64(col.Counts[j]) / float64(top) * 180 |
| + y -= height |
| + col.Segments = append(col.Segments, fleetTrafficSegment{Kind: key, Y: y, Height: height}) |
| + } |
| + } |
| + // Pct is reused as the axis position: SVG's y direction is downward. |
| + c.Ticks = []chartTick{{Pct: 200, Label: "0"}, {Pct: 20, Label: compactCount(top)}} |
| + if top%2 == 0 { |
| + c.Ticks = append(c.Ticks, chartTick{Pct: 110, Label: compactCount(top / 2)}) |
| + } |
| + for _, i := range []int{0, n / 2, n - 1} { |
| + label := c.Cols[i].Start.Format("Jan 2") |
| + if step == time.Hour && n == 24 { |
| + label = c.Cols[i].Start.Format("Jan 2 15:00") |
| + } |
| + c.XLabels = append(c.XLabels, chartXLabel{Col: c.Cols[i].X, Label: label}) |
| + } |
| + return c |
| +} |
| + |
| +// readFleetTraffic reads console.db only. Daily tile evidence uses actual |
| +// five-minute rows over the last 24 hours; range lists use retained hour rows, |
| +// so the thirty-day view survives expiration of the seven-day source series. |
| +func (s *Store) readFleetTraffic(rng string, now time.Time) (*fleetTrafficView, error) { |
| + rng, from, _, _ := trafficRange(rng, now) |
| + v := &fleetTrafficView{Copy: trafficPageCopy} |
| + v.Tabs = opTabs{Label: trafficPageCopy["range"]} |
| + for _, r := range []string{"24h", "7d", "30d"} { |
| + v.Tabs.Items = append(v.Tabs.Items, opTab{Label: trafficPageCopy[r], Href: "?range=" + r, Current: r == rng}) |
| + } |
| + hours, err := s.TrafficHours(from, now) |
| + if err != nil { |
| + return v, err |
| + } |
| + day, starts, err := s.TrafficRange(now.Add(-24*time.Hour), now) |
| + if err != nil { |
| + return v, err |
| + } |
| + open, err := s.OpenAlertIncidents(alertScopeFleet) |
| + if err != nil { |
| + return v, err |
| + } |
| + var first sql.NullInt64 |
| + if err := s.db.QueryRow(`SELECT MIN(start) FROM traffic_hours`).Scan(&first); err != nil { |
| + return v, err |
| + } |
| + if first.Valid && time.Unix(first.Int64, 0).After(from) { |
| + v.Started = fmt.Sprintf(trafficPageCopy["started"], time.Unix(first.Int64, 0).UTC().Format("2006-01-02")) |
| + } |
| + v.Tiles = trafficTiles(open, day, len(starts) > 0) |
| + v.Chart = buildFleetTrafficChart(hours, rng, now) |
| + v.HasHours = len(hours) > 0 |
| + for _, h := range hours { |
| + v.Sum.Apps = mergeTrafficApps(v.Sum.Apps, h.Sum.Apps) |
| + v.Sum.RateApps = mergeTrafficApps(v.Sum.RateApps, h.Sum.RateApps) |
| + v.Sum.Paths = mergeTrafficCounts(v.Sum.Paths, h.Sum.Paths) |
| + v.Sum.Sources = mergeTrafficSources(v.Sum.Sources, h.Sum.Sources) |
| + v.Sum.Hosts = mergeTrafficCounts(v.Sum.Hosts, h.Sum.Hosts) |
| + } |
| + v.Sum = v.Sum.trimmed(10) |
| + return v, nil |
| +} |
| + |
| +// handleFleetTraffic gates every read on deployment-operator membership. The |
| +// page performs no bucket calls and never evaluates rules on a request path. |
| +func (s *Server) handleFleetTraffic(w http.ResponseWriter, r *http.Request) { |
| + addr, raw, ok := s.operatorOnly(w, r) |
| + if !ok { |
| + return |
| + } |
| + v, err := s.store.readFleetTraffic(r.URL.Query().Get("range"), time.Now()) |
| + if err != nil { |
| + log.Printf("console: fleet traffic: %v", err) |
| + v.Err = trafficPageCopy["error"] |
| + } |
| + p := s.opPage(addr, raw, "traffic") |
| + p.FleetTraffic = v |
| + s.render(w, http.StatusOK, "fleet_traffic", p) |
| +} |
diff --git a/internal/console/trafficview_test.go b/internal/console/trafficview_test.go| new file mode 100644 |
| index 000000000..dc1d51694 |
| --- /dev/null |
| +++ b/internal/console/trafficview_test.go |
| @@ -0,0 +1,307 @@ |
| +package console |
| + |
| +import ( |
| + "encoding/json" |
| + "fmt" |
| + "html" |
| + "net/http" |
| + "regexp" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/status" |
| +) |
| + |
| +// trafficViewHour makes a complete observation so each test chooses explicitly |
| +// whether it is testing a gap, incomplete coverage, or a measured zero. |
| +func trafficViewHour(at time.Time) trafficHour { |
| + return trafficHour{Start: at, Windows: 12, Boxes: 2, BoxWindows: 24, |
| + Sum: trafficSum{Requests: 10, S2xx: 4, S3xx: 1, S4xx: 1, S404: 1, S5xx: 1, Refused: 2, UnknownHost: 3}} |
| +} |
| + |
| +// putTrafficViewHour seeds retained history directly: ingest only accepts recent |
| +// windows, but the page must also render hours whose source rows have expired. |
| +func putTrafficViewHour(t *testing.T, s *Store, h trafficHour) { |
| + t.Helper() |
| + body, err := json.Marshal(h.Sum) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := s.db.Exec(`INSERT INTO traffic_hours (start, windows, boxes, box_windows, body) VALUES (?, ?, ?, ?, ?)`, h.Start.Unix(), h.Windows, h.Boxes, h.BoxWindows, string(body)); err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
| + |
| +// renderTrafficChart exercises the real template so a gap cannot accidentally |
| +// acquire a zero-height bar or lose its accessible label at rendering time. |
| +func renderTrafficChart(t *testing.T, c *fleetTrafficChart) string { |
| + t.Helper() |
| + var b strings.Builder |
| + if err := templates.ExecuteTemplate(&b, "traffic_chart", c); err != nil { |
| + t.Fatal(err) |
| + } |
| + return b.String() |
| +} |
| + |
| +// TestFleetTrafficNotOperator404 holds the new route to the same invisible |
| +// operator boundary as the other fleet pages, including malformed ranges. |
| +func TestFleetTrafficNotOperator404(t *testing.T) { |
| + fx := newConsoleFixture(t) |
| + out := newBrowser(t) |
| + _, _, ghost := get(t, out, fx.ts.URL+"/this-route-does-not-exist") |
| + for who, c := range map[string]*http.Client{"signed out": out, "member": signInPaul(t, fx)} { |
| + for _, suffix := range []string{"", "?range=junk", "?range=30d"} { |
| + code, _, body := get(t, c, fx.ts.URL+"/fleet/traffic"+suffix) |
| + if code != http.StatusNotFound || body != ghost { |
| + t.Errorf("%s%s: %d %q", who, suffix, code, body) |
| + } |
| + } |
| + } |
| +} |
| + |
| +// TestFleetTrafficTilesFollowIncidents checks the whole rule table, including |
| +// future rules, without requiring Task 5's evaluators or rule registration. |
| +func TestFleetTrafficTilesFollowIncidents(t *testing.T) { |
| + now := trafficStoreNow |
| + rules := map[string]string{"fleet_5xx": "healthy", "service_down": "healthy", "box_silent": "healthy", "abuse_surge": "abuse", "cpu": "load", "mem": "load", "disk_eta": "capacity", "disk": "capacity", "cert_expiring": "capacity"} |
| + for rule, key := range rules { |
| + t.Run(rule, func(t *testing.T) { |
| + open := []alertIncident{ |
| + {ID: 3, Scope: alertScopeFleet, Rule: rule, OpenedAt: now, Members: []string{"a"}}, |
| + {ID: 8, Scope: alertScopeFleet, Rule: rule, OpenedAt: now.Add(-time.Hour), Members: []string{"a", "b"}}, |
| + {ID: 1, Scope: "account:other", Rule: rule, OpenedAt: now.Add(-3 * time.Hour)}, |
| + {ID: 2, Scope: alertScopeFleet, Rule: rule, OpenedAt: now.Add(-2 * time.Hour), ClosedAt: now}, |
| + } |
| + for _, tile := range trafficTiles(open, trafficSum{}, false) { |
| + if tile.Key == key { |
| + if tile.State != "watch" || tile.Href != "/fleet/alerts/history#incident-8" || !strings.Contains(tile.Line, "2") || !strings.Contains(tile.Line, trafficRuleTitle(rule)) { |
| + t.Errorf("watch = %+v", tile) |
| + } |
| + } else if tile.State != "ok" || tile.Href != "" { |
| + t.Errorf("unrelated tile = %+v", tile) |
| + } |
| + } |
| + }) |
| + } |
| + tiles := trafficTiles(nil, trafficSum{S2xx: 990, S5xx: 10, Refused: 1000, Blocked: 7, Watched: 2}, true) |
| + if len(tiles) != 4 || !strings.Contains(tiles[0].Line, "1.00%") || !strings.Contains(tiles[1].Line, "9") { |
| + t.Fatalf("OK evidence: %+v", tiles) |
| + } |
| + for _, tile := range tiles { |
| + if tile.State != "ok" || tile.Href != "" { |
| + t.Errorf("no incidents: %+v", tile) |
| + } |
| + } |
| + for _, tile := range trafficTiles(nil, trafficSum{}, false)[:2] { |
| + if tile.Line != trafficPageCopy["empty.counts"] { |
| + t.Errorf("no counts: %+v", tile) |
| + } |
| + } |
| +} |
| + |
| +// TestFleetTrafficChartGapNotZero distinguishes an absent hour from a measured |
| +// zero and checks the ingress partition used by the four chart stacks. |
| +func TestFleetTrafficChartGapNotZero(t *testing.T) { |
| + now := trafficStoreNow |
| + start := now.UTC().Truncate(time.Hour).Add(-23 * time.Hour) |
| + var hours []trafficHour |
| + for _, i := range []int{0, 1, 2, 4} { |
| + hours = append(hours, trafficViewHour(start.Add(time.Duration(i)*time.Hour))) |
| + } |
| + zero := trafficViewHour(start.Add(5 * time.Hour)) |
| + zero.Sum = trafficSum{} |
| + hours = append(hours, zero) |
| + chart := buildFleetTrafficChart(hours, "24h", now) |
| + if len(chart.Cols) != 24 || !chart.Cols[3].Gap || chart.Cols[5].Gap { |
| + t.Fatalf("missing/zero: %+v", chart.Cols) |
| + } |
| + if got := chart.Cols[0].Counts; got != [4]int64{5, 2, 1, 5} { |
| + t.Fatalf("stacks = %v", got) |
| + } |
| + rendered := renderTrafficChart(t, chart) |
| + gap := regexp.MustCompile(`(?s)<g[^>]*data-gap="true".*?</g>`).FindString(rendered) |
| + if gap == "" || !strings.Contains(gap, "No data") || strings.Contains(gap, "<rect") || strings.Contains(gap, "height=") { |
| + t.Fatalf("gap markup: %s", gap) |
| + } |
| +} |
| + |
| +// TestFleetTrafficChartPartialMarked preserves incomplete per-box coverage in |
| +// both hour and day views, and labels the live hour separately from history. |
| +func TestFleetTrafficChartPartialMarked(t *testing.T) { |
| + now := trafficStoreNow |
| + h := trafficViewHour(now.Truncate(time.Hour).Add(-time.Hour)) |
| + h.BoxWindows-- |
| + for _, rng := range []string{"24h", "30d"} { |
| + chart := buildFleetTrafficChart([]trafficHour{h}, rng, now) |
| + found := false |
| + for _, c := range chart.Cols { |
| + if !c.Gap { |
| + found = true |
| + if !c.Partial || !strings.Contains(c.Label, "partial") { |
| + t.Errorf("%s: %+v", rng, c) |
| + } |
| + } |
| + } |
| + if !found || !strings.Contains(renderTrafficChart(t, chart), `class="traffic-partial"`) { |
| + t.Fatalf("%s: partial absent", rng) |
| + } |
| + } |
| + live := buildFleetTrafficChart([]trafficHour{trafficViewHour(now.Truncate(time.Hour))}, "24h", now) |
| + if c := live.Cols[23]; !c.Counting || !c.Partial || !strings.Contains(c.Label, "still counting") { |
| + t.Fatalf("live = %+v", c) |
| + } |
| +} |
| + |
| +// TestFleetTrafficChartThirtyDaysDaily checks UTC aggregation, missing hours |
| +// within a day, and all 168 hourly positions in the seven-day view. |
| +func TestFleetTrafficChartThirtyDaysDaily(t *testing.T) { |
| + now := trafficStoreNow |
| + yesterday := now.UTC().Truncate(24 * time.Hour).Add(-24 * time.Hour) |
| + var hours []trafficHour |
| + for i := 0; i < 24; i++ { |
| + hours = append(hours, trafficViewHour(yesterday.Add(time.Duration(i)*time.Hour))) |
| + } |
| + chart := buildFleetTrafficChart(hours, "30d", now) |
| + if len(chart.Cols) != 30 || chart.Cols[28].Partial || chart.Cols[28].Counts != [4]int64{120, 48, 24, 120} { |
| + t.Fatalf("daily = %+v", chart.Cols) |
| + } |
| + if !buildFleetTrafficChart(hours[1:], "30d", now).Cols[28].Partial { |
| + t.Fatal("missing hour became complete day") |
| + } |
| + if len(buildFleetTrafficChart(hours, "7d", now).Cols) != 168 { |
| + t.Fatal("7d is not hourly") |
| + } |
| +} |
| + |
| +// TestFleetTrafficHostileHostEscaped prevents a box-supplied hostname from |
| +// becoming either executable markup or an operator navigation target. |
| +func TestFleetTrafficHostileHostEscaped(t *testing.T) { |
| + fx := newConsoleFixture(t) |
| + c := signInOperator(t, fx) |
| + h := trafficViewHour(time.Now().UTC().Truncate(time.Hour).Add(-time.Hour)) |
| + host := "<script>x</script>.example" |
| + h.Sum.Hosts = []status.TrafficCount{{Key: host, Hits: 7}} |
| + putTrafficViewHour(t, fx.st, h) |
| + code, _, body := get(t, c, fx.ts.URL+"/fleet/traffic") |
| + if code != 200 || !strings.Contains(body, "<td>"+html.EscapeString(host)+"</td>") || strings.Contains(body, host) { |
| + t.Fatalf("host was not plain escaped text: %d %s", code, body) |
| + } |
| + assertOpShell(t, "/fleet/traffic", body) |
| +} |
| + |
| +// TestFleetTrafficRangeDefaults pins forgiving query parsing and all range |
| +// navigation links without tying it to one spelling of the draft labels. |
| +func TestFleetTrafficRangeDefaults(t *testing.T) { |
| + fx := newConsoleFixture(t) |
| + c := signInOperator(t, fx) |
| + for _, q := range []string{"", "?range=junk", "?range=24h", "?range=7d", "?range=30d"} { |
| + code, _, body := get(t, c, fx.ts.URL+"/fleet/traffic"+q) |
| + rng := "24h" |
| + if q == "?range=7d" { |
| + rng = "7d" |
| + } |
| + if q == "?range=30d" { |
| + rng = "30d" |
| + } |
| + if code != 200 || !strings.Contains(body, `href="?range=`+rng+`" aria-current="page"`) { |
| + t.Fatalf("%s: %d %s", q, code, body) |
| + } |
| + } |
| +} |
| + |
| +// TestFleetTrafficEmpty ensures that a new deployment does not claim measured |
| +// zeroes; every list and both traffic-dependent tiles explain their absence. |
| +func TestFleetTrafficEmpty(t *testing.T) { |
| + fx := newConsoleFixture(t) |
| + c := signInOperator(t, fx) |
| + code, _, body := get(t, c, fx.ts.URL+"/fleet/traffic") |
| + if code != 200 || strings.Count(body, trafficPageCopy["empty.counts"]) < 2 || strings.Count(body, trafficPageCopy["empty.list"]) != 5 || strings.Contains(body, "Counting started") { |
| + t.Fatalf("empty: %d %s", code, body) |
| + } |
| +} |
| + |
| +// TestFleetTrafficListsSumBeforeTrimming checks retained thirty-day data, |
| +// repeated identities, both rate columns, and the counting-start notice. |
| +func TestFleetTrafficListsSumBeforeTrimming(t *testing.T) { |
| + fx := newConsoleFixture(t) |
| + c := signInOperator(t, fx) |
| + at := time.Now().UTC().Truncate(time.Hour).Add(-10 * 24 * time.Hour) |
| + for i := 0; i < 2; i++ { |
| + h := trafficViewHour(at.Add(time.Duration(i) * time.Hour)) |
| + for j := 0; j < 12; j++ { |
| + h.Sum.Apps = append(h.Sum.Apps, status.TrafficApp{Account: "acct", App: fmt.Sprintf("app-%02d", j), Requests: int64(100 - j), S5xx: 1}) |
| + } |
| + h.Sum.RateApps = []status.TrafficApp{{Account: "acct", App: "limited", Refused: 7, Observed: 3}} |
| + h.Sum.Paths = []status.TrafficCount{{Key: "/probe", Hits: 2}} |
| + h.Sum.Sources = []status.TrafficSource{{Client: "client-hash", Country: "IE", Hits: 3}} |
| + putTrafficViewHour(t, fx.st, h) |
| + } |
| + code, _, body := get(t, c, fx.ts.URL+"/fleet/traffic?range=30d") |
| + for _, want := range []string{"app-00", "app-09", "<td>200</td>", "<td>14</td>", "<td>6</td>", `href="/fleet/protection">/probe</a>`, `href="/fleet/protection">client-hash</a>`, "Counting started " + at.Format("2006-01-02")} { |
| + if code != 200 || !strings.Contains(body, want) { |
| + t.Errorf("missing %q in %d %s", want, code, body) |
| + } |
| + } |
| + if strings.Contains(body, "app-10") || strings.Contains(body, "app-11") { |
| + t.Fatal("lists not trimmed to ten") |
| + } |
| +} |
| + |
| +// TestFleetTrafficReadOnlyIncidents proves the GET neither prunes flap history |
| +// nor loses old open incidents behind a recent-history limit. |
| +func TestFleetTrafficReadOnlyIncidents(t *testing.T) { |
| + fx := newConsoleFixture(t) |
| + c := signInOperator(t, fx) |
| + now := time.Now() |
| + rows := []alertIncident{{Scope: alertScopeFleet, Rule: "cpu", OpenedAt: now.Add(-48 * time.Hour), Members: []string{"box-1", "box-2"}}} |
| + for i := 0; i < 110; i++ { |
| + rows = append(rows, alertIncident{Scope: alertScopeFleet, Rule: "disk", OpenedAt: now.Add(-time.Hour), ClosedAt: now}) |
| + } |
| + if err := fx.st.CommitAlertStep(rows, nil, nil); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := fx.st.db.Exec(`INSERT INTO alert_fires (scope,rule,subject,fired_at) VALUES (?,?,?,?)`, alertScopeFleet, "cpu", "box-1", now.Add(-48*time.Hour).Unix()); err != nil { |
| + t.Fatal(err) |
| + } |
| + code, _, body := get(t, c, fx.ts.URL+"/fleet/traffic") |
| + if code != 200 || !strings.Contains(body, `href="/fleet/alerts/history#incident-1"`) { |
| + t.Fatalf("old open incident missing: %d %s", code, body) |
| + } |
| + var n int |
| + if err := fx.st.db.QueryRow(`SELECT COUNT(*) FROM alert_fires`).Scan(&n); err != nil || n != 1 { |
| + t.Fatalf("GET pruned history: %d %v", n, err) |
| + } |
| +} |
| + |
| +// TestFleetTrafficReadErrorDoesNotClaimOK prevents a failed history or incident |
| +// read from being presented as four healthy tiles and empty traffic. |
| +func TestFleetTrafficReadErrorDoesNotClaimOK(t *testing.T) { |
| + for _, table := range []string{"traffic_hours", "traffic_windows", "alert_incidents"} { |
| + t.Run(table, func(t *testing.T) { |
| + fx := newConsoleFixture(t) |
| + c := signInOperator(t, fx) |
| + if _, err := fx.st.db.Exec(`DROP TABLE ` + table); err != nil { |
| + t.Fatal(err) |
| + } |
| + code, _, body := get(t, c, fx.ts.URL+"/fleet/traffic") |
| + if code != 200 || !strings.Contains(body, trafficPageCopy["error"]) || strings.Contains(body, `data-state="ok"`) { |
| + t.Fatalf("read failure: %d %s", code, body) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// TestFleetTrafficNoRemoteCalls measures populated range views through the |
| +// production request wrapper: a page read must not consult any bucket or host. |
| +func TestFleetTrafficNoRemoteCalls(t *testing.T) { |
| + fx, lat := newPerfFixture(t) |
| + c := signInOperator(t, fx) |
| + putTrafficViewHour(t, fx.st, trafficViewHour(time.Now().UTC().Truncate(time.Hour).Add(-time.Hour))) |
| + for _, target := range perfOperatorTargets()["GET /fleet/traffic"] { |
| + got := perfOnce(fx, lat, c, target, nil) |
| + if got.err != nil || got.status != http.StatusOK || got.s3 != 0 || got.host != 0 { |
| + t.Errorf("%s: %+v", target.Path, got) |
| + } |
| + } |
| +} |
diff --git a/internal/provision/fleet_traffic_census_test.go b/internal/provision/fleet_traffic_census_test.go| new file mode 100644 |
| index 000000000..37ac3f8f3 |
| --- /dev/null |
| +++ b/internal/provision/fleet_traffic_census_test.go |
| @@ -0,0 +1,28 @@ |
| +package provision |
| + |
| +// fleetTrafficWriteCensusInventory re-pins NewServer for the operator-only |
| +// GET /fleet/traffic registration, layered on the current rootfs-apps-6 |
| +// inventory. The handler reads console.db only: the instances key literal, |
| +// record writes and their authority are unchanged. Source checked by the |
| +// implementer; independent Task 7 review remains part of the branch review. |
| +func fleetTrafficWriteCensusInventory() []censusEntry { |
| + entries := append([]censusEntry(nil), rootfsApps6WriteCensusInventory()...) |
| + repins := []censusEntry{ |
| + {"internal/console/server.go", "NewServer", "key-site", "lit:instances", "53ec116937fbfc3ec8a38729c6220e629b4c0e3c8ac39be9d719a436d9eca3d6"}, |
| + } |
| + for _, r := range repins { |
| + found := false |
| + for i, e := range entries { |
| + if e.File == r.File && e.Unit == r.Unit { |
| + if e.Class != r.Class || e.Kinds != r.Kinds { |
| + panic("fleet-traffic re-pin changes the class or kinds of " + r.File + ":" + r.Unit) |
| + } |
| + entries[i], found = r, true |
| + } |
| + } |
| + if !found { |
| + panic("fleet-traffic re-pin of an unlisted unit " + r.File + ":" + r.Unit) |
| + } |
| + } |
| + return entries |
| +} |
diff --git a/internal/provision/plan9_b8_census_test.go b/internal/provision/plan9_b8_census_test.go| index 82bec06cb..3cad35f8f 100644 |
| --- a/internal/provision/plan9_b8_census_test.go |
| +++ b/internal/provision/plan9_b8_census_test.go |
| @@ -366,7 +366,7 @@ func TestPlan9B8RecordWriteCensus(t *testing.T) { |
| if len(got) < 100 { |
| t.Fatalf("census found only %d units under %s; the walk is broken", len(got), root) |
| } |
| - inventory := rootfsApps6WriteCensusInventory() |
| + inventory := fleetTrafficWriteCensusInventory() |
| problems := append(censusDiff(inventory, got), censusPolicy(inventory)...) |
| if len(problems) > 0 { |
| t.Fatalf("record-write census rejected %d site(s); update the explicit inventory only after reviewing the source:\n %s", len(problems), strings.Join(problems, "\n ")) |