Files
api-go/internal/api/handlers_playground.go
T
2026-11-14 20:49:39 +01:00

171 lines
5.0 KiB
Go

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
}