Compare commits

..
6 Commits
Author SHA1 Message Date
Noel 9478612f1e Merge pull request 'feat: add read-only playground forecast endpoint' (#5) from feat/playground into main
ci / check (push) Successful in 1m0s
Reviewed-on: #5
2026-11-14 20:11:03 +00:00
Noel Sabia b145201022 Merge remote-tracking branch 'refs/remotes/gitea-https/main' into feat/playground
ci / check (push) Successful in 59s
ci / check (pull_request) Successful in 56s
2026-11-14 21:09:09 +01:00
Noel Sabia c1f701fc16 feat: add read-only playground forecast endpoint
ci / check (push) Successful in 58s
2026-11-14 20:49:39 +01:00
Noel a6a4e7509e Merge pull request 'feat: PreZero priority API proxy' (#4) from feat/prezero-api into main
ci / check (push) Successful in 56s
Reviewed-on: #4
2026-11-14 18:24:48 +00:00
Noel Sabia 7e9c2d9663 feat: proxy PreZero priority endpoints to FastAPI
ci / check (push) Successful in 58s
ci / check (pull_request) Successful in 55s
2026-11-14 17:50:53 +01:00
Noel a0ad60ec53 Merge pull request 'feat: ci docs' (#3) from feat/ci-docs into main
ci / check (push) Successful in 56s
Reviewed-on: #3
2026-11-14 08:34:33 +00:00
8 changed files with 1047 additions and 11 deletions

No files matched your search

+1
View File
@@ -28,6 +28,7 @@ first snapshot arrives. Control endpoints return `503` until `CONTROL_USER` and
| `GET /api/series` | Observed series; query `sensor`, `from`, `to`, `step=15m\|1h`. | | `GET /api/series` | Observed series; query `sensor`, `from`, `to`, `step=15m\|1h`. |
| `GET /api/context` | Weather and holidays. | | `GET /api/context` | Weather and holidays. |
| `GET /api/forecast` | Live forecast or last-good fallback; query `sensor`, `horizon`, `scenario`. | | `GET /api/forecast` | Live forecast or last-good fallback; query `sensor`, `horizon`, `scenario`. |
| `GET /api/playground/forecast` | Read-only forecast with optional `temp_c`, `precip_mm`, `is_holiday`; never mutates scenario state. |
| `GET /api/staffing` | Shift plan; query `sensor`, `scenario`, `standard`. | | `GET /api/staffing` | Shift plan; query `sensor`, `scenario`, `standard`. |
| `GET /api/scenario` | Current scenario. | | `GET /api/scenario` | Current scenario. |
| `POST /api/scenario` | Set scenario (control auth) and broadcast it over SSE. | | `POST /api/scenario` | Set scenario (control auth) and broadcast it over SSE. |
+170
View File
@@ -0,0 +1,170 @@
package api
import (
"context"
"fmt"
"log/slog"
"math"
"net/http"
"strconv"
"pulsecast/api/internal/ml"
"pulsecast/api/internal/model"
)
// PlaygroundClient is the optional FastAPI playground surface. It is separate
// from MLClient so existing prediction-only stubs and handlers keep working.
type PlaygroundClient interface {
PlaygroundPredict(ctx context.Context, req ml.PlaygroundRequest) (ml.PlaygroundResponse, error)
}
// handlePlaygroundForecast is a read-only, public forecast endpoint with
// optional weather and holiday overrides. It never mutates the global scenario
// state used by /live, /stage, or /cool.
func (s *Server) handlePlaygroundForecast(w http.ResponseWriter, r *http.Request) {
query := r.URL.Query()
sensor := query.Get("sensor")
if sensor == "" {
writeError(w, http.StatusBadRequest, "bad_request", "sensor is required")
return
}
if s.cache == nil {
writeError(w, http.StatusNotFound, "not_found", "unknown sensor")
return
}
if _, ok := s.cache.Sensor(sensor); !ok {
writeError(w, http.StatusNotFound, "not_found", "unknown sensor")
return
}
horizon := query.Get("horizon")
if horizon == "" {
horizon = "48h"
}
if !model.Contains(model.Horizons, horizon) {
writeError(w, http.StatusBadRequest, "bad_request", "horizon must be one of 15m, 1h, 48h, 7d")
return
}
scenarioName := query.Get("scenario")
if scenarioName == "" {
scenarioName = "base"
}
if !model.Contains(model.Scenarios, scenarioName) {
writeError(w, http.StatusBadRequest, "bad_request", "unknown scenario")
return
}
tempC, err := optionalFloat(query.Get("temp_c"), "temp_c")
if err != nil {
writeError(w, http.StatusBadRequest, "bad_request", err.Error())
return
}
if tempC != nil && (*tempC < -30 || *tempC > 50) {
writeError(w, http.StatusBadRequest, "bad_request", "temp_c must be between -30 and 50")
return
}
precipMM, err := optionalFloat(query.Get("precip_mm"), "precip_mm")
if err != nil {
writeError(w, http.StatusBadRequest, "bad_request", err.Error())
return
}
if precipMM != nil && (*precipMM < 0 || *precipMM > 50) {
writeError(w, http.StatusBadRequest, "bad_request", "precip_mm must be between 0 and 50")
return
}
isHoliday, err := optionalBool(query.Get("is_holiday"))
if err != nil {
writeError(w, http.StatusBadRequest, "bad_request", "is_holiday must be a boolean")
return
}
client, ok := s.ml.(PlaygroundClient)
if !ok || client == nil {
writeError(w, http.StatusBadGateway, "ml_unavailable", "FastAPI prediction is unavailable")
return
}
var weather *ml.PlaygroundWeather
if tempC != nil || precipMM != nil {
weather = &ml.PlaygroundWeather{TempC: tempC, PrecipMM: precipMM}
}
ctx, cancel := context.WithTimeout(r.Context(), s.cfg.MLTimeout)
defer cancel()
result, err := client.PlaygroundPredict(ctx, ml.PlaygroundRequest{
Sensor: sensor,
Horizon: horizon,
Scenario: scenarioName,
Weather: weather,
IsHoliday: isHoliday,
})
if err != nil {
slog.Warn("playground prediction failed", "sensor", sensor, "scenario", scenarioName, "error", err)
writeError(w, http.StatusBadGateway, "ml_unavailable", "FastAPI prediction is unavailable")
return
}
weatherSource := "forecast"
if weather != nil {
weatherSource = "override"
}
w.Header().Set("X-Data-Version", result.DataVersion)
w.Header().Set("X-Model-Version", result.ModelVersion)
w.Header().Set("X-Context-Version", result.ContextVersion)
writeJSON(w, http.StatusOK, struct {
Sensor string `json:"sensor"`
Horizon string `json:"horizon"`
Scenario string `json:"scenario"`
Points []model.ForecastPoint `json:"points"`
DataVersion string `json:"data_version"`
ModelVersion string `json:"model_version"`
ContextVersion string `json:"context_version"`
WeatherSource string `json:"weather_source"`
Request struct {
TempC *float64 `json:"temp_c,omitempty"`
PrecipMM *float64 `json:"precip_mm,omitempty"`
IsHoliday *bool `json:"is_holiday,omitempty"`
} `json:"request"`
}{
Sensor: result.Sensor,
Horizon: result.Horizon,
Scenario: result.Scenario,
Points: result.Points,
DataVersion: result.DataVersion,
ModelVersion: result.ModelVersion,
ContextVersion: result.ContextVersion,
WeatherSource: weatherSource,
Request: struct {
TempC *float64 `json:"temp_c,omitempty"`
PrecipMM *float64 `json:"precip_mm,omitempty"`
IsHoliday *bool `json:"is_holiday,omitempty"`
}{TempC: tempC, PrecipMM: precipMM, IsHoliday: isHoliday},
})
}
func optionalFloat(raw, name string) (*float64, error) {
if raw == "" {
return nil, nil
}
value, err := strconv.ParseFloat(raw, 64)
if err != nil || math.IsNaN(value) || math.IsInf(value, 0) {
return nil, fmt.Errorf("%s must be a number", name)
}
return &value, nil
}
func optionalBool(raw string) (*bool, error) {
if raw == "" {
return nil, nil
}
value, err := strconv.ParseBool(raw)
if err != nil {
return nil, err
}
return &value, nil
}
+200
View File
@@ -0,0 +1,200 @@
package api
import (
"context"
"errors"
"net/http"
"strings"
"testing"
"time"
"pulsecast/api/internal/ml"
"pulsecast/api/internal/model"
)
type stubPlayground struct {
*stubML
fn func(context.Context, ml.PlaygroundRequest) (ml.PlaygroundResponse, error)
}
func (s *stubPlayground) PlaygroundPredict(ctx context.Context, req ml.PlaygroundRequest) (ml.PlaygroundResponse, error) {
if s.fn == nil {
return ml.PlaygroundResponse{}, errors.New("ml unavailable")
}
return s.fn(ctx, req)
}
func playgroundResponse() ml.PlaygroundResponse {
return ml.PlaygroundResponse{
Sensor: "hn-bahnhof-01",
Horizon: "48h",
Scenario: "base",
Points: []model.ForecastPoint{{
T: time.Date(2026, 11, 16, 9, 0, 0, 0, time.UTC), V: 12.3, Lo: 8.1, Hi: 17.2,
}},
DataVersion: "data-1",
ModelVersion: "model-1",
ContextVersion: "context-1",
}
}
type playgroundJSON struct {
Sensor string `json:"sensor"`
Horizon string `json:"horizon"`
Scenario string `json:"scenario"`
Points []model.ForecastPoint `json:"points"`
DataVersion string `json:"data_version"`
ModelVersion string `json:"model_version"`
ContextVersion string `json:"context_version"`
WeatherSource string `json:"weather_source"`
Request struct {
TempC *float64 `json:"temp_c"`
PrecipMM *float64 `json:"precip_mm"`
IsHoliday *bool `json:"is_holiday"`
} `json:"request"`
}
func TestPlaygroundForecastDefaults(t *testing.T) {
var got ml.PlaygroundRequest
client := &stubPlayground{
stubML: &stubML{},
fn: func(_ context.Context, req ml.PlaygroundRequest) (ml.PlaygroundResponse, error) {
got = req
return playgroundResponse(), nil
},
}
_, ts := newTestServer(t, client, nil)
var payload playgroundJSON
resp := getJSON(t, ts.URL+"/api/playground/forecast?sensor=hn-bahnhof-01", &payload)
if resp.StatusCode != http.StatusOK {
t.Fatalf("status=%d", resp.StatusCode)
}
if got.Horizon != "48h" || got.Scenario != "base" {
t.Fatalf("defaults horizon=%q scenario=%q", got.Horizon, got.Scenario)
}
if got.Weather != nil || got.IsHoliday != nil {
t.Fatalf("unexpected overrides: weather=%+v holiday=%v", got.Weather, got.IsHoliday)
}
if payload.WeatherSource != "forecast" {
t.Errorf("weather_source=%q", payload.WeatherSource)
}
if payload.ModelVersion != "model-1" || payload.DataVersion != "data-1" || payload.ContextVersion != "context-1" {
t.Fatalf("versions=%+v", payload)
}
if resp.Header.Get("X-Model-Version") != "model-1" {
t.Errorf("X-Model-Version=%q", resp.Header.Get("X-Model-Version"))
}
if len(payload.Points) != 1 || payload.Points[0].V != 12.3 {
t.Fatalf("points=%+v", payload.Points)
}
}
func TestPlaygroundForecastOverrides(t *testing.T) {
var got ml.PlaygroundRequest
client := &stubPlayground{
stubML: &stubML{},
fn: func(_ context.Context, req ml.PlaygroundRequest) (ml.PlaygroundResponse, error) {
got = req
return playgroundResponse(), nil
},
}
_, ts := newTestServer(t, client, nil)
var payload playgroundJSON
resp := getJSON(t, ts.URL+"/api/playground/forecast?sensor=hn-bahnhof-01&temp_c=29&precip_mm=0&is_holiday=true", &payload)
if resp.StatusCode != http.StatusOK {
t.Fatalf("status=%d", resp.StatusCode)
}
if got.Weather == nil || got.Weather.TempC == nil || *got.Weather.TempC != 29 {
t.Fatalf("weather=%+v", got.Weather)
}
if got.Weather.PrecipMM == nil || *got.Weather.PrecipMM != 0 {
t.Fatalf("precip=%+v", got.Weather.PrecipMM)
}
if got.IsHoliday == nil || !*got.IsHoliday {
t.Fatalf("holiday=%+v", got.IsHoliday)
}
if payload.WeatherSource != "override" {
t.Errorf("weather_source=%q", payload.WeatherSource)
}
if payload.Request.TempC == nil || *payload.Request.TempC != 29 {
t.Errorf("request echo temp=%+v", payload.Request.TempC)
}
if payload.Request.IsHoliday == nil || !*payload.Request.IsHoliday {
t.Errorf("request echo holiday=%+v", payload.Request.IsHoliday)
}
}
func TestPlaygroundForecastValidation(t *testing.T) {
_, ts := newTestServer(t, &stubPlayground{stubML: &stubML{}}, nil)
cases := []struct {
path string
status int
code string
}{
{"/api/playground/forecast", http.StatusBadRequest, "bad_request"},
{"/api/playground/forecast?sensor=nope", http.StatusNotFound, "not_found"},
{"/api/playground/forecast?sensor=hn-bahnhof-01&horizon=2h", http.StatusBadRequest, "bad_request"},
{"/api/playground/forecast?sensor=hn-bahnhof-01&scenario=party", http.StatusBadRequest, "bad_request"},
{"/api/playground/forecast?sensor=hn-bahnhof-01&temp_c=hot", http.StatusBadRequest, "bad_request"},
{"/api/playground/forecast?sensor=hn-bahnhof-01&temp_c=51", http.StatusBadRequest, "bad_request"},
{"/api/playground/forecast?sensor=hn-bahnhof-01&temp_c=NaN", http.StatusBadRequest, "bad_request"},
{"/api/playground/forecast?sensor=hn-bahnhof-01&precip_mm=-1", http.StatusBadRequest, "bad_request"},
{"/api/playground/forecast?sensor=hn-bahnhof-01&precip_mm=51", http.StatusBadRequest, "bad_request"},
{"/api/playground/forecast?sensor=hn-bahnhof-01&is_holiday=maybe", http.StatusBadRequest, "bad_request"},
}
for _, tc := range cases {
var body model.ErrorBody
resp := getJSON(t, ts.URL+tc.path, &body)
if resp.StatusCode != tc.status {
t.Errorf("%s: status=%d, want %d", tc.path, resp.StatusCode, tc.status)
}
if body.Error.Code != tc.code {
t.Errorf("%s: code=%q, want %q", tc.path, body.Error.Code, tc.code)
}
}
}
func TestPlaygroundForecastUpstreamFailure(t *testing.T) {
client := &stubPlayground{
stubML: &stubML{},
fn: func(context.Context, ml.PlaygroundRequest) (ml.PlaygroundResponse, error) {
return ml.PlaygroundResponse{}, errors.New("connection refused")
},
}
_, ts := newTestServer(t, client, nil)
var body model.ErrorBody
resp := getJSON(t, ts.URL+"/api/playground/forecast?sensor=hn-bahnhof-01", &body)
if resp.StatusCode != http.StatusBadGateway {
t.Fatalf("status=%d, want 502", resp.StatusCode)
}
if body.Error.Code != "ml_unavailable" {
t.Fatalf("error=%+v", body.Error)
}
}
func TestPlaygroundForecastMethodNotAllowed(t *testing.T) {
_, ts := newTestServer(t, &stubPlayground{stubML: &stubML{}}, nil)
resp, err := http.Post(ts.URL+"/api/playground/forecast", "application/json", strings.NewReader("{}"))
if err != nil {
t.Fatalf("POST: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusMethodNotAllowed {
t.Fatalf("status=%d, want 405", resp.StatusCode)
}
}
func TestPlaygroundForecastMissingMLClient(t *testing.T) {
_, ts := newTestServer(t, &stubML{}, nil)
var body model.ErrorBody
resp := getJSON(t, ts.URL+"/api/playground/forecast?sensor=hn-bahnhof-01", &body)
if resp.StatusCode != http.StatusBadGateway {
t.Fatalf("status=%d, want 502", resp.StatusCode)
}
if body.Error.Code != "ml_unavailable" {
t.Fatalf("error=%+v", body.Error)
}
}
+97
View File
@@ -0,0 +1,97 @@
package api
import (
"log/slog"
"net/http"
"strconv"
"pulsecast/api/internal/model"
)
// PreZero query defaults and bounds from PREZERO_API_CONTRACT.md §3.
const (
defaultPreZeroLimit = 50
maxPreZeroLimit = 500
)
// PreZeroPriorities are the accepted tier filters.
var PreZeroPriorities = []string{"high", "medium", "low"}
// handlePreZeroSummary proxies GET /api/prezero/summary to FastAPI.
func (s *Server) handlePreZeroSummary(w http.ResponseWriter, r *http.Request) {
if s.prezero == nil {
writeError(w, http.StatusBadGateway, "ml_unavailable", "FastAPI PreZero client is not configured")
return
}
status, body, err := s.prezero.PreZeroSummary(r.Context())
if err != nil {
slog.Warn("prezero summary proxy failed", "error", err)
writeError(w, http.StatusBadGateway, "ml_unavailable", "FastAPI is unavailable")
return
}
relayMLResponse(w, status, body)
}
// handlePreZeroPriority proxies GET /api/prezero/priority. The query is
// validated here so bad input never reaches FastAPI.
func (s *Server) handlePreZeroPriority(w http.ResponseWriter, r *http.Request) {
query := r.URL.Query()
priority := query.Get("priority")
if priority != "" && !model.Contains(PreZeroPriorities, priority) {
writeError(w, http.StatusBadRequest, "bad_request", "priority must be high, medium or low")
return
}
limit := defaultPreZeroLimit
if raw := query.Get("limit"); raw != "" {
parsed, err := strconv.Atoi(raw)
if err != nil || parsed < 1 || parsed > maxPreZeroLimit {
writeError(w, http.StatusBadRequest, "bad_request", "limit must be an integer between 1 and 500")
return
}
limit = parsed
}
offset := 0
if raw := query.Get("offset"); raw != "" {
parsed, err := strconv.Atoi(raw)
if err != nil || parsed < 0 {
writeError(w, http.StatusBadRequest, "bad_request", "offset must be an integer greater than or equal to 0")
return
}
offset = parsed
}
if s.prezero == nil {
writeError(w, http.StatusBadGateway, "ml_unavailable", "FastAPI PreZero client is not configured")
return
}
status, body, err := s.prezero.PreZeroPriority(r.Context(), priority, limit, offset)
if err != nil {
slog.Warn("prezero priority proxy failed", "priority", priority, "error", err)
writeError(w, http.StatusBadGateway, "ml_unavailable", "FastAPI is unavailable")
return
}
relayMLResponse(w, status, body)
}
// handlePreZeroContainer proxies GET /api/prezero/containers/{location_id}.
func (s *Server) handlePreZeroContainer(w http.ResponseWriter, r *http.Request) {
locationID := r.PathValue("location_id")
if locationID == "" {
writeError(w, http.StatusNotFound, "not_found", "container not found")
return
}
if s.prezero == nil {
writeError(w, http.StatusBadGateway, "ml_unavailable", "FastAPI PreZero client is not configured")
return
}
status, body, err := s.prezero.PreZeroContainer(r.Context(), locationID)
if err != nil {
slog.Warn("prezero container proxy failed", "location_id", locationID, "error", err)
writeError(w, http.StatusBadGateway, "ml_unavailable", "FastAPI is unavailable")
return
}
relayMLResponse(w, status, body)
}
+336
View File
@@ -0,0 +1,336 @@
package api
import (
"context"
"encoding/json"
"errors"
"io"
"net/http"
"net/http/httptest"
"sync/atomic"
"testing"
)
// stubPreZero implements MLClient (through the embedded stubML) and
// PreZeroClient, so New's optional type assertion picks it up.
type stubPreZero struct {
*stubML
calls atomic.Int32
summaryFn func(context.Context) (int, []byte, error)
priorityFn func(context.Context, string, int, int) (int, []byte, error)
containerFn func(context.Context, string) (int, []byte, error)
gotPriority string
gotLimit int
gotOffset int
gotLocation string
}
func newStubPreZero() *stubPreZero {
return &stubPreZero{stubML: &stubML{}}
}
func (s *stubPreZero) PreZeroSummary(ctx context.Context) (int, []byte, error) {
s.calls.Add(1)
if s.summaryFn == nil {
return 0, nil, errors.New("ml unavailable")
}
return s.summaryFn(ctx)
}
func (s *stubPreZero) PreZeroPriority(ctx context.Context, priority string, limit, offset int) (int, []byte, error) {
s.calls.Add(1)
s.gotPriority, s.gotLimit, s.gotOffset = priority, limit, offset
if s.priorityFn == nil {
return 0, nil, errors.New("ml unavailable")
}
return s.priorityFn(ctx, priority, limit, offset)
}
func (s *stubPreZero) PreZeroContainer(ctx context.Context, locationID string) (int, []byte, error) {
s.calls.Add(1)
s.gotLocation = locationID
if s.containerFn == nil {
return 0, nil, errors.New("ml unavailable")
}
return s.containerFn(ctx, locationID)
}
func newPreZeroServer(t *testing.T, client MLClient) *httptest.Server {
t.Helper()
_, ts := newTestServer(t, client, nil)
return ts
}
// getRaw is getJSON's byte-preserving sibling: the PreZero tests assert that
// the upstream body passes through unchanged.
func getRaw(t *testing.T, url string) (*http.Response, []byte) {
t.Helper()
resp, err := http.Get(url)
if err != nil {
t.Fatalf("GET %s: %v", url, err)
}
defer resp.Body.Close()
raw, err := io.ReadAll(resp.Body)
if err != nil {
t.Fatalf("read GET %s: %v", url, err)
}
return resp, raw
}
func TestPreZeroSummaryPassthrough(t *testing.T) {
const body = `{"meta":{"rows":11701,"containers":449},"summary":{"priority_counts":{"high":88,"medium":248,"low":113}}}`
stub := newStubPreZero()
stub.summaryFn = func(context.Context) (int, []byte, error) {
return http.StatusOK, []byte(body), nil
}
ts := newPreZeroServer(t, stub)
resp, raw := getRaw(t, ts.URL+"/api/prezero/summary")
if resp.StatusCode != http.StatusOK {
t.Fatalf("summary status=%d body=%s, want 200", resp.StatusCode, raw)
}
if got := resp.Header.Get("Content-Type"); got != "application/json; charset=utf-8" {
t.Errorf("summary Content-Type=%q, want JSON", got)
}
if string(raw) != body {
t.Fatalf("summary body=%s, want exact passthrough", raw)
}
var decoded struct {
Summary struct {
PriorityCounts map[string]int `json:"priority_counts"`
} `json:"summary"`
}
if err := json.Unmarshal(raw, &decoded); err != nil {
t.Fatalf("decode summary: %v", err)
}
if decoded.Summary.PriorityCounts["high"] != 88 ||
decoded.Summary.PriorityCounts["medium"] != 248 ||
decoded.Summary.PriorityCounts["low"] != 113 {
t.Fatalf("priority counts=%v", decoded.Summary.PriorityCounts)
}
if got := stub.calls.Load(); got != 1 {
t.Fatalf("client calls=%d, want 1", got)
}
}
func TestPreZeroPriorityForwardsQuery(t *testing.T) {
stub := newStubPreZero()
stub.priorityFn = func(context.Context, string, int, int) (int, []byte, error) {
return http.StatusOK, []byte(`{"total":88,"count":3,"offset":10,"limit":3,"containers":[{"location_id":"a"},{"location_id":"b"},{"location_id":"c"}]}`), nil
}
ts := newPreZeroServer(t, stub)
resp, raw := getRaw(t, ts.URL+"/api/prezero/priority?priority=high&limit=3&offset=10")
if resp.StatusCode != http.StatusOK {
t.Fatalf("priority status=%d body=%s, want 200", resp.StatusCode, raw)
}
if stub.gotPriority != "high" || stub.gotLimit != 3 || stub.gotOffset != 10 {
t.Fatalf("forwarded priority=%q limit=%d offset=%d, want high/3/10",
stub.gotPriority, stub.gotLimit, stub.gotOffset)
}
var body struct {
Total int `json:"total"`
Count int `json:"count"`
Containers []struct {
LocationID string `json:"location_id"`
} `json:"containers"`
}
if err := json.Unmarshal(raw, &body); err != nil {
t.Fatalf("decode priority: %v", err)
}
if body.Total != 88 || body.Count != 3 || len(body.Containers) != 3 {
t.Fatalf("priority body=%+v", body)
}
// Omitted query parameters use the contract defaults.
getRaw(t, ts.URL+"/api/prezero/priority")
if stub.gotPriority != "" || stub.gotLimit != 50 || stub.gotOffset != 0 {
t.Fatalf("defaults forwarded priority=%q limit=%d offset=%d, want empty/50/0",
stub.gotPriority, stub.gotLimit, stub.gotOffset)
}
}
func TestPreZeroPriorityValidationSkipsClient(t *testing.T) {
stub := newStubPreZero()
stub.priorityFn = func(context.Context, string, int, int) (int, []byte, error) {
return http.StatusOK, []byte(`{"containers":[]}`), nil
}
ts := newPreZeroServer(t, stub)
for _, query := range []string{
"priority=urgent",
"priority=HIGH",
"limit=0",
"limit=501",
"limit=-1",
"limit=abc",
"limit=1.5",
"offset=-1",
"offset=abc",
} {
resp, raw := getRaw(t, ts.URL+"/api/prezero/priority?"+query)
if resp.StatusCode != http.StatusBadRequest {
t.Errorf("%s: status=%d body=%s, want 400", query, resp.StatusCode, raw)
continue
}
var envelope struct {
Error struct {
Code string `json:"code"`
Message string `json:"message"`
} `json:"error"`
}
if err := json.Unmarshal(raw, &envelope); err != nil {
t.Errorf("%s: decode error envelope: %v", query, err)
continue
}
if envelope.Error.Code != "bad_request" || envelope.Error.Message == "" {
t.Errorf("%s: error envelope=%+v", query, envelope.Error)
}
}
if got := stub.calls.Load(); got != 0 {
t.Fatalf("client calls=%d for invalid queries, want 0", got)
}
}
func TestPreZeroContainerPassthrough(t *testing.T) {
const locationID = "eecbf6fa-decf-46da-b110-bf014e7c181d"
stub := newStubPreZero()
stub.containerFn = func(_ context.Context, locationID string) (int, []byte, error) {
if locationID == "eecbf6fa-decf-46da-b110-bf014e7c181d" {
return http.StatusOK, []byte(`{"container":{"location_id":"eecbf6fa-decf-46da-b110-bf014e7c181d","priority":"high"},"readings":[{"date":"2026-09-29"}]}`), nil
}
return http.StatusNotFound, []byte(`{"error":{"code":"not_found","message":"container not found"}}`), nil
}
ts := newPreZeroServer(t, stub)
resp, raw := getRaw(t, ts.URL+"/api/prezero/containers/"+locationID)
if resp.StatusCode != http.StatusOK {
t.Fatalf("container status=%d body=%s, want 200", resp.StatusCode, raw)
}
if stub.gotLocation != locationID {
t.Errorf("forwarded location=%q, want %q", stub.gotLocation, locationID)
}
var body struct {
Container struct {
LocationID string `json:"location_id"`
Priority string `json:"priority"`
} `json:"container"`
}
if err := json.Unmarshal(raw, &body); err != nil {
t.Fatalf("decode container: %v", err)
}
if body.Container.LocationID != locationID || body.Container.Priority != "high" {
t.Fatalf("container=%+v", body.Container)
}
resp, raw = getRaw(t, ts.URL+"/api/prezero/containers/unknown-id")
if resp.StatusCode != http.StatusNotFound {
t.Fatalf("unknown container status=%d body=%s, want 404", resp.StatusCode, raw)
}
if !json.Valid(raw) {
t.Fatalf("unknown container body is not JSON: %s", raw)
}
}
func TestPreZeroUnavailableReturns502(t *testing.T) {
failing := newStubPreZero()
failing.summaryFn = func(context.Context) (int, []byte, error) {
return 0, nil, errors.New("connection refused")
}
failing.priorityFn = func(context.Context, string, int, int) (int, []byte, error) {
return 0, nil, errors.New("connection refused")
}
failing.containerFn = func(context.Context, string) (int, []byte, error) {
return 0, nil, errors.New("connection refused")
}
ts := newPreZeroServer(t, failing)
for _, path := range []string{
"/api/prezero/summary",
"/api/prezero/priority?priority=high",
"/api/prezero/containers/abc",
} {
resp, raw := getRaw(t, ts.URL+path)
if resp.StatusCode != http.StatusBadGateway {
t.Errorf("%s: status=%d body=%s, want 502", path, resp.StatusCode, raw)
continue
}
var envelope struct {
Error struct {
Code string `json:"code"`
} `json:"error"`
}
if err := json.Unmarshal(raw, &envelope); err != nil || envelope.Error.Code != "ml_unavailable" {
t.Errorf("%s: error=%+v err=%v, want ml_unavailable", path, envelope.Error, err)
}
}
// Prediction-only stubs do not implement PreZeroClient; that is also 502.
unconfigured := newPreZeroServer(t, &stubML{})
for _, path := range []string{
"/api/prezero/summary",
"/api/prezero/priority",
"/api/prezero/containers/abc",
} {
resp, raw := getRaw(t, unconfigured.URL+path)
if resp.StatusCode != http.StatusBadGateway {
t.Errorf("unconfigured %s: status=%d body=%s, want 502", path, resp.StatusCode, raw)
}
}
}
func TestPreZeroRouting(t *testing.T) {
stub := newStubPreZero()
stub.summaryFn = func(context.Context) (int, []byte, error) {
return http.StatusOK, []byte(`{}`), nil
}
stub.priorityFn = func(context.Context, string, int, int) (int, []byte, error) {
return http.StatusOK, []byte(`{}`), nil
}
stub.containerFn = func(context.Context, string) (int, []byte, error) {
return http.StatusOK, []byte(`{}`), nil
}
ts := newPreZeroServer(t, stub)
for _, path := range []string{
"/api/prezero/summary",
"/api/prezero/priority",
"/api/prezero/containers/abc",
} {
req, err := http.NewRequest(http.MethodPost, ts.URL+path, nil)
if err != nil {
t.Fatal(err)
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatalf("POST %s: %v", path, err)
}
resp.Body.Close()
if resp.StatusCode != http.StatusMethodNotAllowed {
t.Errorf("POST %s status=%d, want 405", path, resp.StatusCode)
}
if allow := resp.Header.Get("Allow"); allow != "GET" {
t.Errorf("POST %s Allow=%q, want GET", path, allow)
}
}
for _, path := range []string{
"/api/prezero",
"/api/prezero/unknown",
"/api/prezero/containers/",
"/api/prezero/containers/a/b",
} {
resp, raw := getRaw(t, ts.URL+path)
if resp.StatusCode != http.StatusNotFound {
t.Errorf("GET %s status=%d body=%s, want 404", path, resp.StatusCode, raw)
}
if !json.Valid(raw) {
t.Errorf("GET %s body is not JSON: %s", path, raw)
}
}
if got := stub.calls.Load(); got != 0 {
t.Fatalf("client calls=%d for unroutable requests, want 0", got)
}
}
+42 -11
View File
@@ -34,11 +34,20 @@ type TrainClient interface {
TrainStatus(ctx context.Context, jobID string) (int, []byte, error) TrainStatus(ctx context.Context, jobID string) (int, []byte, error)
} }
// PreZeroClient is the optional FastAPI PreZero read-only surface. Like
// TrainClient it is separate so prediction-only stubs keep working.
type PreZeroClient interface {
PreZeroSummary(ctx context.Context) (int, []byte, error)
PreZeroPriority(ctx context.Context, priority string, limit, offset int) (int, []byte, error)
PreZeroContainer(ctx context.Context, locationID string) (int, []byte, error)
}
// Server holds process-wide state. One instance per pod. // Server holds process-wide state. One instance per pod.
type Server struct { type Server struct {
cfg config.Config cfg config.Config
cache *cache.Cache cache *cache.Cache
ml MLClient ml MLClient
prezero PreZeroClient
hub *sse.Hub hub *sse.Hub
scenario *scenario.State scenario *scenario.State
loc *time.Location loc *time.Location
@@ -61,10 +70,15 @@ func New(cfg config.Config, snapshots *cache.Cache, client MLClient, hub *sse.Hu
if cfg.MLTimeout <= 0 { if cfg.MLTimeout <= 0 {
cfg.MLTimeout = ml.DefaultTimeout cfg.MLTimeout = ml.DefaultTimeout
} }
var prezero PreZeroClient
if pc, ok := client.(PreZeroClient); ok {
prezero = pc
}
return &Server{ return &Server{
cfg: cfg, cfg: cfg,
cache: snapshots, cache: snapshots,
ml: client, ml: client,
prezero: prezero,
hub: hub, hub: hub,
scenario: scenario.New(), scenario: scenario.New(),
loc: loc, loc: loc,
@@ -84,28 +98,35 @@ func (s *Server) Handler() http.Handler {
mux.HandleFunc("GET /api/series", s.handleSeries) mux.HandleFunc("GET /api/series", s.handleSeries)
mux.HandleFunc("GET /api/context", s.handleContext) mux.HandleFunc("GET /api/context", s.handleContext)
mux.HandleFunc("GET /api/forecast", s.handleForecast) mux.HandleFunc("GET /api/forecast", s.handleForecast)
mux.HandleFunc("GET /api/playground/forecast", s.handlePlaygroundForecast)
mux.HandleFunc("GET /api/staffing", s.handleStaffing) mux.HandleFunc("GET /api/staffing", s.handleStaffing)
mux.HandleFunc("GET /api/scenario", s.handleScenarioGet) mux.HandleFunc("GET /api/scenario", s.handleScenarioGet)
mux.HandleFunc("POST /api/scenario", s.requireControlAuth(s.handleScenarioPost)) mux.HandleFunc("POST /api/scenario", s.requireControlAuth(s.handleScenarioPost))
mux.HandleFunc("POST /api/train", s.requireControlAuth(s.handleTrain)) mux.HandleFunc("POST /api/train", s.requireControlAuth(s.handleTrain))
mux.HandleFunc("GET /api/train/{job_id}", s.requireControlAuth(s.handleTrainStatus)) mux.HandleFunc("GET /api/train/{job_id}", s.requireControlAuth(s.handleTrainStatus))
mux.HandleFunc("GET /api/prezero/summary", s.handlePreZeroSummary)
mux.HandleFunc("GET /api/prezero/priority", s.handlePreZeroPriority)
mux.HandleFunc("GET /api/prezero/containers/{location_id}", s.handlePreZeroContainer)
mux.HandleFunc("GET /api/stream", s.handleStream) mux.HandleFunc("GET /api/stream", s.handleStream)
return s.recoverer(s.withCORS(s.routeCheck(mux))) return s.recoverer(s.withCORS(s.routeCheck(mux)))
} }
var methodTable = map[string][]string{ var methodTable = map[string][]string{
"/api/healthz": {"GET"}, "/api/healthz": {"GET"},
"/api/readyz": {"GET"}, "/api/readyz": {"GET"},
"/api/meta": {"GET"}, "/api/meta": {"GET"},
"/api/sensors": {"GET"}, "/api/sensors": {"GET"},
"/api/series": {"GET"}, "/api/series": {"GET"},
"/api/context": {"GET"}, "/api/context": {"GET"},
"/api/forecast": {"GET"}, "/api/forecast": {"GET"},
"/api/staffing": {"GET"}, "/api/playground/forecast": {"GET"},
"/api/scenario": {"GET", "POST"}, "/api/staffing": {"GET"},
"/api/train": {"POST"}, "/api/scenario": {"GET", "POST"},
"/api/stream": {"GET"}, "/api/train": {"POST"},
"/api/prezero/summary": {"GET"},
"/api/prezero/priority": {"GET"},
"/api/stream": {"GET"},
} }
// routeCheck keeps unknown routes and methods in the JSON error envelope; // routeCheck keeps unknown routes and methods in the JSON error envelope;
@@ -116,6 +137,9 @@ func (s *Server) routeCheck(next http.Handler) http.Handler {
if !ok && isTrainJobPath(r.URL.Path) { if !ok && isTrainJobPath(r.URL.Path) {
methods, ok = []string{"GET"}, true methods, ok = []string{"GET"}, true
} }
if !ok && isPreZeroContainerPath(r.URL.Path) {
methods, ok = []string{"GET"}, true
}
if !ok { if !ok {
writeError(w, http.StatusNotFound, "not_found", "route not found") writeError(w, http.StatusNotFound, "not_found", "route not found")
return return
@@ -135,6 +159,13 @@ func isTrainJobPath(path string) bool {
return found && jobID != "" && !strings.Contains(jobID, "/") return found && jobID != "" && !strings.Contains(jobID, "/")
} }
// isPreZeroContainerPath matches exactly one location id after
// /api/prezero/containers/.
func isPreZeroContainerPath(path string) bool {
locationID, found := strings.CutPrefix(path, "/api/prezero/containers/")
return found && locationID != "" && !strings.Contains(locationID, "/")
}
func joinMethods(methods []string) string { func joinMethods(methods []string) string {
out := "" out := ""
for i, method := range methods { for i, method := range methods {
+67
View File
@@ -11,6 +11,7 @@ import (
"io" "io"
"net/http" "net/http"
"net/url" "net/url"
"strconv"
"strings" "strings"
"time" "time"
@@ -106,6 +107,36 @@ type WeatherInput struct {
PrecipMM float64 `json:"precip_mm"` PrecipMM float64 `json:"precip_mm"`
} }
// PlaygroundWeather is the optional absolute weather override for the
// playground. Pointers distinguish "not supplied" from a real zero value.
type PlaygroundWeather struct {
TempC *float64 `json:"temp_c,omitempty"`
PrecipMM *float64 `json:"precip_mm,omitempty"`
}
// PlaygroundRequest is the public playground's prediction request. Weather is
// omitted entirely when the caller did not override it, so Python uses its
// baked hourly weather forecast.
type PlaygroundRequest struct {
Sensor string `json:"sensor"`
Horizon string `json:"horizon"`
Scenario string `json:"scenario"`
Weather *PlaygroundWeather `json:"weather,omitempty"`
IsHoliday *bool `json:"is_holiday,omitempty"`
}
// PlaygroundResponse mirrors the subset of FastAPI POST /predict that the
// playground returns to the browser.
type PlaygroundResponse struct {
Sensor string `json:"sensor"`
Horizon string `json:"horizon"`
Scenario string `json:"scenario"`
Points []model.ForecastPoint `json:"points"`
DataVersion string `json:"data_version"`
ModelVersion string `json:"model_version"`
ContextVersion string `json:"context_version"`
}
// SimulateRequest mirrors the API contract POST /simulate. // SimulateRequest mirrors the API contract POST /simulate.
type SimulateRequest struct { type SimulateRequest struct {
Scenario string `json:"scenario"` Scenario string `json:"scenario"`
@@ -147,6 +178,20 @@ func (c *Client) Predict(ctx context.Context, req PredictRequest) ([]model.Forec
return nil, fmt.Errorf("ml: predict returned no points") return nil, fmt.Errorf("ml: predict returned no points")
} }
// PlaygroundPredict calls POST /predict with optional weather and holiday
// overrides. Unlike Predict it preserves the response versions for the public
// playground.
func (c *Client) PlaygroundPredict(ctx context.Context, req PlaygroundRequest) (PlaygroundResponse, error) {
var out PlaygroundResponse
if err := c.post(ctx, "/predict", req, &out); err != nil {
return out, err
}
if len(out.Points) == 0 {
return out, fmt.Errorf("ml: playground predict returned no points")
}
return out, nil
}
// Simulate calls POST /simulate and returns forecasts keyed // Simulate calls POST /simulate and returns forecasts keyed
// sensor -> horizon -> points. // sensor -> horizon -> points.
func (c *Client) Simulate(ctx context.Context, req SimulateRequest) (map[string]map[string][]model.ForecastPoint, error) { func (c *Client) Simulate(ctx context.Context, req SimulateRequest) (map[string]map[string][]model.ForecastPoint, error) {
@@ -176,6 +221,28 @@ func (c *Client) TrainStatus(ctx context.Context, jobID string) (int, []byte, er
return c.controlRequest(ctx, http.MethodGet, "/train/"+url.PathEscape(jobID), "", nil) return c.controlRequest(ctx, http.MethodGet, "/train/"+url.PathEscape(jobID), "", nil)
} }
// PreZeroSummary proxies GET /prezero/summary.
func (c *Client) PreZeroSummary(ctx context.Context) (int, []byte, error) {
return c.controlRequest(ctx, http.MethodGet, "/prezero/summary", "", nil)
}
// PreZeroPriority proxies GET /prezero/priority. priority may be empty to
// return every tier; limit and offset are always forwarded.
func (c *Client) PreZeroPriority(ctx context.Context, priority string, limit, offset int) (int, []byte, error) {
query := url.Values{}
if priority != "" {
query.Set("priority", priority)
}
query.Set("limit", strconv.Itoa(limit))
query.Set("offset", strconv.Itoa(offset))
return c.controlRequest(ctx, http.MethodGet, "/prezero/priority?"+query.Encode(), "", nil)
}
// PreZeroContainer proxies GET /prezero/containers/{location_id}.
func (c *Client) PreZeroContainer(ctx context.Context, locationID string) (int, []byte, error) {
return c.controlRequest(ctx, http.MethodGet, "/prezero/containers/"+url.PathEscape(locationID), "", nil)
}
// controlRequest performs a training/control request and returns the raw // controlRequest performs a training/control request and returns the raw
// upstream status and body. Non-2xx responses are not errors: the proxy // upstream status and body. Non-2xx responses are not errors: the proxy
// forwards them so clients see FastAPI's 400/404/409 semantics. // forwards them so clients see FastAPI's 400/404/409 semantics.
+134
View File
@@ -93,6 +93,72 @@ func TestPredictTimeout(t *testing.T) {
} }
} }
func TestPlaygroundPredictOptionalWeatherAndHoliday(t *testing.T) {
var bodies []map[string]any
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/predict" {
t.Errorf("path=%q", r.URL.Path)
}
var body map[string]any
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
t.Errorf("decode request: %v", err)
}
bodies = append(bodies, body)
_, _ = w.Write([]byte(`{
"sensor":"hn-bahnhof-01",
"horizon":"48h",
"scenario":"base",
"points":[{"t":"2026-11-16T09:00:00Z","v":12.3,"lo":8.1,"hi":17.2}],
"data_version":"d1",
"model_version":"m1",
"context_version":"c1"
}`))
}))
defer srv.Close()
client := New(srv.URL, time.Second)
if _, err := client.PlaygroundPredict(context.Background(), PlaygroundRequest{
Sensor: "hn-bahnhof-01", Horizon: "48h", Scenario: "base",
}); err != nil {
t.Fatalf("PlaygroundPredict without weather: %v", err)
}
if len(bodies) != 1 {
t.Fatalf("requests=%d", len(bodies))
}
if _, ok := bodies[0]["weather"]; ok {
t.Errorf("weather should be omitted when not supplied: %+v", bodies[0])
}
if _, ok := bodies[0]["is_holiday"]; ok {
t.Errorf("is_holiday should be omitted when not supplied: %+v", bodies[0])
}
temp := 29.0
holiday := true
resp, err := client.PlaygroundPredict(context.Background(), PlaygroundRequest{
Sensor: "hn-bahnhof-01", Horizon: "48h", Scenario: "base",
Weather: &PlaygroundWeather{TempC: &temp}, IsHoliday: &holiday,
})
if err != nil {
t.Fatalf("PlaygroundPredict with weather: %v", err)
}
if resp.ModelVersion != "m1" || resp.DataVersion != "d1" || len(resp.Points) != 1 {
t.Fatalf("response=%+v", resp)
}
if len(bodies) != 2 {
t.Fatalf("requests=%d", len(bodies))
}
weather, ok := bodies[1]["weather"].(map[string]any)
if !ok || weather["temp_c"] != float64(29) {
t.Errorf("weather=%+v", bodies[1]["weather"])
}
if _, ok := weather["precip_mm"]; ok {
t.Errorf("precip_mm should be omitted: %+v", weather)
}
if bodies[1]["is_holiday"] != true {
t.Errorf("is_holiday=%+v", bodies[1]["is_holiday"])
}
}
func TestSimulate(t *testing.T) { func TestSimulate(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var req SimulateRequest var req SimulateRequest
@@ -305,3 +371,71 @@ func TestTrainStatusForwardsJobIDAndUpstreamError(t *testing.T) {
t.Fatalf("status=%d body=%s, want forwarded 404", status, body) t.Fatalf("status=%d body=%s, want forwarded 404", status, body)
} }
} }
func TestPreZeroClientsForwardRouteQueryAndStatus(t *testing.T) {
var gotPaths, gotQueries []string
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
t.Errorf("method=%s, want GET", r.Method)
}
gotPaths = append(gotPaths, r.URL.Path)
gotQueries = append(gotQueries, r.URL.RawQuery)
switch {
case r.URL.Path == "/prezero/summary":
_, _ = w.Write([]byte(`{"summary":{"priority_counts":{"high":88}}}`))
case r.URL.Path == "/prezero/priority":
_, _ = w.Write([]byte(`{"total":88,"count":1,"containers":[]}`))
case r.URL.Path == "/prezero/containers/known-id":
_, _ = w.Write([]byte(`{"container":{"location_id":"known-id"}}`))
default:
w.WriteHeader(http.StatusNotFound)
_, _ = w.Write([]byte(`{"error":{"code":"not_found","message":"container not found"}}`))
}
}))
defer srv.Close()
client := New(srv.URL, time.Second)
status, body, err := client.PreZeroSummary(context.Background())
if err != nil || status != http.StatusOK || !strings.Contains(string(body), `"high":88`) {
t.Fatalf("summary status=%d body=%s err=%v", status, body, err)
}
status, body, err = client.PreZeroPriority(context.Background(), "high", 3, 10)
if err != nil || status != http.StatusOK || !strings.Contains(string(body), `"total":88`) {
t.Fatalf("priority status=%d body=%s err=%v", status, body, err)
}
if _, _, err := client.PreZeroPriority(context.Background(), "", 50, 0); err != nil {
t.Fatalf("priority defaults: %v", err)
}
status, body, err = client.PreZeroContainer(context.Background(), "known-id")
if err != nil || status != http.StatusOK || !strings.Contains(string(body), "known-id") {
t.Fatalf("container status=%d body=%s err=%v", status, body, err)
}
status, body, err = client.PreZeroContainer(context.Background(), "missing")
if err != nil {
t.Fatalf("container missing: %v", err)
}
if status != http.StatusNotFound || !strings.Contains(string(body), "container not found") {
t.Fatalf("container missing status=%d body=%s, want forwarded 404", status, body)
}
wantPaths := []string{
"/prezero/summary",
"/prezero/priority",
"/prezero/priority",
"/prezero/containers/known-id",
"/prezero/containers/missing",
}
for i, want := range wantPaths {
if gotPaths[i] != want {
t.Errorf("request %d path=%q, want %q", i, gotPaths[i], want)
}
}
wantQueries := []string{"", "limit=3&offset=10&priority=high", "limit=50&offset=0", "", ""}
for i, want := range wantQueries {
if gotQueries[i] != want {
t.Errorf("request %d query=%q, want %q", i, gotQueries[i], want)
}
}
}