Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions .changeset/history-points-cap.md
Original file line number Diff line number Diff line change
@@ -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.
50 changes: 36 additions & 14 deletions go/internal/api/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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
//
Expand All @@ -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.
Expand Down
6 changes: 3 additions & 3 deletions go/internal/api/api_agent_catalog.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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"},
Expand Down
117 changes: 117 additions & 0 deletions go/internal/api/api_history_points_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
}
}
Loading