From c3200bc15691a3785c1a698fb7980436cfd0e8b0 Mon Sep 17 00:00:00 2001 From: Fredrik Ahlgren Date: Sat, 21 Nov 2026 12:28:58 +0100 Subject: [PATCH] fix(api): cap history and series points at 2000 GET /api/history and GET /api/series took any points value. A huge one reached the store, which refused it, so the caller got a 500; values up to the store's 10000-bucket limit built replies five times the size of the energy history's 2000-bucket budget. /api/series also read a negative or non-numeric value as 0, which returns every stored row, and /api/history quietly used 200. Both routes now share parseHistoryPoints: omitted keeps each route's default (200 rows for history, stored rows for series), a value above 2000 is clamped to 2000 so older clients still get an answer, and a value that is not a whole number, or is below 0, gets a 400. points=0 keeps its meaning on both routes. The agent route hints name the cap. For #1136. Signed-off-by: Fredrik Ahlgren Co-Authored-By: Claude Opus 5.5 --- .changeset/history-points-cap.md | 9 ++ go/internal/api/api.go | 50 ++++++--- go/internal/api/api_agent_catalog.go | 6 +- go/internal/api/api_history_points_test.go | 117 +++++++++++++++++++++ 4 files changed, 165 insertions(+), 17 deletions(-) create mode 100644 .changeset/history-points-cap.md create mode 100644 go/internal/api/api_history_points_test.go diff --git a/.changeset/history-points-cap.md b/.changeset/history-points-cap.md new file mode 100644 index 000000000..2b8c92819 --- /dev/null +++ b/.changeset/history-points-cap.md @@ -0,0 +1,9 @@ +--- +"ftw": patch +--- + +History reads now return at most 2000 rows. `/api/history` and +`/api/series` cut a larger `points` value down to 2000 instead of failing +or building a huge reply, and they refuse a `points` value that is not a +whole number, or is below 0, with a 400. The dashboard's own reads are +unchanged. diff --git a/go/internal/api/api.go b/go/internal/api/api.go index 1f3b3a227..1dd8cd0b2 100644 --- a/go/internal/api/api.go +++ b/go/internal/api/api.go @@ -2436,19 +2436,41 @@ func (s *Server) handleSelfTuneCancel(w http.ResponseWriter, r *http.Request) { // ---- /api/history ---- +// historyMaxPoints bounds the rows one /api/history or /api/series read +// asks for. It is the bucket budget /api/energy/history already uses. +const historyMaxPoints = energyHistoryMaxBuckets + +// parseHistoryPoints reads ?points=. Omitted gives dflt. A larger value is +// clamped to historyMaxPoints, so a client that asks for more still gets an +// answer, at a coarser step. A value that is not a whole number, or is +// negative, is refused. +func parseHistoryPoints(r *http.Request, dflt int) (int, error) { + raw := r.URL.Query().Get("points") + if raw == "" { + return dflt, nil + } + n, err := strconv.Atoi(raw) + if err != nil || n < 0 { + return 0, fmt.Errorf("points must be a whole number, 0 or more") + } + return min(n, historyMaxPoints), nil +} + // handleHistory returns time-series points from state DB. -// Query params: range=5m|15m|1h|6h|24h|3d, points=N +// Query params: range=5m|15m|1h|6h|24h|3d, points=N (0 or omitted: 200; +// at most historyMaxPoints) func (s *Server) handleHistory(w http.ResponseWriter, r *http.Request) { rangeStr := r.URL.Query().Get("range") if rangeStr == "" { rangeStr = "5m" } - pointsStr := r.URL.Query().Get("points") - points := 200 - if pointsStr != "" { - if n, err := strconv.Atoi(pointsStr); err == nil && n > 0 { - points = n - } + points, err := parseHistoryPoints(r, 200) + if err != nil { + writeJSON(w, 400, map[string]string{"error": err.Error()}) + return + } + if points == 0 { + points = 200 } windowMs := parseRange(rangeStr) @@ -3026,8 +3048,9 @@ func (s *Server) handleMPCDiagnoseAt(w http.ResponseWriter, r *http.Request) { // - metric: one name, or several comma-separated (battery_w,heatsink_c) // - range: relative window ending now (1h, 24h, 30d, ...), OR // - since/until: absolute unix-ms bounds (until defaults to now) -// - points: downsampling budget; 0 = stored resolution. Aggregate points carry -// the bucket envelope: v = avg, min/max = extremes, n = sample count +// - points: downsampling budget, at most historyMaxPoints; 0 = stored +// resolution. Aggregate points carry the bucket envelope: v = avg, +// min/max = extremes, n = sample count // - format=csv: long-format CSV with the same observation metadata instead // of JSON — for spreadsheet / ML export // @@ -3042,11 +3065,10 @@ func (s *Server) handleSeries(w http.ResponseWriter, r *http.Request) { } metrics := strings.Split(metricsParam, ",") - points := 0 - if p := r.URL.Query().Get("points"); p != "" { - if v, err := strconv.Atoi(p); err == nil { - points = v - } + points, err := parseHistoryPoints(r, 0) + if err != nil { + writeJSON(w, 400, map[string]string{"error": err.Error()}) + return } // Window: absolute since/until when given, else relative range. diff --git a/go/internal/api/api_agent_catalog.go b/go/internal/api/api_agent_catalog.go index 42a75d3ed..02a109c4f 100644 --- a/go/internal/api/api_agent_catalog.go +++ b/go/internal/api/api_agent_catalog.go @@ -34,13 +34,13 @@ var agentAPIHints = []protocol.AgentAPIRoute{ {Path: "/api/mpc/diagnose", Description: "Current planner inputs, constraints and result"}, {Path: "/api/mpc/diagnose/history", Description: "Recorded planning decisions", Query: map[string]string{"since": "Unix milliseconds", "until": "Unix milliseconds", "limit": "Maximum snapshots, up to 5000"}}, {Path: "/api/mpc/diagnose/at", Description: "The planning snapshot active at an incident", Query: map[string]string{"ts": "Required incident time, Unix milliseconds"}}, - {Path: "/api/history", Description: "Recorded site measurements", Query: map[string]string{"range": "Time back, such as 1h", "points": "Maximum rows"}}, + {Path: "/api/history", Description: "Recorded site measurements", Query: map[string]string{"range": "Time back, such as 1h", "points": "Maximum rows, up to 2000"}}, {Path: "/api/energy/daily", Description: "Daily measured energy and costs", Query: map[string]string{"days": "Number of days"}}, {Path: "/api/energy/assets", Description: "Energy-ledger assets by configured name"}, {Path: "/api/energy/history", Description: "Energy-ledger entries in Wh, including flow, source, quality, provenance and sample count", Query: map[string]string{"scope": "system or asset", "asset_id": "Asset id from /api/energy/assets", "since": "Unix milliseconds", "until": "Unix milliseconds", "bucket": "Bucket duration, at least 5m", "limit": "Maximum buckets, up to 5000"}}, {Path: "/api/savings/daily", Description: "Daily cost comparison and coverage", Query: map[string]string{"days": "Number of days"}}, {Path: "/api/series/catalog", Description: "Stored drivers, metric names and units"}, - {Path: "/api/series", Description: "One driver's measured series with min, max, sample count, resolution and bounds", Query: map[string]string{"driver": "Required driver name from /api/series/catalog", "metric": "Required metric name or comma-separated names from the catalogue", "range": "Time back, such as 6h", "since": "Unix milliseconds", "until": "Unix milliseconds", "points": "Maximum points per metric"}}, + {Path: "/api/series", Description: "One driver's measured series with min, max, sample count, resolution and bounds", Query: map[string]string{"driver": "Required driver name from /api/series/catalog", "metric": "Required metric name or comma-separated names from the catalogue", "range": "Time back, such as 6h", "since": "Unix milliseconds", "until": "Unix milliseconds", "points": "Maximum points per metric, up to 2000"}}, } // These GET handlers return diagnostic data despite their Local tier for @@ -109,7 +109,7 @@ var agentAPIQueryHints = map[string]map[string]string{ "/api/ev/status": {"driver": "Configured driver name"}, "/api/research/load/dump": {"days": "Days of original observations, 1 to 365; tar.gz export"}, "/api/agents/audit": {"before": "Audit sequence before which to page", "n": "Maximum audit rows"}, - "/api/series": {"driver": "Configured driver name", "metric": "Metric or comma-separated metrics from /api/series/catalog", "range": "Time back, such as 6h", "since": "Unix milliseconds", "until": "Unix milliseconds", "points": "Maximum points per metric; 0 returns stored rows", "format": "json (default) or csv"}, + "/api/series": {"driver": "Configured driver name", "metric": "Metric or comma-separated metrics from /api/series/catalog", "range": "Time back, such as 6h", "since": "Unix milliseconds", "until": "Unix milliseconds", "points": "Maximum points per metric, up to 2000; 0 returns stored rows", "format": "json (default) or csv"}, "/api/energy/history.csv": {"scope": "system or asset", "asset_id": "Asset id from /api/energy/assets", "since": "Unix milliseconds", "until": "Unix milliseconds", "bucket": "Bucket duration, at least 5m", "limit": "Maximum buckets, up to 5000"}, "/api/energy/battery-return": {"year": "Calendar year in Swedish time, 2018 to now; default last year"}, "/api/energy/battery-return.csv": {"year": "Calendar year in Swedish time, 2018 to now; default last year"}, diff --git a/go/internal/api/api_history_points_test.go b/go/internal/api/api_history_points_test.go new file mode 100644 index 000000000..32cf16408 --- /dev/null +++ b/go/internal/api/api_history_points_test.go @@ -0,0 +1,117 @@ +package api + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "path/filepath" + "testing" + "time" + + "github.com/srcfl/ftw/go/internal/state" +) + +// storedRows is more than historyMaxPoints, one second apart, so a read +// that is not clamped returns more rows than the limit allows. +const storedRows = 3000 + +func newHistoryPointsServer(t *testing.T) *Server { + t.Helper() + st, err := state.Open(filepath.Join(t.TempDir(), "state.db")) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = st.Close() }) + start := time.Now().Add(-55 * time.Minute).UnixMilli() + samples := make([]state.Sample, 0, storedRows) + for i := int64(0); i < storedRows; i++ { + ts := start + i*1000 + if err := st.RecordHistory(state.HistoryPoint{TsMs: ts, GridW: 1000, PVW: -200, LoadW: 800, JSON: "{}"}); err != nil { + t.Fatal(err) + } + samples = append(samples, state.Sample{Driver: "meter", Metric: "meter_w", TsMs: ts, Value: 1000, Unit: "W"}) + } + if err := st.RecordSamples(samples); err != nil { + t.Fatal(err) + } + return New(&Deps{State: st}) +} + +func historyPointsGet(t *testing.T, srv *Server, url string) (int, int) { + t.Helper() + rr := httptest.NewRecorder() + srv.mux.ServeHTTP(rr, httptest.NewRequest(http.MethodGet, url, nil)) + if rr.Code != http.StatusOK { + return rr.Code, 0 + } + var body struct { + Items []json.RawMessage `json:"items"` + Points []json.RawMessage `json:"points"` + } + if err := json.Unmarshal(rr.Body.Bytes(), &body); err != nil { + t.Fatalf("%s: %v: %s", url, err, rr.Body.String()) + } + return rr.Code, len(body.Items) + len(body.Points) +} + +func TestHistoryAndSeriesClampLargePoints(t *testing.T) { + srv := newHistoryPointsServer(t) + for _, url := range []string{ + "/api/history?range=1h&points=5000", + "/api/history?range=1h&points=1000000000", + "/api/series?driver=meter&metric=meter_w&range=1h&points=5000", + "/api/series?driver=meter&metric=meter_w&range=1h&points=1000000000", + } { + code, n := historyPointsGet(t, srv, url) + if code != http.StatusOK { + t.Errorf("%s: status %d, want 200 with points clamped", url, code) + continue + } + if n == 0 || n > historyMaxPoints { + t.Errorf("%s: %d rows, want 1..%d", url, n, historyMaxPoints) + } + } +} + +func TestHistoryAndSeriesRefuseBadPoints(t *testing.T) { + srv := newHistoryPointsServer(t) + for _, base := range []string{ + "/api/history?range=1h&points=", + "/api/series?driver=meter&metric=meter_w&range=1h&points=", + } { + for _, bad := range []string{"-1", "-5000", "abc", "1.5", "99999999999999999999"} { + if code, _ := historyPointsGet(t, srv, base+bad); code != http.StatusBadRequest { + t.Errorf("%s%s: status %d, want 400", base, bad, code) + } + } + } +} + +func TestHistoryPointsZeroAndOmittedKeepDashboardDefault(t *testing.T) { + srv := newHistoryPointsServer(t) + for _, url := range []string{ + "/api/history?range=1h", + "/api/history?range=1h&points=0", + } { + code, n := historyPointsGet(t, srv, url) + if code != http.StatusOK || n == 0 || n > 200 { + t.Errorf("%s: status %d, %d rows; want 200 and 1..200 rows", url, code, n) + } + } + if code, n := historyPointsGet(t, srv, "/api/history?range=1h&points=360"); code != http.StatusOK || n <= 200 || n > 360 { + t.Errorf("points=360: status %d, %d rows; want the dashboard's 360-point budget", code, n) + } +} + +func TestSeriesPointsZeroAndOmittedReturnStoredRows(t *testing.T) { + srv := newHistoryPointsServer(t) + for _, url := range []string{ + "/api/series?driver=meter&metric=meter_w&range=1h", + "/api/series?driver=meter&metric=meter_w&range=1h&points=0", + } { + code, n := historyPointsGet(t, srv, url) + if code != http.StatusOK || n != storedRows { + t.Errorf("%s: status %d, %d rows; want 200 and all %d stored rows", url, code, n, storedRows) + } + } +}