console: /fleet/traffic fixes from the Task 7 review
Compute tile scalars and distinct window coverage in SQL. Keep key-to-position indexes across window, hourly and page list merges. Seed the perf walk with 480 hours of full lists containing distinct keys. Report counted durations on partial-day OK tiles and prefer shared alert rule titles. Strengthen partial-day, registered-rule and singular Watch checks. Move OpenAlertIncidents into alertstore.go and format the copy deck. Validation: targeted FleetTraffic, Traffic, Perf, OpShell and OpShots tests passed; traffic tests passed with -race; console vet and touched-file gofmt passed. The populated screen walk passed: 30d median 58.1 ms, worst 61.5 ms, zero remote calls. One SQL mutation (s404 summed from s4xx) was caught. Plan interface drift: merge helpers accept persistent destination indexes. Draft wording remains for Task 6. No additional review round was opened.
Co-Authored-By: GPT-6 Astra (codex) <noreply@openai.com>
internal/console/alertstore.go+26 −0internal/console/perfwalk_test.go+17 −0internal/console/testdata/perf-budgets.txt+0 −1internal/console/trafficstore.go+55 −17internal/console/trafficstore_test.go+37 −0internal/console/trafficview.go+81 −57internal/console/trafficview_test.go+63 −6
CI failed — run details
Intent
<task-notification> <task-id>bzb940z94</task-id> <tool-use-id>toolu_015ZL9NmB69izLErdQoCDeb3</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/1f8653ea-6b78-4712-b1ac-1eb863a870a6/tasks/bzb940z94.output</output-file> <status>completed</status> <summary>Background command "Wait for Astra build run D (Task 7)" completed (exit code 0)</summary> </task-notification>
<task-notification> <task-id>a1896ff1f34b4d5aa</task-id> <tool-use-id>toolu_01FGFficLyxoCX7La7AF5CNd</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/1f8653ea-6b78-4712-b1ac-1eb863a870a6/tasks/a1896ff1f34b4d5aa.output</output-file> <status>completed</status> <summary>Agent "Opus review of Task 7 page" 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>I found no Critical issues and one Important one: the page's read cost grows with the square of the list entries. The other seven checks pass. Both targeted test runs passed: `go test ./internal/console -run 'FleetTraffic|OpShell|OpShots'` and `go test ./internal/provision -run TestPlan9B8RecordWriteCensus`. **1. Authorization (pass).** The route is registered at `server.go:1841`. `handleFleetTraffic` calls `operatorOnly` before anything else (`trafficview.go:311`), so nothing is read before the check. `operatorOnly` answers a plain `http.NotFound` for signed-out, unknown and non-operator callers (`server.go:3893-3911`). `TestFleetTrafficNotOperator404` checks that the body matches the "no such route" 404 for a signed-out user and for a member, including `?range=junk`. **2. Tiles (pass).** One source: `OpenAlertIncidents` reads fleet incidents with `closed_at IS NULL` and no row limit (`trafficview.go:108-129`). The tile table (`:58-60`) matches the plan's table. Every ID except the two Task 5 rules is in `alertRuleLevels` (`alertsignals.go:446`). A tile is Watch exactly when a matching open incident exists. It links the oldest one, with a stable tie-break on ID (`:88-94`). Measured data never changes a tile's state. **3. Hostile text (pass).** Account, app, path, client, country and hostname are only ever printed as text inside `<td>` or an `<a>`'s text (`fleet_traffic.html:22,27,32,37,42`). The `<a>` links use the fixed href `/fleet/protection`, and hostnames get no link. There is no `template.HTML` anywhere. SVG attributes carry only numbers, fixed kind names, and labels built from counts and copy. The tile href is a formatted integer ID. **4. Gaps and partial (pass).** A missing slot stays a gap, never drawn as zero. Missing or partial hours mark their day partial (`trafficview.go:197-210`). The current hour or day is marked still counting. 30d draws 30 daily bars. Any unknown range falls back to 24h with a 200 (`:173-183`). **5. console.db only (pass, but see the Important finding).** There are no store or host calls, and `TestFleetTrafficNoRemoteCalls` confirms it. **6. Registry, perf and census (pass).** The rail puts Traffic between Dashboard and People, and a test pins the order. claim-routes, the claim fixtures and probes, opshots, perfwalk and perf-budgets are all updated. The census layer `fleetTrafficWriteCensusInventory` copies the rootfs-apps-6 pattern, re-pins only `NewServer`, and is selected at `plan9_b8_census_test.go:369`. It passes. ### Important **I1. The page's cost grows with the square of the list entries, and it reads whole windows just for four tile numbers.** - At `trafficview.go:279`, `TrafficRange(now-24h, now)` decodes every 5-minute row from every box. That is 288 × N rows, each up to 12 KiB of JSON. It merges all five lists through `slices.IndexFunc`, which compares each new entry against every key collected so far (`trafficstore.go:86-125`). Then it sorts everything (`trimmed(-1)`). Only `S5xx`, the answered total, `Blocked`, `Watched` and "any start" are used. - Failure scenario: 10 boxes under scanner traffic, each window holding 10 distinct paths, hosts and sources. That is 28,800 entries per list and roughly 10^8 to 10^9 comparisons per list, plus about 35 MB of JSON decoded. Every page load would take seconds. - The 30d lists have the same shape (`trafficview.go:297-303`): 720 hours × 20 entries gives up to 14,400 keys per list, about 10^8 comparisons each. - The perf walk seeds no traffic rows, so it cannot see this. - Fix: - Compute the tile numbers in SQL: `SUM(json_extract(body,'$.s5xx'))` and the like, plus `COUNT(DISTINCT start)`. - Index the merges with a map from key to position in `dst`. This also speeds up Task 4's `recomputeTrafficHour`. - Seed a few hundred hostile hours in the perf fixture. ### Minor - **M1. The OK lines overstate how much was counted** (`trafficview.go:68-78,294`). The page says "…in the last 24 hours" once a single window exists (`len(starts) > 0`). After a 20-hour console outage, 4 hours of data is presented as 24. Say how much was counted when `len(starts) < 288`; Task 6 can write that copy. - **M2. The draft rule titles will keep winning after Task 5** (`trafficview.go:43-48`). `trafficPageCopy` is checked before `alertCopy`, so once Task 5 registers its titles, this page and `/fleet/alerts` will name the rule differently. Check `alertCopy` first, or delete the two draft entries in Task 5. - **M3. Test gaps:** - In `TestFleetTrafficChartPartialMarked`, the 30d half proves nothing about partial hours. `trafficStoreNow` is 12:17, so today's column is already partial because its later hours are missing. A day built only from present rows would still pass. Put the partial hour in a full past day instead. - `TestFleetTrafficTilesFollowIncidents` (`:67`) copies the tile table rather than checking it against `alertRuleLevels`. A typo made in both places would pass. Add a check that every tile rule other than `fleet_5xx` and `abuse_surge` is in `alertRuleLevels`. - The `watch.one` line is never checked. - **M4. The link can miss its target.** The history page shows only the newest 200 incidents (`alertpages.go:765`). An open incident older than those 200 has no `#incident-<id>` anchor, so the tile's link lands at the top of the page. The notifier's links already behave this way, so this is a note for later. - **M5. Idiom:** - `OpenAlertIncidents` is a store query living in `trafficview.go`. Its neighbours are in `alertstore.go`. - `trafficPageCopy` packs several entries per line. - `perf-budgets.txt` gains a stray blank line. - Comment density otherwise matches `protectionview.go` and `opdashboard.go`. **7. Would the tests catch a broken implementation?** Mostly yes. They cover the scope, closed-incident and oldest-incident filters on tiles, gap versus measured zero, the stack partition, the hostile hostname, a read error never showing OK, the GET leaving flap history alone, and the old open incident beyond the history limit. The gaps are the ones in M3. FIXES NEEDED (I1)</result> <usage><subagent_tokens>94470</subagent_tokens><tool_uses>17</tool_uses><duration_ms>203278</duration_ms></usage> </task-notification>
<task-notification> <task-id>bycpkz0kl</task-id> <tool-use-id>toolu_01D7XSo6kVe5NAd1A1h48Q6Q</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/1f8653ea-6b78-4712-b1ac-1eb863a870a6/tasks/bycpkz0kl.output</output-file> <status>completed</status> <summary>Background command "Wait for CI on the branch tip" completed (exit code 0)</summary> </task-notification>
Attributed to this commit: 16.7 g CO₂e (2,148,825 tokens). This is an attribution, not a measurement — usage counted from this commit's own marker forward to the next one on fleet-alerts-2-traffic, never backward from it. A turn that produced more than one commit books all of its tokens to the last one, and a concurrent session on this branch can add to the same figure. Some of it was priced using the shared default rate, because no model-specific factor row exists yet for at least one model involved. The Carbon view has the repo total, which is never derived from this attribution.
diff --git a/internal/console/alertstore.go b/internal/console/alertstore.go| index 3c15e3fe5..32ac6b796 100644 |
| --- a/internal/console/alertstore.go |
| +++ b/internal/console/alertstore.go |
| @@ -323,6 +323,32 @@ func alertNullTime(v sql.NullInt64) time.Time { |
| // ---- the step ---------------------------------------------------------------- |
| +// 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() |
| +} |
| + |
| // AlertStepInputs is what the incident step reads: every open incident, and |
| // the flap history inside the last hour by key, oldest first. Fires older |
| // than the hour are pruned here, the one place each pass passes now. |
diff --git a/internal/console/perfwalk_test.go b/internal/console/perfwalk_test.go| index 02537eb0c..030f3da59 100644 |
| --- a/internal/console/perfwalk_test.go |
| +++ b/internal/console/perfwalk_test.go |
| @@ -379,6 +379,7 @@ func perfSeed(t *testing.T, fx *consoleFixture, seeds *perfSeeds) { |
| // The operator pages' tables, populated (opdashboard_test.go). |
| seedOperatorScale(t, fx) |
| + perfSeedTraffic(t, fx, now) |
| // Flagship's shape: boxes in three regions, several apps, one with |
| // many instances across them (perfhotroutes_test.go). |
| @@ -396,6 +397,22 @@ func perfSeed(t *testing.T, fx *consoleFixture, seeds *perfSeeds) { |
| perfSeedGoneBoxes(t, fx, 1100) |
| } |
| +func perfSeedTraffic(t *testing.T, fx *consoleFixture, now time.Time) { |
| + t.Helper() |
| + for i := 1; i <= 480; i++ { |
| + h := trafficViewHour(now.UTC().Truncate(time.Hour).Add(-time.Duration(i) * time.Hour)) |
| + for j := 0; j < 20; j++ { |
| + key := fmt.Sprintf("traffic-%03d-%02d", i, j) |
| + h.Sum.Apps = append(h.Sum.Apps, status.TrafficApp{Account: fx.sqid, App: key, Requests: 100, S5xx: 1}) |
| + h.Sum.RateApps = append(h.Sum.RateApps, status.TrafficApp{Account: fx.sqid, App: key, Refused: 7, Observed: 3}) |
| + h.Sum.Paths = append(h.Sum.Paths, status.TrafficCount{Key: "/" + key, Hits: 10}) |
| + h.Sum.Hosts = append(h.Sum.Hosts, status.TrafficCount{Key: key + ".example", Hits: 10}) |
| + h.Sum.Sources = append(h.Sum.Sources, status.TrafficSource{Client: key, Country: "IE", Hits: 10}) |
| + } |
| + putTrafficViewHour(t, fx.st, h) |
| + } |
| +} |
| + |
| // perfSeedLapsed turns the plan catalogue on and seeds the lapsed |
| // account the keep page lists. |
| func perfSeedLapsed(t *testing.T, fx *consoleFixture, seeds *perfSeeds) { |
diff --git a/internal/console/testdata/perf-budgets.txt b/internal/console/testdata/perf-budgets.txt| index 058f48f7b..e520e4cd5 100644 |
| --- a/internal/console/testdata/perf-budgets.txt |
| +++ b/internal/console/testdata/perf-budgets.txt |
| @@ -109,5 +109,4 @@ 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/trafficstore.go b/internal/console/trafficstore.go| index 26e686e64..9c01a4a23 100644 |
| --- a/internal/console/trafficstore.go |
| +++ b/internal/console/trafficstore.go |
| @@ -57,9 +57,23 @@ func (h trafficHour) Partial(now time.Time) bool { |
| return now.Before(h.Start.Add(time.Hour)) || h.Windows < 12 || h.BoxWindows < h.Boxes*12 |
| } |
| +// trafficListIndex lives for the whole aggregation, until its slices are |
| +// sorted or trimmed. Each key maps to its position in the destination slice. |
| +type trafficListIndex struct { |
| + apps, rateApps, sources map[[2]string]int |
| + paths, hosts map[string]int |
| +} |
| + |
| +func newTrafficListIndex() trafficListIndex { |
| + return trafficListIndex{ |
| + apps: make(map[[2]string]int), rateApps: make(map[[2]string]int), |
| + sources: make(map[[2]string]int), paths: make(map[string]int), hosts: make(map[string]int), |
| + } |
| +} |
| + |
| // addTraffic merges complete observations before any top-list truncation. |
| // Callers count distinct starts separately because a fleet has many boxes. |
| -func addTraffic(sum *trafficSum, w status.TrafficWindow) { |
| +func addTraffic(sum *trafficSum, w status.TrafficWindow, index trafficListIndex) { |
| sum.Requests += w.Requests |
| sum.S2xx += w.S2xx |
| sum.S3xx += w.S3xx |
| @@ -74,19 +88,21 @@ func addTraffic(sum *trafficSum, w status.TrafficWindow) { |
| sum.RateObserved += w.RateObserved |
| sum.PlanThrottled += w.PlanThrottled |
| sum.UnknownHost += w.UnknownHost |
| - sum.Apps = mergeTrafficApps(sum.Apps, w.Apps) |
| - sum.RateApps = mergeTrafficApps(sum.RateApps, w.RateApps) |
| - sum.Paths = mergeTrafficCounts(sum.Paths, w.Paths) |
| - sum.Hosts = mergeTrafficCounts(sum.Hosts, w.Hosts) |
| - sum.Sources = mergeTrafficSources(sum.Sources, w.Sources) |
| + sum.Apps = mergeTrafficApps(sum.Apps, w.Apps, index.apps) |
| + sum.RateApps = mergeTrafficApps(sum.RateApps, w.RateApps, index.rateApps) |
| + sum.Paths = mergeTrafficCounts(sum.Paths, w.Paths, index.paths) |
| + sum.Hosts = mergeTrafficCounts(sum.Hosts, w.Hosts, index.hosts) |
| + sum.Sources = mergeTrafficSources(sum.Sources, w.Sources, index.sources) |
| } |
| // mergeTrafficApps uses a tuple key so slashes in an account or app cannot |
| // combine unrelated rows. All measures survive regardless of list ranking. |
| -func mergeTrafficApps(dst, src []status.TrafficApp) []status.TrafficApp { |
| +func mergeTrafficApps(dst, src []status.TrafficApp, index map[[2]string]int) []status.TrafficApp { |
| for _, row := range src { |
| - i := slices.IndexFunc(dst, func(x status.TrafficApp) bool { return x.Account == row.Account && x.App == row.App }) |
| - if i < 0 { |
| + key := [2]string{row.Account, row.App} |
| + i, ok := index[key] |
| + if !ok { |
| + index[key] = len(dst) |
| dst = append(dst, row) |
| continue |
| } |
| @@ -99,10 +115,11 @@ func mergeTrafficApps(dst, src []status.TrafficApp) []status.TrafficApp { |
| } |
| // mergeTrafficCounts combines repeated paths or hosts across boxes and slots. |
| -func mergeTrafficCounts(dst, src []status.TrafficCount) []status.TrafficCount { |
| +func mergeTrafficCounts(dst, src []status.TrafficCount, index map[string]int) []status.TrafficCount { |
| for _, row := range src { |
| - i := slices.IndexFunc(dst, func(x status.TrafficCount) bool { return x.Key == row.Key }) |
| - if i < 0 { |
| + i, ok := index[row.Key] |
| + if !ok { |
| + index[row.Key] = len(dst) |
| dst = append(dst, row) |
| } else { |
| dst[i].Hits += row.Hits |
| @@ -112,10 +129,12 @@ func mergeTrafficCounts(dst, src []status.TrafficCount) []status.TrafficCount { |
| } |
| // mergeTrafficSources preserves country in the key, matching the edge's list. |
| -func mergeTrafficSources(dst, src []status.TrafficSource) []status.TrafficSource { |
| +func mergeTrafficSources(dst, src []status.TrafficSource, index map[[2]string]int) []status.TrafficSource { |
| for _, row := range src { |
| - i := slices.IndexFunc(dst, func(x status.TrafficSource) bool { return x.Client == row.Client && x.Country == row.Country }) |
| - if i < 0 { |
| + key := [2]string{row.Client, row.Country} |
| + i, ok := index[key] |
| + if !ok { |
| + index[key] = len(dst) |
| dst = append(dst, row) |
| } else { |
| dst[i].Hits += row.Hits |
| @@ -337,6 +356,7 @@ func recomputeTrafficHour(tx *sql.Tx, hour int64) error { |
| return err |
| } |
| var sum trafficSum |
| + index := newTrafficListIndex() |
| starts, boxes := make(map[int64]bool), make(map[string]bool) |
| boxWindows := 0 |
| for rows.Next() { |
| @@ -351,7 +371,7 @@ func recomputeTrafficHour(tx *sql.Tx, hour int64) error { |
| rows.Close() |
| return err |
| } |
| - addTraffic(&sum, w) |
| + addTraffic(&sum, w, index) |
| starts[start], boxes[box] = true, true |
| boxWindows++ |
| } |
| @@ -397,6 +417,7 @@ func (s *Store) TrafficRange(from, to time.Time) (sum trafficSum, starts map[int |
| } |
| defer rows.Close() |
| starts = make(map[int64]bool) |
| + index := newTrafficListIndex() |
| for rows.Next() { |
| var start int64 |
| var body string |
| @@ -407,7 +428,7 @@ func (s *Store) TrafficRange(from, to time.Time) (sum trafficSum, starts map[int |
| if err := json.Unmarshal([]byte(body), &w); err != nil { |
| return trafficSum{}, nil, err |
| } |
| - addTraffic(&sum, w) |
| + addTraffic(&sum, w, index) |
| starts[start] = true |
| } |
| if err := rows.Err(); err != nil { |
| @@ -417,6 +438,23 @@ func (s *Store) TrafficRange(from, to time.Time) (sum trafficSum, starts map[int |
| return sum.trimmed(-1), starts, nil |
| } |
| +// TrafficTileSums reads just the tile scalars in [from, to). SQL leaves the |
| +// top lists in the database and counts a shared start only once across boxes. |
| +func (s *Store) TrafficTileSums(from, to time.Time) (sum trafficSum, err error) { |
| + err = s.db.QueryRow(`SELECT |
| +COALESCE(SUM(json_extract(body, '$.s2xx')), 0), |
| +COALESCE(SUM(json_extract(body, '$.s3xx')), 0), |
| +COALESCE(SUM(json_extract(body, '$.s4xx')), 0), |
| +COALESCE(SUM(json_extract(body, '$.s404')), 0), |
| +COALESCE(SUM(json_extract(body, '$.s5xx')), 0), |
| +COALESCE(SUM(json_extract(body, '$.blocked')), 0), |
| +COALESCE(SUM(json_extract(body, '$.watched')), 0), |
| +COUNT(DISTINCT start) |
| +FROM traffic_windows WHERE start >= ? AND start < ?`, from.Unix(), to.Unix()).Scan( |
| + &sum.S2xx, &sum.S3xx, &sum.S4xx, &sum.S404, &sum.S5xx, &sum.Blocked, &sum.Watched, &sum.Starts) |
| + return sum, err |
| +} |
| + |
| // TrafficHours returns only persisted hours in [from, to), oldest first. |
| // Callers draw missing rows as gaps rather than filling them with zeroes. |
| func (s *Store) TrafficHours(from, to time.Time) ([]trafficHour, error) { |
diff --git a/internal/console/trafficstore_test.go b/internal/console/trafficstore_test.go| index dfeef464e..05bc379c9 100644 |
| --- a/internal/console/trafficstore_test.go |
| +++ b/internal/console/trafficstore_test.go |
| @@ -725,3 +725,40 @@ func TestTrafficIngestClaimGate(t *testing.T) { |
| } |
| } |
| } |
| + |
| +func TestTrafficTileSumsSQL(t *testing.T) { |
| + s := openTestStore(t) |
| + to := trafficStoreNow.Truncate(status.TrafficWindowLen) |
| + from := to.Add(-24 * time.Hour) |
| + // Lists deliberately have a non-list JSON type: tiles only read scalars. |
| + body := `{"s2xx":10000000000,"s3xx":3,"s4xx":5,"s404":7,"s5xx":11,"blocked":13,"watched":17,"apps":"not a list"}` |
| + for _, row := range []struct { |
| + box string |
| + at time.Time |
| + }{ |
| + {"a", from.Add(-status.TrafficWindowLen)}, |
| + {"a", from}, {"b", from}, |
| + {"a", to.Add(-status.TrafficWindowLen)}, |
| + {"a", to}, |
| + } { |
| + if _, err := s.db.Exec(`INSERT INTO traffic_windows(box, start, body) VALUES (?, ?, ?)`, row.box, row.at.Unix(), body); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + want := trafficSum{S2xx: 30000000000, S3xx: 9, S4xx: 15, S404: 21, S5xx: 33, Blocked: 39, Watched: 51, Starts: 2} |
| + got, err := s.TrafficTileSums(from, to) |
| + if err != nil || !reflect.DeepEqual(got, want) { |
| + t.Fatalf("tile sums = %+v, %v; want %+v", got, err, want) |
| + } |
| + empty, err := s.TrafficTileSums(to.Add(time.Hour), to.Add(2*time.Hour)) |
| + if err != nil || !reflect.DeepEqual(empty, trafficSum{}) { |
| + t.Fatalf("empty tile sums = %+v, %v", empty, err) |
| + } |
| + view, err := s.readFleetTraffic("24h", to) |
| + if err != nil { |
| + t.Fatalf("page decoded tile row bodies: %v", err) |
| + } |
| + if !strings.Contains(view.Tiles[1].Line, "90 blocked or watched in the 10 minutes counted") { |
| + t.Fatalf("page tile totals = %+v", view.Tiles) |
| + } |
| +} |
diff --git a/internal/console/trafficview.go b/internal/console/trafficview.go| index db7b1417e..baf73bbc3 100644 |
| --- a/internal/console/trafficview.go |
| +++ b/internal/console/trafficview.go |
| @@ -2,7 +2,6 @@ package console |
| import ( |
| "database/sql" |
| - "encoding/json" |
| "fmt" |
| "log" |
| "net/http" |
| @@ -15,36 +14,76 @@ import ( |
| // 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", |
| + "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 %s.", |
| + "healthy.noanswers": "No answered requests counted %s.", |
| + "abuse.line": "%s blocked or watched %s.", |
| + "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", |
| + "period.full": "in the last 24 hours", |
| + "period.minutes": "in the %d minutes counted", |
| + "period.hour": "in the 1 hour counted", |
| + "period.hours": "in the %d hours counted", |
| } |
| // 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. |
| +// trafficRuleTitle prefers the shared alert title, then a page draft, then |
| +// the rule ID until its copy is registered. |
| func trafficRuleTitle(rule string) string { |
| + if title, ok := alertCopy["rule."+rule+".title"]; ok { |
| + return title |
| + } |
| if title := trafficPageCopy["rule."+rule]; title != "" { |
| return title |
| } |
| - return alertRuleTitle(rule) |
| + return rule |
| } |
| // trafficTiles derives status solely from fleet incidents. The oldest matching |
| @@ -59,6 +98,16 @@ func trafficTiles(open []alertIncident, day trafficSum, dayOK bool) []trafficTil |
| {"abuse", []string{"abuse_surge"}}, {"load", []string{"cpu", "mem"}}, |
| {"capacity", []string{"disk_eta", "disk", "cert_expiring"}}, |
| } |
| + period := trafficPageCopy["period.full"] |
| + if day.Starts < 288 { |
| + minutes := day.Starts * 5 |
| + period = fmt.Sprintf(trafficPageCopy["period.minutes"], minutes) |
| + if minutes == 60 { |
| + period = trafficPageCopy["period.hour"] |
| + } else if minutes%60 == 0 { |
| + period = fmt.Sprintf(trafficPageCopy["period.hours"], minutes/60) |
| + } |
| + } |
| var tiles []trafficTile |
| for _, row := range table { |
| tile := trafficTile{Key: row.key, Name: trafficPageCopy[row.key], State: "ok"} |
| @@ -66,15 +115,15 @@ func trafficTiles(open []alertIncident, day trafficSum, dayOK bool) []trafficTil |
| case "healthy": |
| tile.Line = trafficPageCopy["empty.counts"] |
| if dayOK { |
| - tile.Line = trafficPageCopy["healthy.noanswers"] |
| + tile.Line = fmt.Sprintf(trafficPageCopy["healthy.noanswers"], period) |
| if day.Answered() > 0 { |
| - tile.Line = fmt.Sprintf(trafficPageCopy["healthy.line"], fmt.Sprintf("%.2f%%", 100*float64(day.S5xx)/float64(day.Answered()))) |
| + tile.Line = fmt.Sprintf(trafficPageCopy["healthy.line"], fmt.Sprintf("%.2f%%", 100*float64(day.S5xx)/float64(day.Answered())), period) |
| } |
| } |
| case "abuse": |
| tile.Line = trafficPageCopy["empty.counts"] |
| if dayOK { |
| - tile.Line = fmt.Sprintf(trafficPageCopy["abuse.line"], groupedCount(day.Blocked+day.Watched)) |
| + tile.Line = fmt.Sprintf(trafficPageCopy["abuse.line"], groupedCount(day.Blocked+day.Watched), period) |
| } |
| default: |
| tile.Line = trafficPageCopy[row.key+".line"] |
| @@ -102,32 +151,6 @@ func trafficTiles(open []alertIncident, day trafficSum, dayOK bool) []trafficTil |
| 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 { |
| @@ -276,7 +299,7 @@ func (s *Store) readFleetTraffic(rng string, now time.Time) (*fleetTrafficView, |
| if err != nil { |
| return v, err |
| } |
| - day, starts, err := s.TrafficRange(now.Add(-24*time.Hour), now) |
| + day, err := s.TrafficTileSums(now.Add(-24*time.Hour), now) |
| if err != nil { |
| return v, err |
| } |
| @@ -291,15 +314,16 @@ func (s *Store) readFleetTraffic(rng string, now time.Time) (*fleetTrafficView, |
| 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.Tiles = trafficTiles(open, day, day.Starts > 0) |
| v.Chart = buildFleetTrafficChart(hours, rng, now) |
| v.HasHours = len(hours) > 0 |
| + index := newTrafficListIndex() |
| 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.Apps = mergeTrafficApps(v.Sum.Apps, h.Sum.Apps, index.apps) |
| + v.Sum.RateApps = mergeTrafficApps(v.Sum.RateApps, h.Sum.RateApps, index.rateApps) |
| + v.Sum.Paths = mergeTrafficCounts(v.Sum.Paths, h.Sum.Paths, index.paths) |
| + v.Sum.Sources = mergeTrafficSources(v.Sum.Sources, h.Sum.Sources, index.sources) |
| + v.Sum.Hosts = mergeTrafficCounts(v.Sum.Hosts, h.Sum.Hosts, index.hosts) |
| } |
| v.Sum = v.Sum.trimmed(10) |
| return v, nil |
diff --git a/internal/console/trafficview_test.go b/internal/console/trafficview_test.go| index dc1d51694..0818f1290 100644 |
| --- a/internal/console/trafficview_test.go |
| +++ b/internal/console/trafficview_test.go |
| @@ -67,6 +67,11 @@ func TestFleetTrafficTilesFollowIncidents(t *testing.T) { |
| 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) { |
| + if rule != "fleet_5xx" && rule != "abuse_surge" { |
| + if _, ok := alertRuleLevels[rule]; !ok { |
| + t.Fatalf("tile rule %q is not registered", rule) |
| + } |
| + } |
| 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"}}, |
| @@ -82,6 +87,11 @@ func TestFleetTrafficTilesFollowIncidents(t *testing.T) { |
| t.Errorf("unrelated tile = %+v", tile) |
| } |
| } |
| + for _, tile := range trafficTiles(open[:1], trafficSum{}, false) { |
| + if tile.Key == key && (tile.State != "watch" || tile.Href != "/fleet/alerts/history#incident-3" || tile.Line != fmt.Sprintf(trafficPageCopy["watch.one"], alertRuleTitle(rule))) { |
| + t.Errorf("single-member watch = %+v", tile) |
| + } |
| + } |
| }) |
| } |
| tiles := trafficTiles(nil, trafficSum{S2xx: 990, S5xx: 10, Refused: 1000, Blocked: 7, Watched: 2}, true) |
| @@ -130,15 +140,23 @@ func TestFleetTrafficChartGapNotZero(t *testing.T) { |
| // 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-- |
| + 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))) |
| + } |
| + hours[23].BoxWindows-- |
| for _, rng := range []string{"24h", "30d"} { |
| - chart := buildFleetTrafficChart([]trafficHour{h}, rng, now) |
| + chart := buildFleetTrafficChart(hours, rng, now) |
| + at := hours[23].Start |
| + if rng == "30d" { |
| + at = yesterday |
| + } |
| found := false |
| for _, c := range chart.Cols { |
| - if !c.Gap { |
| + if c.Start.Equal(at) { |
| found = true |
| - if !c.Partial || !strings.Contains(c.Label, "partial") { |
| + if c.Gap || c.Counting || !c.Partial || !strings.Contains(c.Label, "partial") { |
| t.Errorf("%s: %+v", rng, c) |
| } |
| } |
| @@ -147,6 +165,10 @@ func TestFleetTrafficChartPartialMarked(t *testing.T) { |
| t.Fatalf("%s: partial absent", rng) |
| } |
| } |
| + hours[23].BoxWindows++ |
| + if buildFleetTrafficChart(hours, "30d", now).Cols[28].Partial { |
| + t.Fatal("complete past day marked partial") |
| + } |
| 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) |
| @@ -297,7 +319,6 @@ func TestFleetTrafficReadErrorDoesNotClaimOK(t *testing.T) { |
| 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 { |
| @@ -305,3 +326,39 @@ func TestFleetTrafficNoRemoteCalls(t *testing.T) { |
| } |
| } |
| } |
| + |
| +func TestFleetTrafficTilesCountedPeriod(t *testing.T) { |
| + for _, tc := range []struct { |
| + starts int |
| + period string |
| + }{ |
| + {1, "in the 5 minutes counted"}, |
| + {12, "in the 1 hour counted"}, |
| + {48, "in the 4 hours counted"}, |
| + {49, "in the 245 minutes counted"}, |
| + {287, "in the 1435 minutes counted"}, |
| + {288, "in the last 24 hours"}, |
| + } { |
| + for _, answered := range []int64{0, 100} { |
| + tiles := trafficTiles(nil, trafficSum{Starts: tc.starts, S2xx: answered, Blocked: 2, Watched: 3}, true) |
| + for _, tile := range tiles[:2] { |
| + if !strings.Contains(tile.Line, tc.period) { |
| + t.Errorf("%d windows: %s, want %q", tc.starts, tile.Line, tc.period) |
| + } |
| + } |
| + } |
| + } |
| +} |
| + |
| +func TestFleetTrafficRuleTitleUsesAlertCopyFirst(t *testing.T) { |
| + trafficPageCopy["rule.cpu"] = "draft CPU title" |
| + t.Cleanup(func() { delete(trafficPageCopy, "rule.cpu") }) |
| + if got := trafficRuleTitle("cpu"); got != alertRuleTitle("cpu") { |
| + t.Fatalf("title = %q, want %q", got, alertRuleTitle("cpu")) |
| + } |
| + for _, rule := range []string{"fleet_5xx", "abuse_surge"} { |
| + if got := trafficRuleTitle(rule); got != alertRuleTitle(rule) { |
| + t.Errorf("title = %q, want %q", got, alertRuleTitle(rule)) |
| + } |
| + } |
| +} |