| new file mode 100644 |
| index 000000000..dfeef464e |
| --- /dev/null |
| +++ b/internal/console/trafficstore_test.go |
| @@ -0,0 +1,727 @@ |
| +package console |
| + |
| +import ( |
| + "encoding/json" |
| + "fmt" |
| + "math" |
| + "path/filepath" |
| + "reflect" |
| + "strings" |
| + "testing" |
| + "time" |
| + "unicode" |
| + "unicode/utf8" |
| + |
| + "github.com/carlosframework/platform/internal/status" |
| +) |
| + |
| +var trafficStoreNow = time.Date(2026, 11, 1, 12, 17, 0, 0, time.UTC) |
| + |
| +// trafficStoreWindow builds a valid one-request window so storage tests can |
| +// vary the row's identity without accidentally testing the validator instead. |
| +func trafficStoreWindow(start time.Time) status.TrafficWindow { |
| + return status.TrafficWindow{ |
| + Start: start.Unix(), Requests: 1, S2xx: 1, |
| + } |
| +} |
| + |
| +// trafficStoreAt returns a UTC five-minute boundary relative to the fixed |
| +// test clock, keeping every fixture independent of the wall clock. |
| +func trafficStoreAt(minutesAgo int) time.Time { |
| + return trafficStoreNow.Truncate(5 * time.Minute).Add(-time.Duration(minutesAgo) * time.Minute) |
| +} |
| + |
| +// TestTrafficIngestDedupesByBoxAndStart pins the stable identity of a window: |
| +// one box can contribute a start only once, while separate starts remain. |
| +func TestTrafficIngestDedupesByBoxAndStart(t *testing.T) { |
| + s := openTestStore(t) |
| + windows := []status.TrafficWindow{ |
| + trafficStoreWindow(trafficStoreAt(15)), |
| + trafficStoreWindow(trafficStoreAt(10)), |
| + trafficStoreWindow(trafficStoreAt(5)), |
| + } |
| + byBox := map[string][]status.TrafficWindow{"box-a": windows} |
| + inserted, err := s.IngestTraffic(byBox, trafficStoreNow) |
| + if err != nil || inserted != 3 { |
| + t.Fatalf("first ingest = %d, %v; want 3 rows", inserted, err) |
| + } |
| + inserted, err = s.IngestTraffic(byBox, trafficStoreNow) |
| + if err != nil || inserted != 0 { |
| + t.Fatalf("duplicate ingest = %d, %v; want 0 rows", inserted, err) |
| + } |
| + if got := alertCount(t, s, "traffic_windows"); got != 3 { |
| + t.Fatalf("stored windows = %d, want 3", got) |
| + } |
| + for _, w := range windows { |
| + got, starts, err := s.TrafficRange(time.Unix(w.Start, 0), time.Unix(w.Start+300, 0)) |
| + if err != nil || got.Requests != 1 || !starts[w.Start] || len(starts) != 1 { |
| + t.Fatalf("range for start %d = requests %d, starts %v, err %v", w.Start, got.Requests, starts, err) |
| + } |
| + } |
| +} |
| + |
| +// TestTrafficIngestRejectsForgedWindows checks the heartbeat trust boundary: |
| +// invalid windows are discarded and only a box's newest three can be stored. |
| +func TestTrafficIngestRejectsForgedWindows(t *testing.T) { |
| + tests := []struct { |
| + name string |
| + edit func(*status.TrafficWindow) |
| + }{ |
| + {"unaligned start", func(w *status.TrafficWindow) { w.Start++ }}, |
| + {"future window", func(w *status.TrafficWindow) { |
| + w.Start = trafficStoreNow.Truncate(5 * time.Minute).Add(5 * time.Minute).Unix() |
| + }}, |
| + {"too old window", func(w *status.TrafficWindow) { |
| + w.Start = trafficStoreNow.Truncate(5 * time.Minute).Add(-2*time.Hour - 5*time.Minute).Unix() |
| + }}, |
| + {"scalar negative", func(w *status.TrafficWindow) { w.Blocked = -1 }}, |
| + {"request mismatch", func(w *status.TrafficWindow) { w.Requests = 2 }}, |
| + {"scalar over maximum", func(w *status.TrafficWindow) { w.Requests, w.S2xx = 1_000_000_000_001, 1_000_000_000_001 }}, |
| + {"list count over maximum", func(w *status.TrafficWindow) { |
| + w.Paths = []status.TrafficCount{{Key: "/huge", Hits: 1_000_000_000_001}} |
| + }}, |
| + } |
| + for _, tc := range tests { |
| + t.Run(tc.name, func(t *testing.T) { |
| + s := openTestStore(t) |
| + w := trafficStoreWindow(trafficStoreAt(10)) |
| + tc.edit(&w) |
| + inserted, err := s.IngestTraffic(map[string][]status.TrafficWindow{"box-a": {w}}, trafficStoreNow) |
| + if err != nil || inserted != 0 { |
| + t.Fatalf("ingest = %d, %v; want invalid window rejected", inserted, err) |
| + } |
| + if got := alertCount(t, s, "traffic_windows"); got != 0 { |
| + t.Fatalf("invalid window stored %d rows", got) |
| + } |
| + }) |
| + } |
| + |
| + // Five distinct, valid starts in deliberately shuffled order must be cut |
| + // to the latest three, independently of the forged-window checks above. |
| + s := openTestStore(t) |
| + starts := []time.Time{trafficStoreAt(5), trafficStoreAt(20), trafficStoreAt(10), trafficStoreAt(15), trafficStoreAt(25)} |
| + windows := make([]status.TrafficWindow, 0, len(starts)) |
| + for _, start := range starts { |
| + windows = append(windows, trafficStoreWindow(start)) |
| + } |
| + inserted, err := s.IngestTraffic(map[string][]status.TrafficWindow{"box-a": windows}, trafficStoreNow) |
| + if err != nil || inserted != 3 { |
| + t.Fatalf("latest-window ingest = %d, %v; want 3", inserted, err) |
| + } |
| + _, got, err := s.TrafficRange(time.Time{}, trafficStoreNow.Add(time.Second)) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + want := map[int64]bool{trafficStoreAt(15).Unix(): true, trafficStoreAt(10).Unix(): true, trafficStoreAt(5).Unix(): true} |
| + if !reflect.DeepEqual(got, want) { |
| + t.Fatalf("kept starts = %v, want %v", got, want) |
| + } |
| +} |
| + |
| +// TestTrafficIngestChecksEveryScalarBound pins the inclusive 0..1e12 range |
| +// for each wire count and accepts the exact upper boundary on a valid window. |
| +func TestTrafficIngestChecksEveryScalarBound(t *testing.T) { |
| + fields := []string{"Requests", "S2xx", "S3xx", "S4xx", "S404", "S5xx", "Refused", "Blocked", "Watched", "RateShed", "RateCeiling", "RateObserved", "PlanThrottled", "UnknownHost"} |
| + for _, field := range fields { |
| + for _, value := range []int64{-1, 1_000_000_000_001} { |
| + field, value := field, value |
| + t.Run(fmt.Sprintf("%s/%s", field, map[bool]string{true: "negative", false: "over"}[value < 0]), func(t *testing.T) { |
| + s := openTestStore(t) |
| + w := trafficStoreWindow(trafficStoreAt(5)) |
| + setTrafficScalar(&w, field, value) |
| + inserted, err := s.IngestTraffic(map[string][]status.TrafficWindow{"box-a": {w}}, trafficStoreNow) |
| + if err != nil || inserted != 0 { |
| + t.Fatalf("%s=%d ingest = %d, %v; want rejected", field, value, inserted, err) |
| + } |
| + if got := alertCount(t, s, "traffic_windows"); got != 0 { |
| + t.Fatalf("%s=%d stored %d rows", field, value, got) |
| + } |
| + }) |
| + } |
| + } |
| + s := openTestStore(t) |
| + w := trafficStoreWindow(trafficStoreAt(5)) |
| + w.Requests, w.S2xx = 1_000_000_000_000, 1_000_000_000_000 |
| + if inserted, err := s.IngestTraffic(map[string][]status.TrafficWindow{"box-a": {w}}, trafficStoreNow); err != nil || inserted != 1 { |
| + t.Fatalf("exact maximum count ingest = %d, %v; want accepted", inserted, err) |
| + } |
| +} |
| + |
| +// TestTrafficIngestChecksEveryListCountBound rejects oversized values in each |
| +// numeric field of every list shape, regardless of the list's ranking type. |
| +func TestTrafficIngestChecksEveryListCountBound(t *testing.T) { |
| + tests := []struct { |
| + name string |
| + edit func(*status.TrafficWindow) |
| + }{ |
| + {"apps.requests", func(w *status.TrafficWindow) { |
| + w.Apps = []status.TrafficApp{{Account: "a", App: "b", Requests: 1_000_000_000_001}} |
| + }}, |
| + {"apps.s5xx", func(w *status.TrafficWindow) { |
| + w.Apps = []status.TrafficApp{{Account: "a", App: "b", S5xx: 1_000_000_000_001}} |
| + }}, |
| + {"apps.refused", func(w *status.TrafficWindow) { |
| + w.Apps = []status.TrafficApp{{Account: "a", App: "b", Refused: 1_000_000_000_001}} |
| + }}, |
| + {"apps.observed", func(w *status.TrafficWindow) { |
| + w.Apps = []status.TrafficApp{{Account: "a", App: "b", Observed: 1_000_000_000_001}} |
| + }}, |
| + {"rateapps.requests", func(w *status.TrafficWindow) { |
| + w.RateApps = []status.TrafficApp{{Account: "a", App: "b", Requests: 1_000_000_000_001}} |
| + }}, |
| + {"rateapps.s5xx", func(w *status.TrafficWindow) { |
| + w.RateApps = []status.TrafficApp{{Account: "a", App: "b", S5xx: 1_000_000_000_001}} |
| + }}, |
| + {"rateapps.refused", func(w *status.TrafficWindow) { |
| + w.RateApps = []status.TrafficApp{{Account: "a", App: "b", Refused: 1_000_000_000_001}} |
| + }}, |
| + {"rateapps.observed", func(w *status.TrafficWindow) { |
| + w.RateApps = []status.TrafficApp{{Account: "a", App: "b", Observed: 1_000_000_000_001}} |
| + }}, |
| + {"paths.hits", func(w *status.TrafficWindow) { w.Paths = []status.TrafficCount{{Key: "/p", Hits: 1_000_000_000_001}} }}, |
| + {"hosts.hits", func(w *status.TrafficWindow) { w.Hosts = []status.TrafficCount{{Key: "h", Hits: 1_000_000_000_001}} }}, |
| + {"sources.hits", func(w *status.TrafficWindow) { |
| + w.Sources = []status.TrafficSource{{Client: "c", Country: "US", Hits: 1_000_000_000_001}} |
| + }}, |
| + } |
| + for _, tc := range tests { |
| + tc := tc |
| + t.Run(tc.name, func(t *testing.T) { |
| + s := openTestStore(t) |
| + w := trafficStoreWindow(trafficStoreAt(5)) |
| + tc.edit(&w) |
| + if inserted, err := s.IngestTraffic(map[string][]status.TrafficWindow{"box-a": {w}}, trafficStoreNow); err != nil || inserted != 0 { |
| + t.Fatalf("oversized %s ingest = %d, %v; want rejected", tc.name, inserted, err) |
| + } |
| + if got := alertCount(t, s, "traffic_windows"); got != 0 { |
| + t.Fatalf("oversized %s stored %d rows", tc.name, got) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// TestTrafficIngestTimestampBoundaries covers the inclusive age and tolerated |
| +// future edges, plus extreme signed timestamps that could overflow arithmetic. |
| +func TestTrafficIngestTimestampBoundaries(t *testing.T) { |
| + accepted := []struct { |
| + name string |
| + now time.Time |
| + at time.Time |
| + }{ |
| + {"exact two-hour age", time.Date(2026, 11, 1, 12, 20, 0, 0, time.UTC), time.Date(2026, 11, 1, 10, 20, 0, 0, time.UTC)}, |
| + {"window ends one minute ahead", time.Date(2026, 11, 1, 12, 19, 0, 0, time.UTC), time.Date(2026, 11, 1, 12, 15, 0, 0, time.UTC)}, |
| + } |
| + for _, tc := range accepted { |
| + tc := tc |
| + t.Run("accept/"+tc.name, func(t *testing.T) { |
| + s := openTestStore(t) |
| + if inserted, err := s.IngestTraffic(map[string][]status.TrafficWindow{"box-a": {trafficStoreWindow(tc.at)}}, tc.now); err != nil || inserted != 1 { |
| + t.Fatalf("boundary ingest = %d, %v; want accepted", inserted, err) |
| + } |
| + }) |
| + } |
| + rejected := []struct { |
| + name string |
| + now time.Time |
| + at int64 |
| + }{ |
| + {"five minutes beyond age", time.Date(2026, 11, 1, 12, 20, 0, 0, time.UTC), time.Date(2026, 11, 1, 10, 15, 0, 0, time.UTC).Unix()}, |
| + {"future end one second too late", time.Date(2026, 11, 1, 12, 18, 59, 0, time.UTC), time.Date(2026, 11, 1, 12, 15, 0, 0, time.UTC).Unix()}, |
| + {"minimum int64", trafficStoreNow, math.MinInt64}, |
| + {"maximum int64", trafficStoreNow, math.MaxInt64}, |
| + } |
| + for _, tc := range rejected { |
| + tc := tc |
| + t.Run("reject/"+tc.name, func(t *testing.T) { |
| + s := openTestStore(t) |
| + w := trafficStoreWindow(time.Unix(tc.at, 0)) |
| + w.Start = tc.at |
| + if inserted, err := s.IngestTraffic(map[string][]status.TrafficWindow{"box-a": {w}}, tc.now); err != nil || inserted != 0 { |
| + t.Fatalf("boundary ingest = %d, %v; want rejected", inserted, err) |
| + } |
| + if got := alertCount(t, s, "traffic_windows"); got != 0 { |
| + t.Fatalf("rejected timestamp stored %d rows", got) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// setTrafficScalar changes one scalar while preserving a well-formed request |
| +// partition where the selected field allows one. |
| +func setTrafficScalar(w *status.TrafficWindow, field string, value int64) { |
| + switch field { |
| + case "Requests": |
| + w.Requests, w.S2xx = value, value |
| + case "S2xx": |
| + w.Requests, w.S2xx = value, value |
| + case "S3xx", "S4xx", "S404", "S5xx", "Refused": |
| + w.Requests, w.S2xx, w.S3xx, w.S4xx, w.S404, w.S5xx, w.Refused = 0, 0, 0, 0, 0, 0, 0 |
| + switch field { |
| + case "S3xx": |
| + w.S3xx = value |
| + case "S4xx": |
| + w.S4xx = value |
| + case "S404": |
| + w.S404 = value |
| + case "S5xx": |
| + w.S5xx = value |
| + case "Refused": |
| + w.Refused = value |
| + } |
| + w.Requests = value |
| + default: |
| + w.Requests, w.S2xx = 1, 1 |
| + reflect.ValueOf(w).Elem().FieldByName(field).SetInt(value) |
| + } |
| +} |
| + |
| +// TestTrafficIngestDropsNegativeListCounts ensures invalid top-list entries |
| +// disappear without discarding an otherwise valid scalar window. |
| +func TestTrafficIngestDropsNegativeListCounts(t *testing.T) { |
| + s := openTestStore(t) |
| + w := trafficStoreWindow(trafficStoreAt(5)) |
| + w.Apps = []status.TrafficApp{ |
| + {Account: "acct", App: "bad-requests", Requests: -1}, |
| + {Account: "acct", App: "bad-s5xx", S5xx: -1}, |
| + {Account: "acct", App: "bad-refused", Refused: -1}, |
| + {Account: "acct", App: "bad-observed", Observed: -1}, |
| + {Account: "acct", App: "good", Requests: 3, S5xx: 1}, |
| + } |
| + w.RateApps = []status.TrafficApp{ |
| + {Account: "acct", App: "bad-requests", Requests: -1}, |
| + {Account: "acct", App: "bad-s5xx", S5xx: -1}, |
| + {Account: "acct", App: "bad-refused", Refused: -1}, |
| + {Account: "acct", App: "bad-observed", Observed: -1}, |
| + {Account: "acct", App: "good", Refused: 1}, |
| + } |
| + w.Paths = []status.TrafficCount{{Key: "/bad", Hits: -1}, {Key: "/good", Hits: 2}} |
| + inserted, err := s.IngestTraffic(map[string][]status.TrafficWindow{"box-a": {w}}, trafficStoreNow) |
| + if err != nil || inserted != 1 { |
| + t.Fatalf("ingest = %d, %v; want valid window retained", inserted, err) |
| + } |
| + sum, _, err := s.TrafficRange(time.Unix(w.Start, 0), time.Unix(w.Start+300, 0)) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if len(sum.Apps) != 1 || sum.Apps[0].App != "good" || sum.Apps[0].Requests != 3 || len(sum.RateApps) != 1 || sum.RateApps[0].App != "good" || len(sum.Paths) != 1 || sum.Paths[0].Key != "/good" { |
| + t.Fatalf("negative list entries were not dropped: apps=%+v rate apps=%+v paths=%+v", sum.Apps, sum.RateApps, sum.Paths) |
| + } |
| +} |
| + |
| +// TestTrafficIngestTrimsHostileStrings ensures every persisted list is bounded, |
| +// ranked, and safe to pass to later rendering code. |
| +func TestTrafficIngestTrimsHostileStrings(t *testing.T) { |
| + s := openTestStore(t) |
| + w := trafficStoreWindow(trafficStoreAt(10)) |
| + bad := func(n int) string { return strings.Repeat("<", n-2) + "\x00" + string([]byte{0xff}) } |
| + w.Apps = []status.TrafficApp{{Account: bad(128), App: bad(128), Requests: 10}} |
| + w.RateApps = []status.TrafficApp{{Account: bad(128), App: bad(128), Refused: 10}} |
| + w.Paths = []status.TrafficCount{{Key: "bad\x00" + string([]byte{0xff}) + strings.Repeat("p", 510), Hits: 10}} |
| + w.Sources = []status.TrafficSource{{Client: bad(64), Country: "<s", Hits: 10}} |
| + w.Hosts = []status.TrafficCount{{Key: bad(253) + strings.Repeat("h", 2000), Hits: 10}} |
| + before := w |
| + before.Apps = append([]status.TrafficApp(nil), w.Apps...) |
| + before.RateApps = append([]status.TrafficApp(nil), w.RateApps...) |
| + before.Paths = append([]status.TrafficCount(nil), w.Paths...) |
| + before.Sources = append([]status.TrafficSource(nil), w.Sources...) |
| + before.Hosts = append([]status.TrafficCount(nil), w.Hosts...) |
| + if _, err := s.IngestTraffic(map[string][]status.TrafficWindow{"box-a": {w}}, trafficStoreNow); err != nil { |
| + t.Fatal(err) |
| + } |
| + if !reflect.DeepEqual(w, before) { |
| + t.Fatal("ingest mutated the heartbeat's input slices") |
| + } |
| + sum, _, err := s.TrafficRange(time.Unix(w.Start, 0), time.Unix(w.Start+300, 0)) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + check := func(label, value string, cap int) { |
| + t.Helper() |
| + if len(value) > cap || !utf8.ValidString(value) || strings.IndexFunc(value, unicode.IsControl) >= 0 { |
| + t.Errorf("%s = %q (bytes %d), want valid, control-free UTF-8 at most %d bytes", label, value, len(value), cap) |
| + } |
| + } |
| + check("account", sum.Apps[0].Account, 128) |
| + check("app", sum.Apps[0].App, 128) |
| + check("rate account", sum.RateApps[0].Account, 128) |
| + check("rate app", sum.RateApps[0].App, 128) |
| + check("path", sum.Paths[0].Key, 512) |
| + check("host", sum.Hosts[0].Key, 253) |
| + check("client", sum.Sources[0].Client, 64) |
| + if sum.Sources[0].Country != "" { |
| + t.Errorf("country = %q, want empty for invalid two-letter code", sum.Sources[0].Country) |
| + } |
| + |
| + // Worst-case keys make JSON escape each '<' as six bytes. Even this full |
| + // ten-entry payload must fit the 12 KiB wire budget without changing totals. |
| + worst := trafficStoreWindow(trafficStoreAt(5)) |
| + worst.Requests, worst.S2xx, worst.Blocked = 19, 19, 23 |
| + for i := 0; i < 10; i++ { |
| + hits := int64(10 - i) |
| + worst.Apps = append(worst.Apps, status.TrafficApp{Account: strings.Repeat("<", 128), App: strings.Repeat("<", 128), Requests: hits}) |
| + worst.RateApps = append(worst.RateApps, status.TrafficApp{Account: strings.Repeat("<", 128), App: strings.Repeat("<", 128), Refused: hits}) |
| + worst.Paths = append(worst.Paths, status.TrafficCount{Key: strings.Repeat("<", 512), Hits: hits}) |
| + worst.Hosts = append(worst.Hosts, status.TrafficCount{Key: strings.Repeat("<", 253), Hits: hits}) |
| + worst.Sources = append(worst.Sources, status.TrafficSource{Client: strings.Repeat("<", 64), Country: "US", Hits: hits}) |
| + } |
| + worstBefore := worst |
| + worstBefore.Apps = append([]status.TrafficApp(nil), worst.Apps...) |
| + worstBefore.RateApps = append([]status.TrafficApp(nil), worst.RateApps...) |
| + worstBefore.Paths = append([]status.TrafficCount(nil), worst.Paths...) |
| + worstBefore.Hosts = append([]status.TrafficCount(nil), worst.Hosts...) |
| + worstBefore.Sources = append([]status.TrafficSource(nil), worst.Sources...) |
| + if _, err := s.IngestTraffic(map[string][]status.TrafficWindow{"box-a": {worst}}, trafficStoreNow); err != nil { |
| + t.Fatal(err) |
| + } |
| + if !reflect.DeepEqual(worst, worstBefore) { |
| + t.Fatal("worst-case ingest mutated the heartbeat's input slices") |
| + } |
| + var body string |
| + if err := s.db.QueryRow(`SELECT body FROM traffic_windows WHERE box = 'box-a' AND start = ?`, worst.Start).Scan(&body); err != nil { |
| + t.Fatal(err) |
| + } |
| + if len(body) > status.TrafficWindowMaxBytes { |
| + t.Fatalf("stored worst-case window is %d bytes, want at most %d", len(body), status.TrafficWindowMaxBytes) |
| + } |
| + sum, _, err = s.TrafficRange(time.Unix(worst.Start, 0), time.Unix(worst.Start+300, 0)) |
| + if err != nil || sum.Requests != 19 || sum.S2xx != 19 || sum.Blocked != 23 { |
| + t.Fatalf("worst-case scalar totals = %+v, %v; want requests/s2xx=19 and blocked=23", sum, err) |
| + } |
| +} |
| + |
| +// TestTrafficIngestCapsEveryList checks the ten-entry limit independently of |
| +// the byte limit: small keys must not let an oversized list into the database. |
| +func TestTrafficIngestCapsEveryList(t *testing.T) { |
| + s := openTestStore(t) |
| + w := trafficStoreWindow(trafficStoreAt(5)) |
| + for i := 0; i < 20; i++ { |
| + key := fmt.Sprintf("key-%02d", i) |
| + w.Apps = append(w.Apps, status.TrafficApp{Account: "acct", App: key, Requests: int64(i)}) |
| + w.RateApps = append(w.RateApps, status.TrafficApp{Account: "acct", App: key, Observed: int64(20 - i)}) |
| + w.Paths = append(w.Paths, status.TrafficCount{Key: key, Hits: int64(i)}) |
| + w.Hosts = append(w.Hosts, status.TrafficCount{Key: key, Hits: int64(i)}) |
| + w.Sources = append(w.Sources, status.TrafficSource{Client: key, Country: "IE", Hits: int64(i)}) |
| + } |
| + if n, err := s.IngestTraffic(map[string][]status.TrafficWindow{"box": {w}}, trafficStoreNow); err != nil || n != 1 { |
| + t.Fatalf("ingest = %d, %v; want one row", n, err) |
| + } |
| + var body string |
| + if err := s.db.QueryRow(`SELECT body FROM traffic_windows WHERE box = 'box' AND start = ?`, w.Start).Scan(&body); err != nil { |
| + t.Fatal(err) |
| + } |
| + var got status.TrafficWindow |
| + if err := json.Unmarshal([]byte(body), &got); err != nil { |
| + t.Fatal(err) |
| + } |
| + for name, n := range map[string]int{"apps": len(got.Apps), "rate apps": len(got.RateApps), "paths": len(got.Paths), "hosts": len(got.Hosts), "sources": len(got.Sources)} { |
| + if n != status.TrafficTopN { |
| + t.Fatalf("%s has %d entries, want %d", name, n, status.TrafficTopN) |
| + } |
| + } |
| + if got.Apps[0].App != "key-19" || got.RateApps[0].App != "key-00" || got.Paths[0].Key != "key-19" || got.Hosts[0].Key != "key-19" || got.Sources[0].Client != "key-19" { |
| + t.Fatalf("lists lost their highest-ranked entry: %+v", got) |
| + } |
| +} |
| + |
| +// TestTrafficHourRollupMergesBoxesAndLists pins the hourly aggregates, exact |
| +// distinct-start and box counts, and the per-box completeness calculation. |
| +func TestTrafficHourRollupMergesBoxesAndLists(t *testing.T) { |
| + s := openTestStore(t) |
| + start := trafficStoreAt(25).Truncate(time.Hour) |
| + first := trafficStoreWindow(start) |
| + first.Requests, first.S2xx, first.S3xx, first.S4xx, first.S404, first.S5xx = 7, 1, 1, 1, 1, 1 |
| + first.Refused, first.Blocked, first.Watched = 2, 3, 4 |
| + first.RateShed, first.RateCeiling, first.RateObserved, first.PlanThrottled, first.UnknownHost = 5, 6, 7, 8, 9 |
| + first.Apps = []status.TrafficApp{{Account: "acct", App: "same", Requests: 5, S5xx: 1}} |
| + first.RateApps = []status.TrafficApp{{Account: "acct", App: "same", Refused: 2, Observed: 3}} |
| + first.Paths = []status.TrafficCount{{Key: "/same", Hits: 2}} |
| + first.Hosts = []status.TrafficCount{{Key: "same.example", Hits: 3}} |
| + first.Sources = []status.TrafficSource{{Client: "hash", Country: "IE", Hits: 4}} |
| + second := first |
| + second.Start += 5 * 60 |
| + second.Requests, second.S2xx, second.S3xx, second.S4xx, second.S404, second.S5xx = 14, 2, 2, 2, 2, 2 |
| + second.Refused, second.Blocked, second.Watched = 4, 6, 8 |
| + second.RateShed, second.RateCeiling, second.RateObserved, second.PlanThrottled, second.UnknownHost = 10, 12, 14, 16, 18 |
| + second.Apps = []status.TrafficApp{{Account: "acct", App: "same", Requests: 10, S5xx: 2}} |
| + second.RateApps = []status.TrafficApp{{Account: "acct", App: "same", Refused: 4, Observed: 6}} |
| + second.Paths = []status.TrafficCount{{Key: "/same", Hits: 4}} |
| + second.Hosts = []status.TrafficCount{{Key: "same.example", Hits: 6}} |
| + second.Sources = []status.TrafficSource{{Client: "hash", Country: "IE", Hits: 8}} |
| + if n, err := s.IngestTraffic(map[string][]status.TrafficWindow{"box-a": {first, second}, "box-b": {first}}, trafficStoreNow); err != nil || n != 3 { |
| + t.Fatalf("ingest = %d, %v; want 3", n, err) |
| + } |
| + hours, err := s.TrafficHours(start, start.Add(time.Hour)) |
| + if err != nil || len(hours) != 1 { |
| + t.Fatalf("hours = %+v, %v; want one hour", hours, err) |
| + } |
| + h := hours[0] |
| + wantTotals := trafficSum{ |
| + Requests: 28, S2xx: 4, S3xx: 4, S4xx: 4, S404: 4, S5xx: 4, |
| + Refused: 8, Blocked: 12, Watched: 16, RateShed: 20, RateCeiling: 24, |
| + RateObserved: 28, PlanThrottled: 32, UnknownHost: 36, Starts: 2, |
| + Apps: []status.TrafficApp{{Account: "acct", App: "same", Requests: 20, S5xx: 4}}, |
| + RateApps: []status.TrafficApp{{Account: "acct", App: "same", Refused: 8, Observed: 12}}, |
| + Paths: []status.TrafficCount{{Key: "/same", Hits: 8}}, |
| + Hosts: []status.TrafficCount{{Key: "same.example", Hits: 12}}, |
| + Sources: []status.TrafficSource{{Client: "hash", Country: "IE", Hits: 16}}, |
| + } |
| + if h.Windows != 2 || h.Boxes != 2 || h.BoxWindows != 3 || !reflect.DeepEqual(h.Sum, wantTotals) { |
| + t.Fatalf("hour = %+v; want windows=2 boxes=2 box_windows=3 sum=%+v", h, wantTotals) |
| + } |
| + if !h.Partial(trafficStoreNow) { |
| + t.Fatal("hour missing one box/window was not marked partial") |
| + } |
| +} |
| + |
| +// TestTrafficHourRecomputedOnLateWindow confirms a new window refreshes the |
| +// already materialised hour rather than leaving a stale aggregate. |
| +func TestTrafficHourRecomputedOnLateWindow(t *testing.T) { |
| + s := openTestStore(t) |
| + start := trafficStoreAt(30) |
| + first := trafficStoreWindow(start) |
| + if _, err := s.IngestTraffic(map[string][]status.TrafficWindow{"box-a": {first}}, trafficStoreNow); err != nil { |
| + t.Fatal(err) |
| + } |
| + late := trafficStoreWindow(start.Add(5 * time.Minute)) |
| + late.Requests, late.S2xx = 7, 7 |
| + if _, err := s.IngestTraffic(map[string][]status.TrafficWindow{"box-a": {late}}, trafficStoreNow); err != nil { |
| + t.Fatal(err) |
| + } |
| + hours, err := s.TrafficHours(start.Truncate(time.Hour), start.Truncate(time.Hour).Add(time.Hour)) |
| + if err != nil || len(hours) != 1 || hours[0].Sum.Requests != 8 || hours[0].Windows != 2 || hours[0].BoxWindows != 2 { |
| + t.Fatalf("late recompute = %+v, %v; want 8 requests over 2 windows", hours, err) |
| + } |
| +} |
| + |
| +// TestTrafficHourRollupRanksTwentyEntries checks that the stored hourly top |
| +// lists merge across windows and boxes before retaining the 20 highest counts. |
| +func TestTrafficHourRollupRanksTwentyEntries(t *testing.T) { |
| + s := openTestStore(t) |
| + byBox := make(map[string][]status.TrafficWindow) |
| + starts := []time.Time{trafficStoreAt(75), trafficStoreAt(70), trafficStoreAt(65)} |
| + for boxIndex, box := range []string{"box-a", "box-b", "box-c"} { |
| + for _, start := range starts { |
| + w := trafficStoreWindow(start) |
| + for offset := 0; offset < 10; offset++ { |
| + index := boxIndex*10 + offset |
| + key := string(rune('a'+index/26)) + string(rune('a'+index%26)) |
| + count := int64(30 - index) |
| + w.Apps = append(w.Apps, status.TrafficApp{Account: "acct", App: key, Requests: count, S5xx: 1}) |
| + w.RateApps = append(w.RateApps, status.TrafficApp{Account: "acct", App: key, Refused: count, Observed: count}) |
| + w.Paths = append(w.Paths, status.TrafficCount{Key: "/" + key, Hits: count}) |
| + w.Hosts = append(w.Hosts, status.TrafficCount{Key: key + ".example", Hits: count}) |
| + w.Sources = append(w.Sources, status.TrafficSource{Client: key, Country: "US", Hits: count}) |
| + } |
| + // One request answer keeps the scalar partition valid; list totals |
| + // are independent samples of their own decisions and hits. |
| + byBox[box] = append(byBox[box], w) |
| + } |
| + } |
| + if n, err := s.IngestTraffic(byBox, trafficStoreNow); err != nil || n != 9 { |
| + t.Fatalf("ingest = %d, %v; want 9 rows", n, err) |
| + } |
| + hour := starts[0].Truncate(time.Hour) |
| + hours, err := s.TrafficHours(hour, hour.Add(time.Hour)) |
| + if err != nil || len(hours) != 1 { |
| + t.Fatalf("hour = %+v, %v; want one", hours, err) |
| + } |
| + sum := hours[0].Sum |
| + if len(sum.Apps) != 20 || len(sum.RateApps) != 20 || len(sum.Paths) != 20 || len(sum.Hosts) != 20 || len(sum.Sources) != 20 { |
| + t.Fatalf("hourly list sizes = apps %d rate apps %d paths %d hosts %d sources %d; want 20 each", |
| + len(sum.Apps), len(sum.RateApps), len(sum.Paths), len(sum.Hosts), len(sum.Sources)) |
| + } |
| + if sum.Apps[0].App != "aa" || sum.Apps[0].Requests != 90 || sum.Apps[19].App != "at" || sum.Apps[19].Requests != 33 { |
| + t.Fatalf("ranked apps = first %+v last %+v; want aa/90 through at/33", sum.Apps[0], sum.Apps[19]) |
| + } |
| + if sum.Paths[0].Key != "/aa" || sum.Paths[19].Key != "/at" || sum.Hosts[0].Key != "aa.example" || sum.Hosts[19].Key != "at.example" || sum.Sources[0].Client != "aa" || sum.Sources[19].Client != "at" { |
| + t.Fatalf("ranked list endpoints = paths %+v/%+v hosts %+v/%+v sources %+v/%+v", |
| + sum.Paths[0], sum.Paths[19], sum.Hosts[0], sum.Hosts[19], sum.Sources[0], sum.Sources[19]) |
| + } |
| +} |
| + |
| +// TestTrafficPruneKeeps7DaysAnd90Days pins both retention cutoffs at their |
| +// exact boundary so pruning does not delete data one instant too early. |
| +func TestTrafficPruneKeeps7DaysAnd90Days(t *testing.T) { |
| + s := openTestStore(t) |
| + now := trafficStoreNow.Truncate(time.Hour) |
| + oldWindow := now.Add(-7*24*time.Hour - 5*time.Minute) |
| + keepWindow := now.Add(-7 * 24 * time.Hour) |
| + for box, at := range map[string]time.Time{"old": oldWindow, "keep": keepWindow} { |
| + body, _ := json.Marshal(trafficStoreWindow(at)) |
| + if _, err := s.db.Exec(`INSERT INTO traffic_windows(box, start, body) VALUES(?, ?, ?)`, box, at.Unix(), string(body)); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + oldHour := now.Add(-90*24*time.Hour - time.Hour).Unix() |
| + keepHour := now.Add(-90 * 24 * time.Hour).Unix() |
| + body, _ := json.Marshal(trafficSum{}) |
| + for _, start := range []int64{oldHour, keepHour} { |
| + if _, err := s.db.Exec(`INSERT INTO traffic_hours(start, windows, boxes, box_windows, body) VALUES(?, 0, 0, 0, ?)`, start, string(body)); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + if err := s.PruneTraffic(now); err != nil { |
| + t.Fatal(err) |
| + } |
| + if got := alertCount(t, s, "traffic_windows"); got != 1 { |
| + t.Fatalf("windows after prune = %d, want only the exact 7-day boundary", got) |
| + } |
| + var hours int |
| + if err := s.db.QueryRow(`SELECT COUNT(*) FROM traffic_hours`).Scan(&hours); err != nil || hours != 1 { |
| + t.Fatalf("hours after prune = %d, %v; want exact 90-day boundary only", hours, err) |
| + } |
| +} |
| + |
| +// TestTrafficHoursGapIsAbsent ensures a missing hour remains a gap instead of |
| +// becoming a synthetic zero-valued traffic bar. |
| +func TestTrafficHoursGapIsAbsent(t *testing.T) { |
| + s := openTestStore(t) |
| + start := trafficStoreAt(5).Truncate(time.Hour) |
| + if _, err := s.IngestTraffic(map[string][]status.TrafficWindow{"box-a": {trafficStoreWindow(start)}}, trafficStoreNow); err != nil { |
| + t.Fatal(err) |
| + } |
| + hours, err := s.TrafficHours(start.Add(-time.Hour), start.Add(time.Hour)) |
| + if err != nil || len(hours) != 1 || !hours[0].Start.Equal(start) { |
| + t.Fatalf("hours across one missing hour = %+v, %v; want only %s", hours, err, start) |
| + } |
| +} |
| + |
| +// TestTrafficHourCurrentIsPartial keeps the live bucket visibly incomplete |
| +// while it is still collecting windows, even when no heartbeat has been lost. |
| +func TestTrafficHourCurrentIsPartial(t *testing.T) { |
| + s := openTestStore(t) |
| + start := trafficStoreNow.Truncate(time.Hour) |
| + if _, err := s.IngestTraffic(map[string][]status.TrafficWindow{"box-a": {trafficStoreWindow(start)}}, trafficStoreNow); err != nil { |
| + t.Fatal(err) |
| + } |
| + hours, err := s.TrafficHours(start, start.Add(time.Hour)) |
| + if err != nil || len(hours) != 1 || !hours[0].Partial(trafficStoreNow) { |
| + t.Fatalf("current hour = %+v, %v; want one partial hour", hours, err) |
| + } |
| +} |
| + |
| +// TestTrafficHourPerBoxCompleteness distinguishes a full set of starts from |
| +// complete per-box coverage, then proves one late window fills the only gap. |
| +func TestTrafficHourPerBoxCompleteness(t *testing.T) { |
| + s := openTestStore(t) |
| + hour := time.Date(2026, 11, 1, 11, 0, 0, 0, time.UTC) |
| + missing := hour.Add(55 * time.Minute) |
| + for batch := 0; batch < 4; batch++ { |
| + byBox := map[string][]status.TrafficWindow{"box-a": {}, "box-b": {}} |
| + for offset := 0; offset < 3; offset++ { |
| + at := hour.Add(time.Duration(batch*3+offset) * 5 * time.Minute) |
| + byBox["box-a"] = append(byBox["box-a"], trafficStoreWindow(at)) |
| + if !at.Equal(missing) { |
| + byBox["box-b"] = append(byBox["box-b"], trafficStoreWindow(at)) |
| + } |
| + } |
| + if _, err := s.IngestTraffic(byBox, trafficStoreNow); err != nil { |
| + t.Fatalf("batch %d ingest: %v", batch, err) |
| + } |
| + } |
| + hours, err := s.TrafficHours(hour, hour.Add(time.Hour)) |
| + if err != nil || len(hours) != 1 || hours[0].Windows != 12 || hours[0].Boxes != 2 || hours[0].BoxWindows != 23 || !hours[0].Partial(trafficStoreNow) { |
| + t.Fatalf("hour with one missing box window = %+v, %v; want 12 starts, 2 boxes, 23 rows, partial", hours, err) |
| + } |
| + if _, err := s.IngestTraffic(map[string][]status.TrafficWindow{"box-b": {trafficStoreWindow(missing)}}, trafficStoreNow); err != nil { |
| + t.Fatal(err) |
| + } |
| + hours, err = s.TrafficHours(hour, hour.Add(time.Hour)) |
| + if err != nil || len(hours) != 1 || hours[0].BoxWindows != 24 || hours[0].Partial(trafficStoreNow) { |
| + t.Fatalf("hour after late missing window = %+v, %v; want complete 24 rows", hours, err) |
| + } |
| +} |
| + |
| +// TestTrafficIngestRollsBackAndRetries proves the rows and inserted count are |
| +// atomic when the hourly materialisation fails, and that retry can store them. |
| +func TestTrafficIngestRollsBackAndRetries(t *testing.T) { |
| + s := openTestStore(t) |
| + if _, err := s.db.Exec(`CREATE TRIGGER traffic_hours_fail BEFORE INSERT ON traffic_hours BEGIN SELECT RAISE(ABORT, 'forced'); END`); err != nil { |
| + t.Fatal(err) |
| + } |
| + w := trafficStoreWindow(trafficStoreAt(5)) |
| + inserted, err := s.IngestTraffic(map[string][]status.TrafficWindow{"box-a": {w}}, trafficStoreNow) |
| + if err == nil || inserted != 0 { |
| + t.Fatalf("failed ingest = %d, %v; want rollback and zero inserted", inserted, err) |
| + } |
| + if got := alertCount(t, s, "traffic_windows"); got != 0 { |
| + t.Fatalf("rows survived failed rollup: %d", got) |
| + } |
| + if _, err := s.db.Exec(`DROP TRIGGER traffic_hours_fail`); err != nil { |
| + t.Fatal(err) |
| + } |
| + inserted, err = s.IngestTraffic(map[string][]status.TrafficWindow{"box-a": {w}}, trafficStoreNow) |
| + if err != nil || inserted != 1 { |
| + t.Fatalf("retry = %d, %v; want one inserted row", inserted, err) |
| + } |
| +} |
| + |
| +// TestTrafficRangeUsesHalfOpenEndpoints fixes the inclusive-from/exclusive-to |
| +// contract used by callers that combine adjacent chart ranges. |
| +func TestTrafficRangeUsesHalfOpenEndpoints(t *testing.T) { |
| + s := openTestStore(t) |
| + starts := []time.Time{trafficStoreAt(15), trafficStoreAt(10), trafficStoreAt(5)} |
| + windows := []status.TrafficWindow{} |
| + for _, start := range starts { |
| + w := trafficStoreWindow(start) |
| + w.Requests, w.S2xx = 2, 2 |
| + windows = append(windows, w) |
| + } |
| + if _, err := s.IngestTraffic(map[string][]status.TrafficWindow{"box-a": windows}, trafficStoreNow); err != nil { |
| + t.Fatal(err) |
| + } |
| + sum, gotStarts, err := s.TrafficRange(starts[1], starts[2]) |
| + if err != nil || sum.Requests != 2 || !reflect.DeepEqual(gotStarts, map[int64]bool{starts[1].Unix(): true}) { |
| + t.Fatalf("half-open range = requests %d starts %v err %v", sum.Requests, gotStarts, err) |
| + } |
| +} |
| + |
| +// TestTrafficStoreSurvivesReopen verifies migration-on-open preserves the |
| +// traffic rows and their rollup body across a normal console restart. |
| +func TestTrafficStoreSurvivesReopen(t *testing.T) { |
| + path := filepath.Join(t.TempDir(), "console.db") |
| + s, err := Open(path) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + w := trafficStoreWindow(trafficStoreAt(5)) |
| + w.Requests, w.S2xx, w.Blocked = 9, 9, 3 |
| + if n, err := s.IngestTraffic(map[string][]status.TrafficWindow{"box-a": {w}}, trafficStoreNow); err != nil || n != 1 { |
| + t.Fatalf("ingest = %d, %v", n, err) |
| + } |
| + if err := s.Close(); err != nil { |
| + t.Fatal(err) |
| + } |
| + s, err = Open(path) |
| + if err != nil { |
| + t.Fatalf("reopen: %v", err) |
| + } |
| + defer s.Close() |
| + sum, starts, err := s.TrafficRange(time.Unix(w.Start, 0), time.Unix(w.Start+300, 0)) |
| + if err != nil || sum.Requests != 9 || sum.Blocked != 3 || len(starts) != 1 { |
| + t.Fatalf("after reopen = %+v starts=%v err=%v", sum, starts, err) |
| + } |
| + hours, err := s.TrafficHours(time.Unix(w.Start, 0).Truncate(time.Hour), time.Unix(w.Start, 0).Truncate(time.Hour).Add(time.Hour)) |
| + if err != nil || len(hours) != 1 || hours[0].Sum.Requests != 9 { |
| + t.Fatalf("hour after reopen = %+v, %v", hours, err) |
| + } |
| +} |
| + |
| +// TestTrafficIngestClaimGate checks that newly migrated traffic tables are |
| +// explicitly treated as non-app telemetry by the claim SQL census. |
| +func TestTrafficIngestClaimGate(t *testing.T) { |
| + s := openGatedStore(t) |
| + if _, err := s.IngestTraffic(map[string][]status.TrafficWindow{"box-a": {trafficStoreWindow(trafficStoreAt(5))}}, trafficStoreNow); err != nil { |
| + t.Fatal(err) |
| + } |
| + present, err := claimSQLCensus(s.bootDB(), claimSQLTables) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, name := range []string{"traffic_windows", "traffic_hours"} { |
| + spec, ok := present[name] |
| + if !ok || spec.NonApp == "" { |
| + t.Errorf("%s classification = %+v (present %v), want NonApp", name, spec, ok) |
| + } |
| + } |
| +} |