Merge pull request 'feat: api bootstrap' (#1) from feat/api-bootstrap into main

Reviewed-on: #1
This commit was merged in pull request #1.
This commit is contained in:
Noel committed 2026-11-14 04:06:09 +00:00
commit 11f670c13c
30 files changed
+3832

No files matched your search

+4
View File
@@ -0,0 +1,4 @@
.git
.gitignore
*.md
opencode.json
+29
View File
@@ -0,0 +1,29 @@
# syntax=docker/dockerfile:1
FROM golang:1.27-alpine AS build
WORKDIR /src
# Dependencies are only the standard library today; the explicit copy keeps
# the module cache layer stable when that changes.
COPY go.mod ./
RUN go mod download
COPY . .
RUN CGO_ENABLED=0 GOOS=linux go build \
-trimpath -ldflags="-s -w" \
-o /out/api ./cmd/api
FROM gcr.io/distroless/static-debian12:nonroot
WORKDIR /app
COPY --from=build /out/api /app/api
# Baked fallback data lives in the image; there is no runtime data fetch.
COPY --from=build /src/testdata/data /app/data
ENV DATA_DIR=/app/data \
PORT=8080
EXPOSE 8080
USER nonroot:nonroot
ENTRYPOINT ["/app/api"]
+66
View File
@@ -0,0 +1,66 @@
// Command api serves the PulseCast Go API, SSE stream and cached fallback.
package main
import (
"context"
"errors"
"log/slog"
"net/http"
"os"
"os/signal"
"syscall"
"time"
"pulsecast/api/internal/api"
"pulsecast/api/internal/config"
"pulsecast/api/internal/ml"
"pulsecast/api/internal/sse"
"pulsecast/api/internal/store"
)
func main() {
cfg := config.Load()
// A partial dataset is not fatal: the process starts and /api/readyz reports
// 503 until the baked artifacts are complete, instead of crash-looping.
st, err := store.Load(cfg.DataDir)
if err != nil {
slog.Error("baked data is incomplete", "dir", cfg.DataDir, "error", err)
}
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
hub := sse.NewHub(cfg.Heartbeat)
go hub.Run(ctx)
server := &http.Server{
Addr: cfg.Addr,
Handler: api.New(cfg, st, ml.NewWithToken(cfg.FastAPIURL, cfg.MLTimeout, cfg.ControlToken), hub).Handler(),
ReadHeaderTimeout: 5 * time.Second,
IdleTimeout: 120 * time.Second,
}
serveErr := make(chan error, 1)
go func() {
slog.Info("api listening", "addr", cfg.Addr, "data_dir", cfg.DataDir, "fastapi", cfg.FastAPIURL)
serveErr <- server.ListenAndServe()
}()
select {
case <-ctx.Done():
slog.Info("shutting down")
case err := <-serveErr:
if !errors.Is(err, http.ErrServerClosed) {
slog.Error("server stopped", "error", err)
os.Exit(1)
}
return
}
shutdownCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
if err := server.Shutdown(shutdownCtx); err != nil {
slog.Error("graceful shutdown failed", "error", err)
}
}
+3
View File
@@ -0,0 +1,3 @@
module pulsecast/api
go 1.27.0
+631
View File
@@ -0,0 +1,631 @@
package api
import (
"bufio"
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"pulsecast/api/internal/config"
"pulsecast/api/internal/ml"
"pulsecast/api/internal/model"
"pulsecast/api/internal/sse"
"pulsecast/api/internal/store"
)
const fixtureDir = "../../testdata/data"
type stubML struct {
predict func(context.Context, ml.PredictRequest) ([]model.ForecastPoint, error)
simulate func(context.Context, ml.SimulateRequest) (map[string]map[string][]model.ForecastPoint, error)
train func(context.Context, string, io.Reader) (int, []byte, error)
trainStatus func(context.Context, string) (int, []byte, error)
}
func (s *stubML) Predict(ctx context.Context, req ml.PredictRequest) ([]model.ForecastPoint, error) {
if s.predict == nil {
return nil, errors.New("ml unavailable")
}
return s.predict(ctx, req)
}
func (s *stubML) Simulate(ctx context.Context, req ml.SimulateRequest) (map[string]map[string][]model.ForecastPoint, error) {
if s.simulate == nil {
return nil, errors.New("ml unavailable")
}
return s.simulate(ctx, req)
}
func (s *stubML) Train(ctx context.Context, contentType string, body io.Reader) (int, []byte, error) {
if s.train == nil {
return 0, nil, errors.New("ml unavailable")
}
return s.train(ctx, contentType, body)
}
func (s *stubML) TrainStatus(ctx context.Context, jobID string) (int, []byte, error) {
if s.trainStatus == nil {
return 0, nil, errors.New("ml unavailable")
}
return s.trainStatus(ctx, jobID)
}
func loadFixtureStore(t *testing.T) *store.Store {
t.Helper()
st, err := store.Load(fixtureDir)
if err != nil {
t.Fatalf("load fixtures: %v", err)
}
return st
}
func newTestServer(t *testing.T, client MLClient, mutate func(*config.Config)) (*Server, *httptest.Server) {
t.Helper()
cfg := config.Config{
Addr: ":0",
DataDir: fixtureDir,
FastAPIURL: "http://127.0.0.1:1",
Heartbeat: time.Hour,
MLTimeout: 100 * time.Millisecond,
}
if mutate != nil {
mutate(&cfg)
}
hub := sse.NewHub(cfg.Heartbeat)
ctx, cancel := context.WithCancel(context.Background())
t.Cleanup(cancel)
go hub.Run(ctx)
srv := New(cfg, loadFixtureStore(t), client, hub)
ts := httptest.NewServer(srv.Handler())
t.Cleanup(ts.Close)
return srv, ts
}
func getJSON(t *testing.T, url string, dst any) *http.Response {
t.Helper()
resp, err := http.Get(url)
if err != nil {
t.Fatalf("GET %s: %v", url, err)
}
defer resp.Body.Close()
if dst != nil {
if err := json.NewDecoder(resp.Body).Decode(dst); err != nil {
t.Fatalf("decode GET %s: %v", url, err)
}
}
return resp
}
func TestHealthAndReady(t *testing.T) {
_, ts := newTestServer(t, &stubML{}, nil)
var health map[string]bool
resp := getJSON(t, ts.URL+"/api/healthz", &health)
if resp.StatusCode != http.StatusOK || !health["ok"] {
t.Fatalf("healthz: status=%d body=%v", resp.StatusCode, health)
}
var ready map[string]bool
resp = getJSON(t, ts.URL+"/api/readyz", &ready)
if resp.StatusCode != http.StatusOK {
t.Fatalf("readyz status=%d body=%v", resp.StatusCode, ready)
}
if !ready["ok"] || !ready["data"] || !ready["model"] {
t.Fatalf("readyz body=%v", ready)
}
}
func TestReadyzWithoutData(t *testing.T) {
cfg := config.Config{Addr: ":0", DataDir: t.TempDir(), FastAPIURL: "http://127.0.0.1:1", Heartbeat: time.Hour, MLTimeout: 50 * time.Millisecond}
st, err := store.Load(cfg.DataDir)
if err != nil {
t.Logf("expected load error: %v", err)
}
srv := New(cfg, st, &stubML{}, sse.NewHub(time.Hour))
ts := httptest.NewServer(srv.Handler())
defer ts.Close()
var ready map[string]bool
resp := getJSON(t, ts.URL+"/api/readyz", &ready)
if resp.StatusCode != http.StatusServiceUnavailable {
t.Fatalf("readyz status=%d, want 503", resp.StatusCode)
}
if ready["ok"] || ready["data"] || ready["model"] {
t.Fatalf("readyz body=%v, want all false", ready)
}
}
func TestMetaSensorsAndVersionHeaders(t *testing.T) {
_, ts := newTestServer(t, &stubML{}, nil)
var meta model.Meta
resp := getJSON(t, ts.URL+"/api/meta", &meta)
if resp.StatusCode != http.StatusOK {
t.Fatalf("meta status=%d", resp.StatusCode)
}
if meta.Coverage.Sensors != 8 || meta.ModelVersion == "" || meta.ContextVersion == "" {
t.Fatalf("meta=%+v", meta)
}
for _, header := range []string{"X-Data-Version", "X-Model-Version", "X-Context-Version"} {
if resp.Header.Get(header) == "" {
t.Errorf("missing %s header", header)
}
}
var sensors []model.Sensor
resp = getJSON(t, ts.URL+"/api/sensors", &sensors)
if resp.StatusCode != http.StatusOK {
t.Fatalf("sensors status=%d", resp.StatusCode)
}
if len(sensors) != 8 {
t.Fatalf("got %d sensors, want 8", len(sensors))
}
for i := 1; i < len(sensors); i++ {
if sensors[i-1].ID >= sensors[i].ID {
t.Fatalf("sensors not sorted by id: %q then %q", sensors[i-1].ID, sensors[i].ID)
}
}
if sensors[0].ID != "hn-bahnhof-01" || sensors[0].Battery == nil {
t.Fatalf("unexpected first sensor: %+v", sensors[0])
}
}
func TestSeriesRangeStepAndErrors(t *testing.T) {
_, ts := newTestServer(t, &stubML{}, nil)
var body struct {
Sensor string `json:"sensor"`
Step string `json:"step"`
Points []model.Point `json:"points"`
}
resp := getJSON(t, ts.URL+"/api/series?sensor=hn-bahnhof-01&from=2026-11-01T00:00:00Z&to=2026-11-01T23:59:59Z&step=15m", &body)
if resp.StatusCode != http.StatusOK {
t.Fatalf("series 15m status=%d", resp.StatusCode)
}
if body.Step != "15m" || len(body.Points) != 96 {
t.Fatalf("series 15m step=%q points=%d, want 96", body.Step, len(body.Points))
}
body.Points = nil
resp = getJSON(t, ts.URL+"/api/series?sensor=hn-bahnhof-01&from=2026-11-01T00:00:00Z&to=2026-11-01T23:59:59Z&step=1h", &body)
if resp.StatusCode != http.StatusOK || len(body.Points) != 24 {
t.Fatalf("series 1h status=%d points=%d, want 24", resp.StatusCode, len(body.Points))
}
cases := []struct {
path string
status int
}{
{"/api/series?sensor=does-not-exist", http.StatusNotFound},
{"/api/series?sensor=hn-bahnhof-01&step=5m", http.StatusBadRequest},
{"/api/series", http.StatusBadRequest},
{"/api/series?sensor=hn-bahnhof-01&from=not-a-time", http.StatusBadRequest},
{"/api/series?sensor=hn-bahnhof-01&from=2026-11-02T00:00:00Z&to=2026-11-01T00:00:00Z", http.StatusBadRequest},
}
for _, tc := range cases {
var errBody model.ErrorBody
resp := getJSON(t, ts.URL+tc.path, &errBody)
if resp.StatusCode != tc.status {
t.Errorf("%s: status=%d, want %d", tc.path, resp.StatusCode, tc.status)
}
if errBody.Error.Code == "" {
t.Errorf("%s: missing error envelope: %+v", tc.path, errBody)
}
}
}
func TestContextEndpoint(t *testing.T) {
_, ts := newTestServer(t, &stubML{}, nil)
var ctx model.ContextResponse
resp := getJSON(t, ts.URL+"/api/context", &ctx)
if resp.StatusCode != http.StatusOK {
t.Fatalf("context status=%d", resp.StatusCode)
}
if len(ctx.Weather.Forecast) != 168 {
t.Errorf("weather forecast points=%d, want 168", len(ctx.Weather.Forecast))
}
if len(ctx.Holidays) == 0 {
t.Error("expected holidays")
}
if ctx.UpdatedAt.IsZero() {
t.Error("expected updated_at")
}
}
func TestForecastFallsBackWhenMLIsDown(t *testing.T) {
_, ts := newTestServer(t, &stubML{}, nil)
var forecast model.ForecastResponse
resp := getJSON(t, ts.URL+"/api/forecast?sensor=hn-bahnhof-01&horizon=7d", &forecast)
if resp.StatusCode != http.StatusOK {
t.Fatalf("forecast status=%d", resp.StatusCode)
}
if !forecast.Cached {
t.Error("cached=false, want true when FastAPI is down")
}
if len(forecast.Points) != 168 {
t.Fatalf("points=%d, want 168", len(forecast.Points))
}
if forecast.Scenario != "base" || forecast.DataVersion == "" || forecast.ModelVersion == "" {
t.Fatalf("forecast=%+v", forecast)
}
}
func TestForecastTimeoutFallsBack(t *testing.T) {
client := &stubML{predict: func(ctx context.Context, _ ml.PredictRequest) ([]model.ForecastPoint, error) {
<-ctx.Done()
return nil, ctx.Err()
}}
_, ts := newTestServer(t, client, func(cfg *config.Config) { cfg.MLTimeout = 20 * time.Millisecond })
start := time.Now()
var forecast model.ForecastResponse
resp := getJSON(t, ts.URL+"/api/forecast?sensor=hn-stadtgalerie-01&horizon=48h&scenario=sunny-saturday-market", &forecast)
if resp.StatusCode != http.StatusOK {
t.Fatalf("forecast status=%d", resp.StatusCode)
}
if !forecast.Cached || len(forecast.Points) != 48 {
t.Fatalf("cached=%v points=%d, want cached 48 points", forecast.Cached, len(forecast.Points))
}
if elapsed := time.Since(start); elapsed > 2*time.Second {
t.Fatalf("fallback took %s, want <2s", elapsed)
}
}
func TestForecastLivePath(t *testing.T) {
point := model.ForecastPoint{T: time.Date(2026, 11, 16, 9, 0, 0, 0, time.UTC), V: 42, Lo: 40, Hi: 44}
var gotReq ml.PredictRequest
client := &stubML{predict: func(_ context.Context, req ml.PredictRequest) ([]model.ForecastPoint, error) {
gotReq = req
return []model.ForecastPoint{point}, nil
}}
_, ts := newTestServer(t, client, nil)
var forecast model.ForecastResponse
resp := getJSON(t, ts.URL+"/api/forecast?sensor=hn-bahnhof-01&horizon=1h&scenario=rainy-saturday", &forecast)
if resp.StatusCode != http.StatusOK {
t.Fatalf("forecast status=%d", resp.StatusCode)
}
if forecast.Cached {
t.Error("cached=true, want false for a live prediction")
}
if len(forecast.Points) != 1 || forecast.Points[0].V != 42 {
t.Fatalf("points=%+v", forecast.Points)
}
if gotReq.Sensor != "hn-bahnhof-01" || gotReq.Horizon != "1h" || gotReq.Scenario != "rainy-saturday" {
t.Fatalf("predict request=%+v", gotReq)
}
}
func TestForecastValidation(t *testing.T) {
_, ts := newTestServer(t, &stubML{}, nil)
for _, tc := range []struct {
path string
status int
}{
{"/api/forecast", http.StatusBadRequest},
{"/api/forecast?sensor=nope", http.StatusNotFound},
{"/api/forecast?sensor=hn-bahnhof-01&horizon=2h", http.StatusBadRequest},
{"/api/forecast?sensor=hn-bahnhof-01&scenario=party", http.StatusBadRequest},
} {
resp := getJSON(t, ts.URL+tc.path, nil)
if resp.StatusCode != tc.status {
t.Errorf("%s: status=%d, want %d", tc.path, resp.StatusCode, tc.status)
}
}
}
func TestStaffingPlan(t *testing.T) {
_, ts := newTestServer(t, &stubML{}, nil)
start := time.Now()
var plan model.StaffingResponse
resp := getJSON(t, ts.URL+"/api/staffing?sensor=hn-bahnhof-01&scenario=base&standard=standard", &plan)
if resp.StatusCode != http.StatusOK {
t.Fatalf("staffing status=%d", resp.StatusCode)
}
if elapsed := time.Since(start); elapsed > 2*time.Second {
t.Errorf("plan took %s, want <2s", elapsed)
}
if plan.Assumptions.VisitorsPerStaffHour != 25 || plan.Assumptions.ShiftLengthH != 4 {
t.Fatalf("assumptions=%+v", plan.Assumptions)
}
if len(plan.Hours) != 70 {
t.Errorf("hours=%d, want 70 (7 days x 10 store hours)", len(plan.Hours))
}
if len(plan.Shifts) != 21 {
t.Errorf("shifts=%d, want 21 (3 blocks x 7 days)", len(plan.Shifts))
}
if plan.Summary.CoveragePct != 100 {
t.Errorf("coverage=%v, want 100", plan.Summary.CoveragePct)
}
if plan.Summary.CostEUR <= 0 || plan.Summary.FlatScheduleCostEUR <= 0 {
t.Errorf("summary=%+v", plan.Summary)
}
if len(plan.Why) == 0 {
t.Error("expected a non-empty why list")
}
for _, hour := range plan.Hours {
if hour.Coverage != "ok" && hour.Coverage != "over" && hour.Coverage != "under" {
t.Fatalf("invalid coverage label %q", hour.Coverage)
}
}
}
func TestStaffingValidation(t *testing.T) {
_, ts := newTestServer(t, &stubML{}, nil)
for _, tc := range []struct {
path string
status int
}{
{"/api/staffing", http.StatusBadRequest},
{"/api/staffing?sensor=nope", http.StatusNotFound},
{"/api/staffing?sensor=hn-bahnhof-01&standard=luxury", http.StatusBadRequest},
{"/api/staffing?sensor=hn-bahnhof-01&scenario=party", http.StatusBadRequest},
} {
resp := getJSON(t, ts.URL+tc.path, nil)
if resp.StatusCode != tc.status {
t.Errorf("%s: status=%d, want %d", tc.path, resp.StatusCode, tc.status)
}
}
}
func TestScenarioAuthAndValidation(t *testing.T) {
client := &stubML{}
_, ts := newTestServer(t, client, func(cfg *config.Config) {
cfg.ControlUser = "control"
cfg.ControlPass = "secret"
})
post := func(body string, user, pass string) *http.Response {
req, err := http.NewRequest(http.MethodPost, ts.URL+"/api/scenario", strings.NewReader(body))
if err != nil {
t.Fatal(err)
}
req.Header.Set("Content-Type", "application/json")
if user != "" {
req.SetBasicAuth(user, pass)
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatal(err)
}
resp.Body.Close()
return resp
}
valid := `{"scenario":"sunny-saturday-market","weather":{"temp_delta_c":4,"precip_mm":0},"event":{"type":"market","uplift":0.2}}`
if resp := post(valid, "", ""); resp.StatusCode != http.StatusUnauthorized {
t.Fatalf("no auth status=%d, want 401", resp.StatusCode)
} else if resp.Header.Get("WWW-Authenticate") == "" {
t.Error("missing WWW-Authenticate header")
}
if resp := post(valid, "control", "wrong"); resp.StatusCode != http.StatusUnauthorized {
t.Fatalf("bad password status=%d, want 401", resp.StatusCode)
}
if resp := post(`{"scenario":"nope"}`, "control", "secret"); resp.StatusCode != http.StatusBadRequest {
t.Fatalf("bad enum status=%d, want 400", resp.StatusCode)
}
if resp := post(`{"scenario":"base","weather":{"precip_mm":-1}}`, "control", "secret"); resp.StatusCode != http.StatusBadRequest {
t.Fatalf("negative precip status=%d, want 400", resp.StatusCode)
}
if resp := post(`{`, "control", "secret"); resp.StatusCode != http.StatusBadRequest {
t.Fatalf("malformed JSON status=%d, want 400", resp.StatusCode)
}
resp := post(valid, "control", "secret")
if resp.StatusCode != http.StatusOK {
t.Fatalf("valid POST status=%d, want 200", resp.StatusCode)
}
var state model.ScenarioState
getJSON(t, ts.URL+"/api/scenario", &state)
if state.Version != 2 || state.Scenario.Scenario != "sunny-saturday-market" {
t.Fatalf("scenario state=%+v", state)
}
if state.Scenario.Weather.TempDeltaC != 4 || state.Scenario.Event.Uplift != 0.2 {
t.Fatalf("scenario overrides lost: %+v", state.Scenario)
}
}
func TestScenarioAuthUnconfigured(t *testing.T) {
_, ts := newTestServer(t, &stubML{}, nil)
resp, err := http.Post(ts.URL+"/api/scenario", "application/json", strings.NewReader(`{"scenario":"base"}`))
if err != nil {
t.Fatal(err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusServiceUnavailable {
t.Fatalf("status=%d, want 503 when control auth is unset", resp.StatusCode)
}
}
func TestScenarioBroadcastOverSSE(t *testing.T) {
_, ts := newTestServer(t, &stubML{}, func(cfg *config.Config) {
cfg.ControlUser = "control"
cfg.ControlPass = "secret"
cfg.Heartbeat = 20 * time.Millisecond
})
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
req, err := http.NewRequestWithContext(ctx, http.MethodGet, ts.URL+"/api/stream", nil)
if err != nil {
t.Fatal(err)
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatal(err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
t.Fatalf("stream status=%d", resp.StatusCode)
}
if got := resp.Header.Get("Content-Type"); !strings.HasPrefix(got, "text/event-stream") {
t.Fatalf("Content-Type=%q", got)
}
if resp.Header.Get("X-Accel-Buffering") != "no" {
t.Errorf("X-Accel-Buffering=%q", resp.Header.Get("X-Accel-Buffering"))
}
reader := bufio.NewReader(resp.Body)
event := readEvent(t, reader)
if event.name != "scenario" || event.id != "1" {
t.Fatalf("initial event=%+v, want scenario id 1", event)
}
body := `{"scenario":"rainy-saturday"}`
postReq, err := http.NewRequest(http.MethodPost, ts.URL+"/api/scenario", bytes.NewBufferString(body))
if err != nil {
t.Fatal(err)
}
postReq.SetBasicAuth("control", "secret")
postReq.Header.Set("Content-Type", "application/json")
postResp, err := http.DefaultClient.Do(postReq)
if err != nil {
t.Fatal(err)
}
postResp.Body.Close()
if postResp.StatusCode != http.StatusOK {
t.Fatalf("scenario POST status=%d", postResp.StatusCode)
}
deadline := time.Now().Add(3 * time.Second)
for {
if time.Now().After(deadline) {
t.Fatal("timed out waiting for scenario event")
}
event := readEvent(t, reader)
if event.name == "scenario" {
if event.id != "2" {
t.Fatalf("scenario event id=%q, want 2", event.id)
}
var state model.ScenarioState
if err := json.Unmarshal([]byte(event.data), &state); err != nil {
t.Fatalf("decode event data: %v", err)
}
if state.Scenario.Scenario != "rainy-saturday" || state.Version != 2 {
t.Fatalf("event state=%+v", state)
}
break
}
if event.name != "ping" {
t.Fatalf("unexpected event=%+v", event)
}
}
}
type sseFrame struct {
name string
id string
data string
}
func readEvent(t *testing.T, reader *bufio.Reader) sseFrame {
t.Helper()
var frame sseFrame
for {
line, err := reader.ReadString('\n')
if err != nil {
t.Fatalf("read SSE: %v", err)
}
line = strings.TrimSuffix(strings.TrimSuffix(line, "\n"), "\r")
if line == "" {
if frame.name != "" || frame.data != "" {
return frame
}
continue
}
switch {
case strings.HasPrefix(line, "event: "):
frame.name = strings.TrimPrefix(line, "event: ")
case strings.HasPrefix(line, "id: "):
frame.id = strings.TrimPrefix(line, "id: ")
case strings.HasPrefix(line, "data: "):
frame.data = strings.TrimPrefix(line, "data: ")
}
}
}
func TestRoutingCORNAndErrors(t *testing.T) {
_, ts := newTestServer(t, &stubML{}, nil)
req, _ := http.NewRequest(http.MethodOptions, ts.URL+"/api/scenario", nil)
req.Header.Set("Origin", "https://pulse.noelsabia.dev")
resp, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatal(err)
}
resp.Body.Close()
if resp.StatusCode != http.StatusNoContent {
t.Fatalf("OPTIONS status=%d, want 204", resp.StatusCode)
}
if resp.Header.Get("Access-Control-Allow-Origin") != "https://pulse.noelsabia.dev" {
t.Errorf("missing CORS origin header: %v", resp.Header)
}
var errBody model.ErrorBody
resp = getJSON(t, ts.URL+"/api/nope", &errBody)
if resp.StatusCode != http.StatusNotFound || errBody.Error.Code != "not_found" {
t.Fatalf("unknown route status=%d body=%+v", resp.StatusCode, errBody)
}
if ct := resp.Header.Get("Content-Type"); !strings.HasPrefix(ct, "application/json") {
t.Errorf("unknown route Content-Type=%q", ct)
}
req, _ = http.NewRequest(http.MethodPost, ts.URL+"/api/meta", strings.NewReader("{}"))
resp, err = http.DefaultClient.Do(req)
if err != nil {
t.Fatal(err)
}
body, _ := io.ReadAll(resp.Body)
resp.Body.Close()
if resp.StatusCode != http.StatusMethodNotAllowed {
t.Fatalf("POST /api/meta status=%d, want 405 (body=%s)", resp.StatusCode, body)
}
if allow := resp.Header.Get("Allow"); allow != "GET" {
t.Errorf("Allow=%q, want GET", allow)
}
}
func TestSSEConcurrentClients(t *testing.T) {
srv, _ := newTestServer(t, &stubML{}, func(cfg *config.Config) { cfg.Heartbeat = time.Hour })
const clients = 120
channels := make([]<-chan sse.Event, clients)
cancels := make([]func(), clients)
for i := 0; i < clients; i++ {
channels[i], cancels[i] = srv.hub.Subscribe()
}
defer func() {
for _, cancel := range cancels {
cancel()
}
}()
if got := srv.hub.Clients(); got != clients {
t.Fatalf("clients=%d, want %d", got, clients)
}
srv.hub.Broadcast(sse.Event{Name: "scenario", ID: 7, Data: []byte(fmt.Sprintf(`{"version":%d}`, 7))})
for i, ch := range channels {
select {
case event := <-ch:
if event.Name != "scenario" || event.ID != 7 {
t.Fatalf("client %d event=%+v", i, event)
}
case <-time.After(2 * time.Second):
t.Fatalf("client %d did not receive the broadcast", i)
}
}
}
+154
View File
@@ -0,0 +1,154 @@
package api
import (
"math"
"net/http"
"sort"
"time"
"pulsecast/api/internal/model"
)
func (s *Server) handleHealthz(w http.ResponseWriter, _ *http.Request) {
writeJSON(w, http.StatusOK, map[string]bool{"ok": true})
}
func (s *Server) handleReadyz(w http.ResponseWriter, _ *http.Request) {
ready := s.store != nil && s.store.Ready()
dataOK := s.store != nil && s.store.Len() > 0 && !s.store.Context().UpdatedAt.IsZero()
modelOK := s.store != nil && s.store.Meta().ModelVersion != ""
status := http.StatusOK
if !ready {
status = http.StatusServiceUnavailable
}
writeJSON(w, status, map[string]bool{"ok": ready, "data": dataOK, "model": modelOK})
}
func (s *Server) handleMeta(w http.ResponseWriter, _ *http.Request) {
s.setVersions(w)
writeJSON(w, http.StatusOK, s.store.Meta())
}
func (s *Server) handleSensors(w http.ResponseWriter, _ *http.Request) {
s.setVersions(w)
writeJSON(w, http.StatusOK, s.store.Sensors())
}
func (s *Server) handleSeries(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 _, ok := s.store.Sensor(sensor); !ok {
writeError(w, http.StatusNotFound, "not_found", "unknown sensor")
return
}
step := query.Get("step")
if step == "" {
step = "1h"
}
if step != "15m" && step != "1h" {
writeError(w, http.StatusBadRequest, "bad_request", "step must be 15m or 1h")
return
}
raw, _ := s.store.Series(sensor)
if len(raw) == 0 {
s.setVersions(w)
writeJSON(w, http.StatusOK, map[string]any{"sensor": sensor, "step": step, "points": []model.Point{}})
return
}
to := time.Time{}
if rawTime := query.Get("to"); rawTime != "" {
parsed, err := time.Parse(time.RFC3339, rawTime)
if err != nil {
writeError(w, http.StatusBadRequest, "bad_request", "to must be RFC 3339")
return
}
to = parsed.UTC()
} else if len(raw) > 0 {
to = raw[len(raw)-1].T.UTC()
}
from := time.Time{}
if rawTime := query.Get("from"); rawTime != "" {
parsed, err := time.Parse(time.RFC3339, rawTime)
if err != nil {
writeError(w, http.StatusBadRequest, "bad_request", "from must be RFC 3339")
return
}
from = parsed.UTC()
} else {
from = to.AddDate(0, 0, -7)
}
if to.IsZero() || !from.Before(to) {
writeError(w, http.StatusBadRequest, "bad_request", "from must be before to and the series must not be empty")
return
}
points := filterSeries(raw, from, to)
if step == "1h" {
points = hourlyMean(points)
}
s.setVersions(w)
writeJSON(w, http.StatusOK, map[string]any{
"sensor": sensor,
"step": step,
"points": points,
})
}
func filterSeries(points []model.Point, from, to time.Time) []model.Point {
out := make([]model.Point, 0, len(points))
for _, point := range points {
if point.T.Before(from) || point.T.After(to) {
continue
}
out = append(out, point)
}
return out
}
// hourlyMean aggregates 15-minute observations into clock hours (UTC buckets)
// using the mean of the density index, not the sum.
func hourlyMean(points []model.Point) []model.Point {
type bucket struct {
sum float64
count int
}
buckets := make(map[time.Time]bucket)
for _, point := range points {
key := point.T.UTC().Truncate(time.Hour)
b := buckets[key]
b.sum += point.V
b.count++
buckets[key] = b
}
keys := make([]time.Time, 0, len(buckets))
for key := range buckets {
keys = append(keys, key)
}
sort.Slice(keys, func(i, j int) bool { return keys[i].Before(keys[j]) })
out := make([]model.Point, 0, len(keys))
for _, key := range keys {
b := buckets[key]
out = append(out, model.Point{T: key, V: math.Round(b.sum/float64(b.count)*10) / 10})
}
return out
}
func (s *Server) handleContext(w http.ResponseWriter, _ *http.Request) {
ctx := s.store.Context()
s.setVersions(w)
writeJSON(w, http.StatusOK, model.ContextResponse{
Weather: ctx.Weather,
Holidays: ctx.Holidays,
UpdatedAt: ctx.UpdatedAt,
Cached: false,
})
}
+227
View File
@@ -0,0 +1,227 @@
package api
import (
"context"
"fmt"
"log/slog"
"net/http"
"sort"
"time"
"pulsecast/api/internal/ml"
"pulsecast/api/internal/model"
"pulsecast/api/internal/staffing"
)
func (s *Server) handleForecast(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 _, ok := s.store.Sensor(sensor); !ok {
writeError(w, http.StatusNotFound, "not_found", "unknown sensor")
return
}
horizon := query.Get("horizon")
if horizon == "" {
horizon = "7d"
}
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
}
state := s.scenario.Get()
points, err := s.liveForecast(r.Context(), sensor, horizon, scenarioName, state)
cached := false
if err != nil {
cached = true
var ok bool
points, ok = s.fallbackForecast(sensor, scenarioName, horizon)
if !ok {
slog.Warn("forecast unavailable", "sensor", sensor, "horizon", horizon, "scenario", scenarioName, "error", err)
writeError(w, http.StatusServiceUnavailable, "forecast_unavailable",
"no live forecast and no baked forecast for this sensor, scenario and horizon")
return
}
}
s.setVersions(w)
writeJSON(w, http.StatusOK, model.ForecastResponse{
Sensor: sensor,
Horizon: horizon,
Scenario: scenarioName,
Points: points,
Cached: cached,
DataVersion: s.store.Meta().DataVersion,
ModelVersion: s.store.Meta().ModelVersion,
ContextVersion: s.store.Meta().ContextVersion,
})
}
func (s *Server) liveForecast(ctx context.Context, sensor, horizon, scenarioName string, state model.ScenarioState) ([]model.ForecastPoint, error) {
if s.ml == nil {
return nil, fmt.Errorf("ml client not configured")
}
ctx, cancel := context.WithTimeout(ctx, s.cfg.MLTimeout)
defer cancel()
ctxData := s.store.Context()
precip := ctxData.Weather.Now.PrecipMM
if state.Scenario.Weather.PrecipMM > 0 {
precip = state.Scenario.Weather.PrecipMM
}
_, isHoliday := s.holidayOn(state.At)
points, err := s.ml.Predict(ctx, ml.PredictRequest{
Sensor: sensor,
Horizon: horizon,
Scenario: scenarioName,
Weather: ml.WeatherInput{
TempC: ctxData.Weather.Now.TempC + state.Scenario.Weather.TempDeltaC,
PrecipMM: precip,
},
IsHoliday: isHoliday,
})
if err != nil {
return nil, err
}
return sortedForecast(points), nil
}
// fallbackForecast prefers live /simulate output for the current scenario, then
// the baked scenario grid. It never labels base data as another scenario.
func (s *Server) fallbackForecast(sensor, scenarioName, horizon string) ([]model.ForecastPoint, bool) {
s.mu.RLock()
if s.simFor == scenarioName {
if horizons, ok := s.sim[sensor]; ok {
if points, ok := horizons[horizon]; ok && len(points) > 0 {
out := sortedForecast(points)
s.mu.RUnlock()
return out, true
}
}
}
s.mu.RUnlock()
if points, ok := s.store.Forecast(sensor, scenarioName, horizon); ok {
return sortedForecast(points), true
}
return nil, false
}
func sortedForecast(points []model.ForecastPoint) []model.ForecastPoint {
out := make([]model.ForecastPoint, len(points))
copy(out, points)
sort.Slice(out, func(i, j int) bool { return out[i].T.Before(out[j].T) })
return out
}
func (s *Server) holidayOn(t time.Time) (string, bool) {
day := t.In(s.loc).Format("2006-01-02")
for _, holiday := range s.store.Context().Holidays {
if holiday.Date == day {
return holiday.Name, true
}
}
return "", false
}
func (s *Server) handleStaffing(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 _, ok := s.store.Sensor(sensor); !ok {
writeError(w, http.StatusNotFound, "not_found", "unknown sensor")
return
}
scenarioName := query.Get("scenario")
if scenarioName == "" {
scenarioName = "base"
}
if !model.Contains(model.Scenarios, scenarioName) {
writeError(w, http.StatusBadRequest, "bad_request", "unknown scenario")
return
}
standard := query.Get("standard")
if standard == "" {
standard = "standard"
}
if !model.Contains(model.Standards, standard) {
writeError(w, http.StatusBadRequest, "bad_request", "standard must be relaxed, standard or premium")
return
}
state := s.scenario.Get()
points, cached, ok := s.staffingForecast(sensor, scenarioName)
if !ok {
writeError(w, http.StatusServiceUnavailable, "staffing_unavailable",
"no 7d forecast for this sensor and scenario")
return
}
s.mu.RLock()
generation := s.simGen
s.mu.RUnlock()
key := fmt.Sprintf("%s|%s|%s|%d|%d", sensor, scenarioName, standard, state.Version, generation)
s.mu.RLock()
plan, hit := s.staffing[key]
s.mu.RUnlock()
if !hit {
built, err := staffing.Build(sensor, scenarioName, standard, points, s.store.Context())
if err != nil {
slog.Warn("staffing build failed", "sensor", sensor, "scenario", scenarioName, "standard", standard, "error", err)
writeError(w, http.StatusServiceUnavailable, "staffing_unavailable", "could not build a plan from the available forecast")
return
}
s.mu.Lock()
s.staffing[key] = built
s.mu.Unlock()
plan = built
}
plan.Cached = cached
plan.DataVersion = s.store.Meta().DataVersion
plan.ModelVersion = s.store.Meta().ModelVersion
plan.ContextVersion = s.store.Meta().ContextVersion
s.setVersions(w)
writeJSON(w, http.StatusOK, plan)
}
// staffingForecast returns the best 7d points and whether they came from the
// fallback grid rather than live /simulate output.
func (s *Server) staffingForecast(sensor, scenarioName string) ([]model.ForecastPoint, bool, bool) {
s.mu.RLock()
if s.simFor == scenarioName {
if horizons, ok := s.sim[sensor]; ok {
if points, ok := horizons["7d"]; ok && len(points) > 0 {
out := sortedForecast(points)
s.mu.RUnlock()
return out, false, true
}
}
}
s.mu.RUnlock()
if points, ok := s.store.Forecast(sensor, scenarioName, "7d"); ok {
return sortedForecast(points), scenarioName != "base", true
}
return nil, false, false
}
+162
View File
@@ -0,0 +1,162 @@
package api
import (
"context"
"crypto/subtle"
"encoding/json"
"fmt"
"io"
"log/slog"
"net/http"
"pulsecast/api/internal/ml"
"pulsecast/api/internal/model"
"pulsecast/api/internal/sse"
)
func (s *Server) handleScenarioGet(w http.ResponseWriter, _ *http.Request) {
writeJSON(w, http.StatusOK, s.scenario.Get())
}
func (s *Server) handleScenarioPost(w http.ResponseWriter, r *http.Request) {
r.Body = http.MaxBytesReader(w, r.Body, 1<<20)
var input model.ScenarioInput
if err := decodeJSON(r, &input); err != nil {
writeError(w, http.StatusBadRequest, "bad_request", "invalid JSON body")
return
}
if !model.Contains(model.Scenarios, input.Scenario) {
writeError(w, http.StatusBadRequest, "bad_request", "scenario must be one of base, sunny-saturday-market, rainy-saturday, weekday-event")
return
}
if input.Weather.PrecipMM < 0 {
writeError(w, http.StatusBadRequest, "bad_request", "weather.precip_mm must be >= 0")
return
}
state := s.scenario.Set(input)
if raw, err := json.Marshal(state); err == nil {
s.hub.Broadcast(sse.Event{Name: "scenario", ID: state.Version, Data: raw})
}
// Contract §3: refresh the scenario forecast grid through /simulate and
// cache it. This never blocks the control response.
go s.refreshSimulation(state)
writeJSON(w, http.StatusOK, state)
}
func decodeJSON(r *http.Request, dst any) error {
decoder := json.NewDecoder(r.Body)
if err := decoder.Decode(dst); err != nil {
return err
}
if err := decoder.Decode(&struct{}{}); err != io.EOF {
return fmt.Errorf("trailing JSON data")
}
return nil
}
func (s *Server) refreshSimulation(state model.ScenarioState) {
if s.ml == nil {
return
}
ctx, cancel := context.WithTimeout(context.Background(), s.cfg.MLTimeout)
defer cancel()
forecasts, err := s.ml.Simulate(ctx, ml.SimulateRequest{
Scenario: state.Scenario.Scenario,
Weather: state.Scenario.Weather,
Sensors: "all",
})
if err != nil {
slog.Warn("simulate fallback", "scenario", state.Scenario.Scenario, "error", err)
return
}
// Discard a response that belongs to an older scenario.
if s.scenario.Get().Version != state.Version {
return
}
s.mu.Lock()
s.sim = forecasts
s.simFor = state.Scenario.Scenario
s.simGen++
s.staffing = make(map[string]model.StaffingResponse)
s.mu.Unlock()
}
func (s *Server) requireControlAuth(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if !s.cfg.ControlAuthConfigured() {
writeError(w, http.StatusServiceUnavailable, "control_auth_unconfigured",
"CONTROL_USER and CONTROL_PASS are not configured")
return
}
user, pass, ok := r.BasicAuth()
userOK := subtle.ConstantTimeCompare([]byte(user), []byte(s.cfg.ControlUser)) == 1
passOK := subtle.ConstantTimeCompare([]byte(pass), []byte(s.cfg.ControlPass)) == 1
if !ok || !userOK || !passOK {
w.Header().Set("WWW-Authenticate", `Basic realm="pulsecast-control"`)
writeError(w, http.StatusUnauthorized, "unauthorized", "valid control credentials are required")
return
}
next(w, r)
}
}
func (s *Server) handleStream(w http.ResponseWriter, r *http.Request) {
flusher, ok := w.(http.Flusher)
if !ok {
writeError(w, http.StatusInternalServerError, "internal", "streaming is not supported by this server")
return
}
headers := w.Header()
headers.Set("Content-Type", "text/event-stream")
headers.Set("Cache-Control", "no-cache")
headers.Set("Connection", "keep-alive")
headers.Set("X-Accel-Buffering", "no")
events, unsubscribe := s.hub.Subscribe()
defer unsubscribe()
w.WriteHeader(http.StatusOK)
if _, err := fmt.Fprint(w, "retry: 3000\n\n"); err != nil {
return
}
flusher.Flush()
state := s.scenario.Get()
raw, _ := json.Marshal(state)
if err := writeSSEEvent(w, flusher, sse.Event{Name: "scenario", ID: state.Version, Data: raw}); err != nil {
return
}
for {
select {
case <-r.Context().Done():
return
case event := <-events:
if err := writeSSEEvent(w, flusher, event); err != nil {
return
}
}
}
}
func writeSSEEvent(w http.ResponseWriter, flusher http.Flusher, event sse.Event) error {
if _, err := fmt.Fprintf(w, "event: %s\n", event.Name); err != nil {
return err
}
if event.ID > 0 {
if _, err := fmt.Fprintf(w, "id: %d\n", event.ID); err != nil {
return err
}
}
if _, err := fmt.Fprintf(w, "data: %s\n\n", event.Data); err != nil {
return err
}
flusher.Flush()
return nil
}
+115
View File
@@ -0,0 +1,115 @@
package api
import (
"bytes"
"context"
"encoding/json"
"io"
"log/slog"
"mime"
"net/http"
"pulsecast/api/internal/ml"
"pulsecast/api/internal/model"
)
// maxTrainBody bounds an uploaded CSV. The raw dataset is ~18 MB; 64 MB leaves
// room for a larger export without letting the API accept unbounded bodies.
const maxTrainBody = 64 << 20
// handleTrain proxies POST /api/train to FastAPI. The request is queued there,
// so this handler only validates the JSON form and relays the 202/409 response.
func (s *Server) handleTrain(w http.ResponseWriter, r *http.Request) {
trainer, ok := s.ml.(TrainClient)
if !ok {
writeError(w, http.StatusBadGateway, "ml_unavailable", "FastAPI training client is not configured")
return
}
r.Body = http.MaxBytesReader(w, r.Body, maxTrainBody)
mediaType, _, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
if err != nil {
writeError(w, http.StatusBadRequest, "bad_request", "Content-Type must be application/json or multipart/form-data")
return
}
switch mediaType {
case "application/json":
var req ml.TrainRequest
if err := decodeJSON(r, &req); err != nil {
writeError(w, http.StatusBadRequest, "bad_request", "invalid JSON body")
return
}
if req.Path == "" {
writeError(w, http.StatusBadRequest, "bad_request", "path is required")
return
}
if req.Model == "" {
req.Model = "small"
}
if !model.Contains(ml.TrainModels, req.Model) {
writeError(w, http.StatusBadRequest, "bad_request", "model must be small or forecast")
return
}
raw, err := json.Marshal(req)
if err != nil {
writeError(w, http.StatusInternalServerError, "internal", "failed to encode request")
return
}
s.relayTrain(r.Context(), trainer, w, "application/json", bytes.NewReader(raw))
case "multipart/form-data":
// Forward the stream unchanged: file and model fields belong to FastAPI.
s.relayTrain(r.Context(), trainer, w, r.Header.Get("Content-Type"), r.Body)
default:
writeError(w, http.StatusBadRequest, "bad_request", "Content-Type must be application/json or multipart/form-data")
}
}
// handleTrainStatus proxies GET /api/train/{job_id}.
func (s *Server) handleTrainStatus(w http.ResponseWriter, r *http.Request) {
trainer, ok := s.ml.(TrainClient)
if !ok {
writeError(w, http.StatusBadGateway, "ml_unavailable", "FastAPI training client is not configured")
return
}
jobID := r.PathValue("job_id")
if jobID == "" {
writeError(w, http.StatusNotFound, "not_found", "training job not found")
return
}
status, body, err := trainer.TrainStatus(r.Context(), jobID)
if err != nil {
slog.Warn("train status proxy failed", "job_id", jobID, "error", err)
writeError(w, http.StatusBadGateway, "ml_unavailable", "FastAPI is unavailable")
return
}
relayMLResponse(w, status, body)
}
func (s *Server) relayTrain(ctx context.Context, trainer TrainClient, w http.ResponseWriter, contentType string, body io.Reader) {
status, raw, err := trainer.Train(ctx, contentType, body)
if err != nil {
slog.Warn("train proxy failed", "error", err)
writeError(w, http.StatusBadGateway, "ml_unavailable", "FastAPI is unavailable")
return
}
relayMLResponse(w, status, raw)
}
// relayMLResponse forwards FastAPI's status and JSON body. A non-JSON upstream
// body is converted to the contract error envelope instead of leaking HTML.
func relayMLResponse(w http.ResponseWriter, status int, body []byte) {
if status < 100 || status > 599 {
writeError(w, http.StatusBadGateway, "bad_gateway", "FastAPI returned an invalid status")
return
}
body = bytes.TrimSpace(body)
if len(body) == 0 || !json.Valid(body) {
writeError(w, http.StatusBadGateway, "bad_gateway", "FastAPI returned a non-JSON response")
return
}
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(status)
_, _ = w.Write(body)
}
+285
View File
@@ -0,0 +1,285 @@
package api
import (
"bytes"
"encoding/json"
"io"
"mime/multipart"
"net/http"
"net/http/httptest"
"strings"
"sync/atomic"
"testing"
"time"
"pulsecast/api/internal/config"
"pulsecast/api/internal/ml"
)
func newTrainServer(t *testing.T, fastapiURL string) *httptest.Server {
t.Helper()
_, ts := newTestServer(t, ml.New(fastapiURL, 500*time.Millisecond), func(cfg *config.Config) {
cfg.FastAPIURL = fastapiURL
cfg.ControlUser = "control"
cfg.ControlPass = "secret"
})
return ts
}
func controlRequest(t *testing.T, method, url, contentType string, body io.Reader, user, pass string) (*http.Response, []byte) {
t.Helper()
req, err := http.NewRequest(method, url, body)
if err != nil {
t.Fatal(err)
}
if contentType != "" {
req.Header.Set("Content-Type", contentType)
}
if user != "" {
req.SetBasicAuth(user, pass)
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatalf("%s %s: %v", method, url, err)
}
defer resp.Body.Close()
raw, err := io.ReadAll(resp.Body)
if err != nil {
t.Fatalf("read %s %s: %v", method, url, err)
}
return resp, raw
}
func TestTrainJSONProxyAndControlAuth(t *testing.T) {
var calls atomic.Int32
var gotBody []byte
fastapi := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost || r.URL.Path != "/train" {
http.Error(w, "unexpected", http.StatusNotFound)
return
}
calls.Add(1)
if ct := r.Header.Get("Content-Type"); ct != "application/json" {
t.Errorf("FastAPI Content-Type=%q, want application/json", ct)
}
gotBody, _ = io.ReadAll(r.Body)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusAccepted)
_, _ = w.Write([]byte(`{"job_id":"job-1","status":"queued","model":"small","submitted_at":"2026-11-14T09:00:00Z"}`))
}))
defer fastapi.Close()
ts := newTrainServer(t, fastapi.URL)
body := `{"path":"/tmp/new.csv"}`
if resp, _ := controlRequest(t, http.MethodPost, ts.URL+"/api/train", "application/json", strings.NewReader(body), "", ""); resp.StatusCode != http.StatusUnauthorized {
t.Fatalf("no auth status=%d, want 401", resp.StatusCode)
} else if resp.Header.Get("WWW-Authenticate") == "" {
t.Error("missing WWW-Authenticate header")
}
if resp, _ := controlRequest(t, http.MethodPost, ts.URL+"/api/train", "application/json", strings.NewReader(body), "control", "wrong"); resp.StatusCode != http.StatusUnauthorized {
t.Fatalf("bad auth status=%d, want 401", resp.StatusCode)
}
if got := calls.Load(); got != 0 {
t.Fatalf("FastAPI calls=%d before auth succeeded, want 0", got)
}
resp, raw := controlRequest(t, http.MethodPost, ts.URL+"/api/train", "application/json", strings.NewReader(body), "control", "secret")
if resp.StatusCode != http.StatusAccepted {
t.Fatalf("train status=%d body=%s, want 202", resp.StatusCode, raw)
}
var job map[string]any
if err := json.Unmarshal(raw, &job); err != nil {
t.Fatalf("decode train response: %v", err)
}
if job["job_id"] != "job-1" || job["status"] != "queued" {
t.Fatalf("train response=%v", job)
}
var forwarded ml.TrainRequest
if err := json.Unmarshal(gotBody, &forwarded); err != nil {
t.Fatalf("decode forwarded body: %v", err)
}
if forwarded.Path != "/tmp/new.csv" || forwarded.Model != "small" {
t.Fatalf("forwarded body=%+v, want path and default model=small", forwarded)
}
if resp, _ := controlRequest(t, http.MethodGet, ts.URL+"/api/train/job-1", "", nil, "", ""); resp.StatusCode != http.StatusUnauthorized {
t.Fatalf("status without auth=%d, want 401", resp.StatusCode)
}
}
func TestTrainStatusProxy(t *testing.T) {
fastapi := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
switch r.URL.Path {
case "/train/job-1":
if r.Method != http.MethodGet {
t.Errorf("method=%s, want GET", r.Method)
}
_, _ = w.Write([]byte(`{"job_id":"job-1","status":"succeeded","model":"forecast","metrics":{"accuracy":0.9},"model_version":"v2","error":null}`))
default:
w.WriteHeader(http.StatusNotFound)
_, _ = w.Write([]byte(`{"detail":"job not found"}`))
}
}))
defer fastapi.Close()
ts := newTrainServer(t, fastapi.URL)
resp, raw := controlRequest(t, http.MethodGet, ts.URL+"/api/train/job-1", "", nil, "control", "secret")
if resp.StatusCode != http.StatusOK {
t.Fatalf("status=%d body=%s, want 200", resp.StatusCode, raw)
}
var job struct {
JobID string `json:"job_id"`
Status string `json:"status"`
Metrics map[string]any `json:"metrics"`
Error any `json:"error"`
}
if err := json.Unmarshal(raw, &job); err != nil {
t.Fatalf("decode status response: %v", err)
}
if job.JobID != "job-1" || job.Status != "succeeded" || job.Metrics["accuracy"] != 0.9 {
t.Fatalf("status response=%+v", job)
}
resp, raw = controlRequest(t, http.MethodGet, ts.URL+"/api/train/missing", "", nil, "control", "secret")
if resp.StatusCode != http.StatusNotFound {
t.Fatalf("unknown job status=%d body=%s, want 404", resp.StatusCode, raw)
}
if !json.Valid(raw) {
t.Fatalf("unknown job body is not JSON: %s", raw)
}
}
func TestTrainMultipartProxy(t *testing.T) {
var gotFile, gotModel string
fastapi := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost || r.URL.Path != "/train" {
http.Error(w, "unexpected", http.StatusNotFound)
return
}
if !strings.HasPrefix(r.Header.Get("Content-Type"), "multipart/form-data; boundary=") {
t.Errorf("Content-Type=%q, want multipart/form-data", r.Header.Get("Content-Type"))
}
if err := r.ParseMultipartForm(1 << 20); err != nil {
t.Errorf("parse multipart: %v", err)
http.Error(w, "bad multipart", http.StatusBadRequest)
return
}
gotModel = r.FormValue("model")
file, _, err := r.FormFile("file")
if err != nil {
t.Errorf("form file: %v", err)
} else {
raw, _ := io.ReadAll(file)
file.Close()
gotFile = string(raw)
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusAccepted)
_, _ = w.Write([]byte(`{"job_id":"job-2","status":"queued","model":"forecast","submitted_at":"2026-11-14T09:00:00Z"}`))
}))
defer fastapi.Close()
ts := newTrainServer(t, fastapi.URL)
var buf bytes.Buffer
mw := multipart.NewWriter(&buf)
part, err := mw.CreateFormFile("file", "new-data.csv")
if err != nil {
t.Fatal(err)
}
if _, err := part.Write([]byte("timestamp,count\n2026-11-01T10:00:00Z,42\n")); err != nil {
t.Fatal(err)
}
if err := mw.WriteField("model", "forecast"); err != nil {
t.Fatal(err)
}
if err := mw.Close(); err != nil {
t.Fatal(err)
}
resp, raw := controlRequest(t, http.MethodPost, ts.URL+"/api/train", mw.FormDataContentType(), &buf, "control", "secret")
if resp.StatusCode != http.StatusAccepted {
t.Fatalf("multipart status=%d body=%s, want 202", resp.StatusCode, raw)
}
if gotModel != "forecast" {
t.Errorf("forwarded model=%q, want forecast", gotModel)
}
if !strings.Contains(gotFile, "42") {
t.Errorf("forwarded file=%q, want CSV content", gotFile)
}
}
func TestTrainValidationAndUpstreamErrors(t *testing.T) {
var calls atomic.Int32
fastapi := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
calls.Add(1)
w.Header().Set("Content-Type", "application/json")
if r.Method == http.MethodPost {
w.WriteHeader(http.StatusConflict)
_, _ = w.Write([]byte(`{"detail":"a training job is already running"}`))
return
}
http.NotFound(w, r)
}))
defer fastapi.Close()
ts := newTrainServer(t, fastapi.URL)
for _, tc := range []struct {
name string
contentType string
body string
}{
{"unknown model", "application/json", `{"path":"/tmp/x.csv","model":"huge"}`},
{"missing path", "application/json", `{"model":"small"}`},
{"malformed json", "application/json", `{`},
{"wrong content type", "text/plain", `path=/tmp/x.csv`},
} {
resp, raw := controlRequest(t, http.MethodPost, ts.URL+"/api/train", tc.contentType, strings.NewReader(tc.body), "control", "secret")
if resp.StatusCode != http.StatusBadRequest {
t.Errorf("%s: status=%d body=%s, want 400", tc.name, resp.StatusCode, raw)
}
}
if got := calls.Load(); got != 0 {
t.Fatalf("FastAPI calls=%d for invalid requests, want 0", got)
}
resp, raw := controlRequest(t, http.MethodPost, ts.URL+"/api/train", "application/json", strings.NewReader(`{"path":"/tmp/x.csv","model":"forecast"}`), "control", "secret")
if resp.StatusCode != http.StatusConflict {
t.Fatalf("busy status=%d body=%s, want upstream 409", resp.StatusCode, raw)
}
if resp, _ := controlRequest(t, http.MethodPost, ts.URL+"/api/train/job-1", "application/json", strings.NewReader(`{}`), "control", "secret"); resp.StatusCode != http.StatusMethodNotAllowed {
t.Errorf("POST job status=%d, want 405", resp.StatusCode)
} else if allow := resp.Header.Get("Allow"); allow != "GET" {
t.Errorf("Allow=%q, want GET", allow)
}
if resp, _ := controlRequest(t, http.MethodGet, ts.URL+"/api/train", "", nil, "control", "secret"); resp.StatusCode != http.StatusMethodNotAllowed {
t.Errorf("GET train status=%d, want 405", resp.StatusCode)
}
if resp, _ := controlRequest(t, http.MethodGet, ts.URL+"/api/train/a/b", "", nil, "control", "secret"); resp.StatusCode != http.StatusNotFound {
t.Errorf("nested job path status=%d, want 404", resp.StatusCode)
}
}
func TestTrainFastAPIDownAndAuthUnconfigured(t *testing.T) {
_, down := newTestServer(t, ml.New("http://127.0.0.1:1", 50*time.Millisecond), func(cfg *config.Config) {
cfg.FastAPIURL = "http://127.0.0.1:1"
cfg.ControlUser = "control"
cfg.ControlPass = "secret"
})
resp, raw := controlRequest(t, http.MethodPost, down.URL+"/api/train", "application/json", strings.NewReader(`{"path":"/tmp/x.csv"}`), "control", "secret")
if resp.StatusCode != http.StatusBadGateway {
t.Fatalf("train with FastAPI down status=%d body=%s, want 502", resp.StatusCode, raw)
}
resp, raw = controlRequest(t, http.MethodGet, down.URL+"/api/train/job-1", "", nil, "control", "secret")
if resp.StatusCode != http.StatusBadGateway {
t.Fatalf("status with FastAPI down=%d body=%s, want 502", resp.StatusCode, raw)
}
_, unconfigured := newTestServer(t, &stubML{}, nil)
resp, raw = controlRequest(t, http.MethodPost, unconfigured.URL+"/api/train", "application/json", strings.NewReader(`{"path":"/tmp/x.csv"}`), "control", "secret")
if resp.StatusCode != http.StatusServiceUnavailable {
t.Fatalf("train without control env status=%d body=%s, want 503", resp.StatusCode, raw)
}
}
+203
View File
@@ -0,0 +1,203 @@
// Package api wires the HTTP handlers, scenario state, SSE hub and cache
// fallback into the Go service described by CONTRACT.md.
package api
import (
"context"
"encoding/json"
"io"
"log/slog"
"net/http"
"strings"
"sync"
"time"
"pulsecast/api/internal/config"
"pulsecast/api/internal/ml"
"pulsecast/api/internal/model"
"pulsecast/api/internal/scenario"
"pulsecast/api/internal/sse"
"pulsecast/api/internal/store"
)
// MLClient is the FastAPI prediction surface the data handlers need.
// *ml.Client implements it; tests use a stub.
type MLClient interface {
Predict(ctx context.Context, req ml.PredictRequest) ([]model.ForecastPoint, error)
Simulate(ctx context.Context, req ml.SimulateRequest) (map[string]map[string][]model.ForecastPoint, error)
}
// TrainClient is the optional FastAPI training surface. Keeping it separate
// lets prediction-only stubs (and the cached fallback) work unchanged.
type TrainClient interface {
Train(ctx context.Context, contentType string, body io.Reader) (int, []byte, error)
TrainStatus(ctx context.Context, jobID string) (int, []byte, error)
}
// Server holds process-wide state. One instance per pod.
type Server struct {
cfg config.Config
store *store.Store
ml MLClient
hub *sse.Hub
scenario *scenario.State
loc *time.Location
now func() time.Time
mu sync.RWMutex
sim map[string]map[string][]model.ForecastPoint // sensor -> horizon -> points
simFor string // scenario the sim belongs to
simGen int // invalidates staffing cache
staffing map[string]model.StaffingResponse
}
// New builds a server. hub must be non-nil; main runs hub.Run.
func New(cfg config.Config, st *store.Store, client MLClient, hub *sse.Hub) *Server {
loc, err := time.LoadLocation(model.StoreHours.TZ)
if err != nil {
loc = time.UTC
}
if cfg.MLTimeout <= 0 {
cfg.MLTimeout = ml.DefaultTimeout
}
return &Server{
cfg: cfg,
store: st,
ml: client,
hub: hub,
scenario: scenario.New(),
loc: loc,
now: time.Now,
staffing: make(map[string]model.StaffingResponse),
}
}
// Handler returns the full middleware + route stack.
func (s *Server) Handler() http.Handler {
mux := http.NewServeMux()
mux.HandleFunc("GET /api/healthz", s.handleHealthz)
mux.HandleFunc("GET /api/readyz", s.handleReadyz)
mux.HandleFunc("GET /api/meta", s.handleMeta)
mux.HandleFunc("GET /api/sensors", s.handleSensors)
mux.HandleFunc("GET /api/series", s.handleSeries)
mux.HandleFunc("GET /api/context", s.handleContext)
mux.HandleFunc("GET /api/forecast", s.handleForecast)
mux.HandleFunc("GET /api/staffing", s.handleStaffing)
mux.HandleFunc("GET /api/scenario", s.handleScenarioGet)
mux.HandleFunc("POST /api/scenario", s.requireControlAuth(s.handleScenarioPost))
mux.HandleFunc("POST /api/train", s.requireControlAuth(s.handleTrain))
mux.HandleFunc("GET /api/train/{job_id}", s.requireControlAuth(s.handleTrainStatus))
mux.HandleFunc("GET /api/stream", s.handleStream)
return s.recoverer(s.withCORS(s.routeCheck(mux)))
}
var methodTable = map[string][]string{
"/api/healthz": {"GET"},
"/api/readyz": {"GET"},
"/api/meta": {"GET"},
"/api/sensors": {"GET"},
"/api/series": {"GET"},
"/api/context": {"GET"},
"/api/forecast": {"GET"},
"/api/staffing": {"GET"},
"/api/scenario": {"GET", "POST"},
"/api/train": {"POST"},
"/api/stream": {"GET"},
}
func (s *Server) routeCheck(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
methods, ok := methodTable[r.URL.Path]
if !ok && isTrainJobPath(r.URL.Path) {
methods, ok = []string{"GET"}, true
}
if !ok {
writeError(w, http.StatusNotFound, "not_found", "route not found")
return
}
if !model.Contains(methods, r.Method) {
w.Header().Set("Allow", joinMethods(methods))
writeError(w, http.StatusMethodNotAllowed, "method_not_allowed", "method not allowed for this route")
return
}
next.ServeHTTP(w, r)
})
}
// isTrainJobPath matches exactly one job id after /api/train/.
func isTrainJobPath(path string) bool {
jobID, found := strings.CutPrefix(path, "/api/train/")
return found && jobID != "" && !strings.Contains(jobID, "/")
}
func joinMethods(methods []string) string {
out := ""
for i, method := range methods {
if i > 0 {
out += ", "
}
out += method
}
return out
}
func (s *Server) withCORS(next http.Handler) http.Handler {
allowed := map[string]bool{
"https://pulse.noelsabia.dev": true,
"http://localhost:3000": true,
}
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
origin := r.Header.Get("Origin")
if allowed[origin] {
w.Header().Set("Access-Control-Allow-Origin", origin)
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization")
w.Header().Set("Access-Control-Max-Age", "600")
w.Header().Add("Vary", "Origin")
}
if r.Method == http.MethodOptions {
w.WriteHeader(http.StatusNoContent)
return
}
next.ServeHTTP(w, r)
})
}
func (s *Server) recoverer(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer func() {
if rec := recover(); rec != nil {
slog.Error("panic serving request", "path", r.URL.Path, "panic", rec)
writeError(w, http.StatusInternalServerError, "internal", "internal server error")
}
}()
next.ServeHTTP(w, r)
})
}
func writeJSON(w http.ResponseWriter, status int, body any) {
raw, err := json.Marshal(body)
if err != nil {
writeError(w, http.StatusInternalServerError, "internal", "failed to encode response")
return
}
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(status)
_, _ = w.Write(raw)
}
func writeError(w http.ResponseWriter, status int, code, message string) {
raw, _ := json.Marshal(model.ErrorBody{Error: model.ErrorDetail{Code: code, Message: message}})
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(status)
_, _ = w.Write(raw)
}
// setVersions adds the contract's version headers.
func (s *Server) setVersions(w http.ResponseWriter) {
data, modelVersion, context := s.store.Versions()
w.Header().Set("X-Data-Version", data)
w.Header().Set("X-Model-Version", modelVersion)
w.Header().Set("X-Context-Version", context)
}
+65
View File
@@ -0,0 +1,65 @@
// Package config reads runtime configuration from the environment.
package config
import (
"os"
"strconv"
"time"
)
// Config is the process configuration.
type Config struct {
Addr string
DataDir string
FastAPIURL string
ControlUser string
ControlPass string
ControlToken string
Heartbeat time.Duration
MLTimeout time.Duration
}
// Load reads configuration from env with local-development defaults.
// CONTROL_USER / CONTROL_PASS have no defaults: POST /api/scenario fails
// closed when they are unset. CONTROL_TOKEN is optional and, when set, is
// forwarded to FastAPI's internal /train endpoints as a Bearer token.
func Load() Config {
port := getenv("PORT", "8080")
return Config{
Addr: ":" + port,
DataDir: getenv("DATA_DIR", "testdata/data"),
FastAPIURL: getenv("FASTAPI_URL", "http://localhost:8000"),
ControlUser: os.Getenv("CONTROL_USER"),
ControlPass: os.Getenv("CONTROL_PASS"),
ControlToken: os.Getenv("CONTROL_TOKEN"),
Heartbeat: durationEnv("SSE_HEARTBEAT", 15*time.Second),
MLTimeout: durationEnv("ML_TIMEOUT", 1500*time.Millisecond),
}
}
// ControlAuthConfigured reports whether both control credentials exist.
func (c Config) ControlAuthConfigured() bool {
return c.ControlUser != "" && c.ControlPass != ""
}
func getenv(key, fallback string) string {
if v := os.Getenv(key); v != "" {
return v
}
return fallback
}
func durationEnv(key string, fallback time.Duration) time.Duration {
raw := os.Getenv(key)
if raw == "" {
return fallback
}
if d, err := time.ParseDuration(raw); err == nil && d > 0 {
return d
}
// Also accept a plain number of seconds for operational convenience.
if secs, err := strconv.Atoi(raw); err == nil && secs > 0 {
return time.Duration(secs) * time.Second
}
return fallback
}
+74
View File
@@ -0,0 +1,74 @@
package config
import (
"testing"
"time"
)
func TestLoadDefaults(t *testing.T) {
for _, key := range []string{"PORT", "DATA_DIR", "FASTAPI_URL", "CONTROL_USER", "CONTROL_PASS", "CONTROL_TOKEN", "SSE_HEARTBEAT", "ML_TIMEOUT"} {
t.Setenv(key, "")
}
cfg := Load()
if cfg.Addr != ":8080" {
t.Errorf("Addr=%q", cfg.Addr)
}
if cfg.DataDir != "testdata/data" {
t.Errorf("DataDir=%q", cfg.DataDir)
}
if cfg.FastAPIURL != "http://localhost:8000" {
t.Errorf("FastAPIURL=%q", cfg.FastAPIURL)
}
if cfg.Heartbeat != 15*time.Second || cfg.MLTimeout != 1500*time.Millisecond {
t.Errorf("timeouts: heartbeat=%s ml=%s", cfg.Heartbeat, cfg.MLTimeout)
}
if cfg.ControlAuthConfigured() {
t.Error("control auth should be unconfigured by default")
}
if cfg.ControlToken != "" {
t.Errorf("ControlToken=%q, want empty by default", cfg.ControlToken)
}
}
func TestLoadFromEnv(t *testing.T) {
t.Setenv("PORT", "9999")
t.Setenv("DATA_DIR", "/data")
t.Setenv("FASTAPI_URL", "http://ml:8000")
t.Setenv("CONTROL_USER", "user")
t.Setenv("CONTROL_PASS", "pass")
t.Setenv("CONTROL_TOKEN", "token-123")
t.Setenv("SSE_HEARTBEAT", "5s")
t.Setenv("ML_TIMEOUT", "2s")
cfg := Load()
if cfg.Addr != ":9999" || cfg.DataDir != "/data" || cfg.FastAPIURL != "http://ml:8000" {
t.Fatalf("cfg=%+v", cfg)
}
if cfg.ControlToken != "token-123" {
t.Fatalf("ControlToken=%q, want token-123", cfg.ControlToken)
}
if cfg.Heartbeat != 5*time.Second || cfg.MLTimeout != 2*time.Second {
t.Fatalf("timeouts: heartbeat=%s ml=%s", cfg.Heartbeat, cfg.MLTimeout)
}
if !cfg.ControlAuthConfigured() {
t.Fatal("control auth should be configured")
}
}
func TestDurationAcceptsPlainSeconds(t *testing.T) {
t.Setenv("SSE_HEARTBEAT", "7")
t.Setenv("ML_TIMEOUT", "3")
cfg := Load()
if cfg.Heartbeat != 7*time.Second || cfg.MLTimeout != 3*time.Second {
t.Fatalf("timeouts: heartbeat=%s ml=%s", cfg.Heartbeat, cfg.MLTimeout)
}
}
func TestDurationFallsBackOnInvalidValue(t *testing.T) {
t.Setenv("SSE_HEARTBEAT", "soon")
t.Setenv("ML_TIMEOUT", "-1s")
cfg := Load()
if cfg.Heartbeat != 15*time.Second || cfg.MLTimeout != 1500*time.Millisecond {
t.Fatalf("timeouts: heartbeat=%s ml=%s", cfg.Heartbeat, cfg.MLTimeout)
}
}
+205
View File
@@ -0,0 +1,205 @@
// Package ml is the FastAPI client. Every call is bounded by a 1.5 s timeout;
// callers fall back to baked JSON on any error.
package ml
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"strings"
"time"
"pulsecast/api/internal/model"
)
// DefaultTimeout is the contract limit for a live prediction.
const DefaultTimeout = 1500 * time.Millisecond
// controlTimeout bounds training submissions and status reads. Uploads are
// larger than prediction payloads, so they get more than DefaultTimeout.
const controlTimeout = 30 * time.Second
// Client talks to the FastAPI ML service.
type Client struct {
baseURL string
http *http.Client
control *http.Client
controlToken string
}
// New returns a client for baseURL (for example http://localhost:8000).
func New(baseURL string, timeout time.Duration) *Client {
return NewWithToken(baseURL, timeout, "")
}
// NewWithToken is New plus the Bearer token FastAPI's internal /train
// endpoints expect. An empty token sends no Authorization header.
func NewWithToken(baseURL string, timeout time.Duration, controlToken string) *Client {
if timeout <= 0 {
timeout = DefaultTimeout
}
return &Client{
baseURL: strings.TrimRight(baseURL, "/"),
http: &http.Client{Timeout: timeout},
control: &http.Client{Timeout: controlTimeout},
controlToken: controlToken,
}
}
// PredictRequest mirrors CONTRACT.md §3 POST /predict.
type PredictRequest struct {
Sensor string `json:"sensor"`
Horizon string `json:"horizon"`
Scenario string `json:"scenario"`
Weather WeatherInput `json:"weather"`
IsHoliday bool `json:"is_holiday"`
}
// WeatherInput is the optional weather block.
type WeatherInput struct {
TempC float64 `json:"temp_c"`
PrecipMM float64 `json:"precip_mm"`
}
// SimulateRequest mirrors CONTRACT.md §3 POST /simulate.
type SimulateRequest struct {
Scenario string `json:"scenario"`
Weather model.WeatherInput `json:"weather"`
Sensors string `json:"sensors"`
}
// TrainRequest is the JSON form of POST /train.
type TrainRequest struct {
Path string `json:"path"`
Model string `json:"model"`
}
// TrainModels are the accepted training targets from CONTRACT.md §3.
var TrainModels = []string{"small", "forecast"}
// Predict calls POST /predict and returns the forecast points. The contract
// response is {"points":[...]}; a bare array is accepted as well.
func (c *Client) Predict(ctx context.Context, req PredictRequest) ([]model.ForecastPoint, error) {
raw, err := c.postRaw(ctx, "/predict", req)
if err != nil {
return nil, err
}
var out struct {
Points []model.ForecastPoint `json:"points"`
}
if err := json.Unmarshal(raw, &out); err == nil && out.Points != nil {
if len(out.Points) == 0 {
return nil, fmt.Errorf("ml: predict returned no points")
}
return out.Points, nil
}
var points []model.ForecastPoint
if err := json.Unmarshal(raw, &points); err == nil && len(points) > 0 {
return points, nil
}
return nil, fmt.Errorf("ml: predict returned no points")
}
// Simulate calls POST /simulate and returns forecasts keyed
// sensor -> horizon -> points.
func (c *Client) Simulate(ctx context.Context, req SimulateRequest) (map[string]map[string][]model.ForecastPoint, error) {
var out struct {
Scenario string `json:"scenario"`
Generated string `json:"generated_at"`
Forecasts map[string]map[string][]model.ForecastPoint `json:"forecasts"`
}
if err := c.post(ctx, "/simulate", req, &out); err != nil {
return nil, err
}
if len(out.Forecasts) == 0 {
return nil, fmt.Errorf("ml: simulate returned no forecasts")
}
return out.Forecasts, nil
}
// Train proxies POST /train. body is forwarded verbatim (JSON or multipart),
// and the upstream status and response are returned unchanged for the Go
// handler to relay. Training itself runs in FastAPI; this call only queues it.
func (c *Client) Train(ctx context.Context, contentType string, body io.Reader) (int, []byte, error) {
return c.controlRequest(ctx, http.MethodPost, "/train", contentType, body)
}
// TrainStatus proxies GET /train/{job_id}.
func (c *Client) TrainStatus(ctx context.Context, jobID string) (int, []byte, error) {
return c.controlRequest(ctx, http.MethodGet, "/train/"+url.PathEscape(jobID), "", nil)
}
// controlRequest performs a training/control request and returns the raw
// upstream status and body. Non-2xx responses are not errors: the proxy
// forwards them so clients see FastAPI's 400/404/409 semantics.
func (c *Client) controlRequest(ctx context.Context, method, path, contentType string, body io.Reader) (int, []byte, error) {
req, err := http.NewRequestWithContext(ctx, method, c.baseURL+path, body)
if err != nil {
return 0, nil, fmt.Errorf("ml: build request: %w", err)
}
if contentType != "" {
req.Header.Set("Content-Type", contentType)
}
req.Header.Set("Accept", "application/json")
if c.controlToken != "" {
req.Header.Set("Authorization", "Bearer "+c.controlToken)
}
resp, err := c.control.Do(req)
if err != nil {
return 0, nil, fmt.Errorf("ml: %s: %w", path, err)
}
defer resp.Body.Close()
raw, err := io.ReadAll(io.LimitReader(resp.Body, 32<<20))
if err != nil {
return 0, nil, fmt.Errorf("ml: read %s: %w", path, err)
}
return resp.StatusCode, raw, nil
}
func (c *Client) post(ctx context.Context, path string, body, dst any) error {
raw, err := c.postRaw(ctx, path, body)
if err != nil {
return err
}
if err := json.Unmarshal(raw, dst); err != nil {
return fmt.Errorf("ml: decode %s: %w", path, err)
}
return nil
}
func (c *Client) postRaw(ctx context.Context, path string, body any) ([]byte, error) {
raw, err := json.Marshal(body)
if err != nil {
return nil, fmt.Errorf("ml: encode request: %w", err)
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.baseURL+path, bytes.NewReader(raw))
if err != nil {
return nil, fmt.Errorf("ml: build request: %w", err)
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Accept", "application/json")
resp, err := c.http.Do(req)
if err != nil {
return nil, fmt.Errorf("ml: %s: %w", path, err)
}
defer resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode > 299 {
snippet, _ := io.ReadAll(io.LimitReader(resp.Body, 256))
return nil, fmt.Errorf("ml: %s: status %d: %s", path, resp.StatusCode, strings.TrimSpace(string(snippet)))
}
raw, err = io.ReadAll(io.LimitReader(resp.Body, 32<<20))
if err != nil {
return nil, fmt.Errorf("ml: read %s: %w", path, err)
}
return raw, nil
}
+219
View File
@@ -0,0 +1,219 @@
package ml
import (
"context"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
)
func TestPredictObjectResponseAndRequest(t *testing.T) {
var got PredictRequest
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/predict" {
t.Errorf("path=%q", r.URL.Path)
}
if r.Header.Get("Content-Type") != "application/json" {
t.Errorf("Content-Type=%q", r.Header.Get("Content-Type"))
}
if err := json.NewDecoder(r.Body).Decode(&got); err != nil {
t.Errorf("decode request: %v", err)
}
_, _ = w.Write([]byte(`{"points":[{"t":"2026-11-16T09:00:00Z","v":12.3,"lo":8.1,"hi":17.2}]}`))
}))
defer srv.Close()
client := New(srv.URL+"/", time.Second)
points, err := client.Predict(context.Background(), PredictRequest{
Sensor: "hn-bahnhof-01", Horizon: "1h", Scenario: "base",
Weather: WeatherInput{TempC: 9, PrecipMM: 0}, IsHoliday: false,
})
if err != nil {
t.Fatalf("Predict: %v", err)
}
if len(points) != 1 || points[0].V != 12.3 || points[0].Lo != 8.1 {
t.Fatalf("points=%+v", points)
}
if got.Sensor != "hn-bahnhof-01" || got.Horizon != "1h" || got.Weather.TempC != 9 {
t.Fatalf("request=%+v", got)
}
}
func TestPredictBareArrayResponse(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
_, _ = w.Write([]byte(`[{"t":"2026-11-16T09:00:00Z","v":1,"lo":0.5,"hi":1.5}]`))
}))
defer srv.Close()
points, err := New(srv.URL, time.Second).Predict(context.Background(), PredictRequest{})
if err != nil {
t.Fatalf("Predict: %v", err)
}
if len(points) != 1 || points[0].V != 1 {
t.Fatalf("points=%+v", points)
}
}
func TestPredictRejectsEmptyAndErrorStatus(t *testing.T) {
empty := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
_, _ = w.Write([]byte(`{"points":[]}`))
}))
defer empty.Close()
if _, err := New(empty.URL, time.Second).Predict(context.Background(), PredictRequest{}); err == nil {
t.Fatal("expected an error for an empty points array")
}
boom := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
http.Error(w, "nope", http.StatusInternalServerError)
}))
defer boom.Close()
if _, err := New(boom.URL, time.Second).Predict(context.Background(), PredictRequest{}); err == nil {
t.Fatal("expected an error for HTTP 500")
}
}
func TestPredictTimeout(t *testing.T) {
slow := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
time.Sleep(150 * time.Millisecond)
_, _ = w.Write([]byte(`{"points":[{"t":"2026-11-16T09:00:00Z","v":1,"lo":0,"hi":2}]}`))
}))
defer slow.Close()
client := New(slow.URL, 20*time.Millisecond)
start := time.Now()
if _, err := client.Predict(context.Background(), PredictRequest{}); err == nil {
t.Fatal("expected a timeout error")
}
if elapsed := time.Since(start); elapsed > time.Second {
t.Fatalf("timeout took %s", elapsed)
}
}
func TestSimulate(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var req SimulateRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
t.Errorf("decode: %v", err)
}
if req.Scenario != "rainy-saturday" || req.Sensors != "all" {
t.Errorf("request=%+v", req)
}
_, _ = w.Write([]byte(`{"scenario":"rainy-saturday","generated_at":"2026-11-14T09:12:00Z","forecasts":{"hn-bahnhof-01":{"7d":[{"t":"2026-11-16T09:00:00Z","v":5,"lo":4,"hi":6}]}}}`))
}))
defer srv.Close()
forecasts, err := New(srv.URL, time.Second).Simulate(context.Background(), SimulateRequest{
Scenario: "rainy-saturday", Sensors: "all",
})
if err != nil {
t.Fatalf("Simulate: %v", err)
}
points := forecasts["hn-bahnhof-01"]["7d"]
if len(points) != 1 || points[0].V != 5 {
t.Fatalf("forecasts=%+v", forecasts)
}
if _, ok := forecasts["missing"]; ok {
t.Fatal("unexpected sensor")
}
}
func TestNewUsesDefaultTimeout(t *testing.T) {
client := New("http://example.invalid", 0)
if client.http.Timeout != DefaultTimeout {
t.Fatalf("timeout=%s, want %s", client.http.Timeout, DefaultTimeout)
}
}
func TestTrainForwardsBodyContentTypeAndStatus(t *testing.T) {
var gotMethod, gotPath, gotType, gotBody string
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
gotMethod, gotPath = r.Method, r.URL.Path
gotType = r.Header.Get("Content-Type")
raw, _ := io.ReadAll(r.Body)
gotBody = string(raw)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusAccepted)
_, _ = w.Write([]byte(`{"job_id":"job-1","status":"queued","model":"small"}`))
}))
defer srv.Close()
status, body, err := New(srv.URL, time.Second).Train(context.Background(), "application/json",
strings.NewReader(`{"path":"/tmp/new.csv","model":"small"}`))
if err != nil {
t.Fatalf("Train: %v", err)
}
if status != http.StatusAccepted {
t.Fatalf("status=%d, want 202", status)
}
if !strings.Contains(string(body), `"job_id":"job-1"`) {
t.Fatalf("body=%s", body)
}
if gotMethod != http.MethodPost || gotPath != "/train" {
t.Fatalf("request=%s %s, want POST /train", gotMethod, gotPath)
}
if gotType != "application/json" || !strings.Contains(gotBody, "/tmp/new.csv") {
t.Fatalf("content-type=%q body=%q", gotType, gotBody)
}
}
func TestControlRequestsForwardBearerToken(t *testing.T) {
var got []string
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
got = append(got, r.Header.Get("Authorization"))
w.Header().Set("Content-Type", "application/json")
if r.Method == http.MethodPost {
w.WriteHeader(http.StatusAccepted)
}
_, _ = w.Write([]byte(`{"job_id":"job-1","status":"queued"}`))
}))
defer srv.Close()
client := NewWithToken(srv.URL, time.Second, "token-123")
if _, _, err := client.Train(context.Background(), "application/json", strings.NewReader(`{"path":"/tmp/x.csv"}`)); err != nil {
t.Fatalf("Train: %v", err)
}
if _, _, err := client.TrainStatus(context.Background(), "job-1"); err != nil {
t.Fatalf("TrainStatus: %v", err)
}
for i, auth := range got {
if auth != "Bearer token-123" {
t.Errorf("request %d Authorization=%q, want Bearer token-123", i, auth)
}
}
}
func TestTrainStatusForwardsJobIDAndUpstreamError(t *testing.T) {
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)
}
if r.URL.Path == "/train/job-1" {
_, _ = w.Write([]byte(`{"job_id":"job-1","status":"succeeded","error":null}`))
return
}
w.WriteHeader(http.StatusNotFound)
_, _ = w.Write([]byte(`{"detail":"job not found"}`))
}))
defer srv.Close()
client := New(srv.URL, time.Second)
status, body, err := client.TrainStatus(context.Background(), "job-1")
if err != nil {
t.Fatalf("TrainStatus: %v", err)
}
if status != http.StatusOK || !strings.Contains(string(body), `"succeeded"`) {
t.Fatalf("status=%d body=%s", status, body)
}
status, body, err = client.TrainStatus(context.Background(), "missing")
if err != nil {
t.Fatalf("TrainStatus missing: %v", err)
}
if status != http.StatusNotFound || !strings.Contains(string(body), "job not found") {
t.Fatalf("status=%d body=%s, want forwarded 404", status, body)
}
}
+248
View File
@@ -0,0 +1,248 @@
// Package model contains the wire types shared by the HTTP handlers, the
// baked-data store and the FastAPI client. JSON tags mirror CONTRACT.md.
package model
import "time"
// Horizons and enums from CONTRACT.md §1.
var (
Horizons = []string{"15m", "1h", "48h", "7d"}
Scenarios = []string{"base", "sunny-saturday-market", "rainy-saturday", "weekday-event"}
Standards = []string{"relaxed", "standard", "premium"}
)
// Contains reports whether v is in list.
func Contains(list []string, v string) bool {
for _, item := range list {
if item == v {
return true
}
}
return false
}
// Sensor is one row of GET /api/sensors.
type Sensor struct {
ID string `json:"id"`
Name string `json:"name"`
Lat float64 `json:"lat"`
Lon float64 `json:"lon"`
Mean float64 `json:"mean"`
P95 float64 `json:"p95"`
Battery *int `json:"battery"`
}
// Point is one observed series point.
type Point struct {
T time.Time `json:"t"`
V float64 `json:"v"`
}
// ForecastPoint is one forecast point with its 80% band.
type ForecastPoint struct {
T time.Time `json:"t"`
V float64 `json:"v"`
Lo float64 `json:"lo"`
Hi float64 `json:"hi"`
}
// Coverage describes the training/observation window.
type Coverage struct {
Sensors int `json:"sensors"`
From string `json:"from"`
To string `json:"to"`
CadenceMin int `json:"cadence_min"`
}
// Metrics is the model card headline block exposed by GET /api/meta.
type Metrics struct {
Model string `json:"model"`
MAE float64 `json:"mae"`
WAPE float64 `json:"wape"`
R2 float64 `json:"r2"`
BaselineMAE float64 `json:"baseline_mae"`
BaselineWAPE float64 `json:"baseline_wape"`
}
// Meta is GET /api/meta.
type Meta struct {
DataVersion string `json:"data_version"`
ModelVersion string `json:"model_version"`
ContextVersion string `json:"context_version"`
Coverage Coverage `json:"coverage"`
Metrics Metrics `json:"metrics"`
Limits []string `json:"limits"`
}
// WeatherNow is the current conditions block.
type WeatherNow struct {
T time.Time `json:"t"`
TempC float64 `json:"temp_c"`
PrecipMM float64 `json:"precip_mm"`
CloudPct int `json:"cloud_pct"`
WindKMH float64 `json:"wind_kmh"`
HumidityPct int `json:"humidity_pct"`
}
// WeatherPoint is one forecast hour.
type WeatherPoint struct {
T time.Time `json:"t"`
TempC float64 `json:"temp_c"`
PrecipMM float64 `json:"precip_mm"`
CloudPct int `json:"cloud_pct"`
WindKMH float64 `json:"wind_kmh"`
HumidityPct int `json:"humidity_pct"`
}
// Weather groups current conditions and the hourly forecast.
type Weather struct {
Now WeatherNow `json:"now"`
Forecast []WeatherPoint `json:"forecast"`
}
// Holiday is one public holiday (Baden-Württemberg).
type Holiday struct {
Date string `json:"date"`
Name string `json:"name"`
}
// ContextData is the stored context artifact.
type ContextData struct {
Weather Weather `json:"weather"`
Holidays []Holiday `json:"holidays"`
UpdatedAt time.Time `json:"updated_at"`
}
// ContextResponse is GET /api/context.
type ContextResponse struct {
Weather Weather `json:"weather"`
Holidays []Holiday `json:"holidays"`
UpdatedAt time.Time `json:"updated_at"`
Cached bool `json:"cached"`
}
// WeatherInput is the scenario weather override.
type WeatherInput struct {
TempDeltaC float64 `json:"temp_delta_c"`
PrecipMM float64 `json:"precip_mm"`
}
// EventInput is the scenario event override.
type EventInput struct {
Type string `json:"type"`
Uplift float64 `json:"uplift"`
}
// ScenarioInput is the scenario body from POST /api/scenario.
type ScenarioInput struct {
Scenario string `json:"scenario"`
Weather WeatherInput `json:"weather"`
Event EventInput `json:"event"`
}
// ScenarioState is the current scenario plus its version.
type ScenarioState struct {
Version int `json:"version"`
Scenario ScenarioInput `json:"scenario"`
At time.Time `json:"at"`
}
// ForecastResponse is GET /api/forecast.
type ForecastResponse struct {
Sensor string `json:"sensor"`
Horizon string `json:"horizon"`
Scenario string `json:"scenario"`
Points []ForecastPoint `json:"points"`
Cached bool `json:"cached"`
DataVersion string `json:"data_version"`
ModelVersion string `json:"model_version"`
ContextVersion string `json:"context_version"`
}
// Staffing assumptions, echoed in every plan.
const (
VisitorsPerStaffRelaxed = 35
VisitorsPerStaffStandard = 25
VisitorsPerStaffPremium = 18
SafetyFactor = 1.15
MinStaff = 1
ShiftLengthHours = 4
LaborCostEURPerHour = 16
)
// StoreHours are local Europe/Berlin opening hours.
var StoreHours = struct {
Open int
Close int
TZ string
}{Open: 10, Close: 20, TZ: "Europe/Berlin"}
// StaffingAssumptions is echoed in the plan so the UI can show them.
type StaffingAssumptions struct {
VisitorsPerStaffHour int `json:"visitors_per_staff_hour"`
SafetyFactor float64 `json:"safety_factor"`
MinStaff int `json:"min_staff"`
ShiftLengthH int `json:"shift_length_h"`
LaborCostEURH int `json:"labor_cost_eur_h"`
StoreHours StoreHoursSpec `json:"store_hours"`
}
// StoreHoursSpec is the display form of the opening hours.
type StoreHoursSpec struct {
Open string `json:"open"`
Close string `json:"close"`
TZ string `json:"tz"`
}
// StaffingHour is one hour of the plan.
type StaffingHour struct {
T time.Time `json:"t"`
Footfall float64 `json:"footfall"`
RequiredStaff int `json:"required_staff"`
ScheduledStaff int `json:"scheduled_staff"`
Coverage string `json:"coverage"`
}
// Shift is one contiguous shift block.
type Shift struct {
Date string `json:"date"`
Start string `json:"start"`
End string `json:"end"`
Staff int `json:"staff"`
}
// StaffingSummary is the plan headline block.
type StaffingSummary struct {
CoveragePct float64 `json:"coverage_pct"`
CostEUR int `json:"cost_eur"`
FlatScheduleCostEUR int `json:"flat_schedule_cost_eur"`
OverstaffedHours int `json:"overstaffed_hours"`
UnderstaffedHours int `json:"understaffed_hours"`
}
// StaffingResponse is GET /api/staffing.
type StaffingResponse struct {
Sensor string `json:"sensor"`
Scenario string `json:"scenario"`
Standard string `json:"standard"`
Assumptions StaffingAssumptions `json:"assumptions"`
Hours []StaffingHour `json:"hours"`
Shifts []Shift `json:"shifts"`
Summary StaffingSummary `json:"summary"`
Why []string `json:"why"`
Cached bool `json:"cached"`
DataVersion string `json:"data_version"`
ModelVersion string `json:"model_version"`
ContextVersion string `json:"context_version"`
}
// ErrorBody is the canonical error envelope.
type ErrorBody struct {
Error ErrorDetail `json:"error"`
}
// ErrorDetail is the inner error object.
type ErrorDetail struct {
Code string `json:"code"`
Message string `json:"message"`
}
+47
View File
@@ -0,0 +1,47 @@
// Package scenario holds the single in-memory scenario state.
package scenario
import (
"sync"
"time"
"pulsecast/api/internal/model"
)
// State is safe for concurrent readers and writers.
type State struct {
mu sync.RWMutex
current model.ScenarioState
}
// New returns the initial base scenario at version 1.
func New() *State {
return &State{current: model.ScenarioState{
Version: 1,
Scenario: model.ScenarioInput{
Scenario: "base",
Weather: model.WeatherInput{},
Event: model.EventInput{},
},
At: time.Now().UTC().Truncate(time.Second),
}}
}
// Get returns a consistent snapshot.
func (s *State) Get() model.ScenarioState {
s.mu.RLock()
defer s.mu.RUnlock()
return s.current
}
// Set stores a new scenario and returns its snapshot.
func (s *State) Set(in model.ScenarioInput) model.ScenarioState {
s.mu.Lock()
defer s.mu.Unlock()
s.current = model.ScenarioState{
Version: s.current.Version + 1,
Scenario: in,
At: time.Now().UTC().Truncate(time.Second),
}
return s.current
}
+50
View File
@@ -0,0 +1,50 @@
package scenario
import (
"sync"
"testing"
"pulsecast/api/internal/model"
)
func TestNewAndSet(t *testing.T) {
state := New()
initial := state.Get()
if initial.Version != 1 || initial.Scenario.Scenario != "base" {
t.Fatalf("initial state=%+v", initial)
}
if initial.At.IsZero() {
t.Fatal("initial timestamp is zero")
}
next := state.Set(model.ScenarioInput{
Scenario: "sunny-saturday-market",
Weather: model.WeatherInput{TempDeltaC: 4, PrecipMM: 0},
Event: model.EventInput{Type: "market", Uplift: 0.2},
})
if next.Version != 2 || next.Scenario.Scenario != "sunny-saturday-market" {
t.Fatalf("next state=%+v", next)
}
if got := state.Get(); got.Version != 2 || got.Scenario.Weather.TempDeltaC != 4 {
t.Fatalf("Get after Set=%+v", got)
}
}
func TestConcurrentSetProducesUniqueVersions(t *testing.T) {
state := New()
const writers = 50
var wg sync.WaitGroup
wg.Add(writers)
for i := 0; i < writers; i++ {
go func() {
defer wg.Done()
state.Set(model.ScenarioInput{Scenario: "base"})
}()
}
wg.Wait()
if got := state.Get().Version; got != writers+1 {
t.Fatalf("version=%d, want %d", got, writers+1)
}
}
+92
View File
@@ -0,0 +1,92 @@
// Package sse is a small fan-out hub for Server-Sent Events.
package sse
import (
"context"
"encoding/json"
"sync"
"time"
)
// Event is one SSE message. ID is omitted when zero.
type Event struct {
Name string
ID int
Data []byte
}
// Hub fans events out to every subscribed client and emits a heartbeat.
type Hub struct {
heartbeat time.Duration
mu sync.RWMutex
clients map[chan Event]struct{}
}
// NewHub returns a hub that pings every heartbeat (15 s in production).
func NewHub(heartbeat time.Duration) *Hub {
if heartbeat <= 0 {
heartbeat = 15 * time.Second
}
return &Hub{
heartbeat: heartbeat,
clients: make(map[chan Event]struct{}),
}
}
// Run emits heartbeats until ctx is cancelled.
func (h *Hub) Run(ctx context.Context) {
ticker := time.NewTicker(h.heartbeat)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
data, _ := json.Marshal(map[string]string{"t": time.Now().UTC().Truncate(time.Second).Format(time.RFC3339)})
h.send(Event{Name: "ping", Data: data})
}
}
}
// Subscribe registers a client. The returned cancel function must be called
// when the request ends. The channel is never closed; cancelling drops it.
func (h *Hub) Subscribe() (<-chan Event, func()) {
ch := make(chan Event, 16)
h.mu.Lock()
h.clients[ch] = struct{}{}
h.mu.Unlock()
var once sync.Once
cancel := func() {
once.Do(func() {
h.mu.Lock()
delete(h.clients, ch)
h.mu.Unlock()
})
}
return ch, cancel
}
// Broadcast queues an event for every client. Slow clients drop the event
// rather than blocking the broadcaster; scenario state is versioned and can
// always be re-read with GET /api/scenario.
func (h *Hub) Broadcast(event Event) { h.send(event) }
func (h *Hub) send(event Event) {
h.mu.RLock()
defer h.mu.RUnlock()
for ch := range h.clients {
select {
case ch <- event:
default:
}
}
}
// Clients reports the number of subscribed clients.
func (h *Hub) Clients() int {
h.mu.RLock()
defer h.mu.RUnlock()
return len(h.clients)
}
+133
View File
@@ -0,0 +1,133 @@
package sse
import (
"context"
"encoding/json"
"testing"
"time"
)
func TestBroadcastDeliversToAllAndUnsubscribe(t *testing.T) {
hub := NewHub(time.Hour)
first, cancelFirst := hub.Subscribe()
second, cancelSecond := hub.Subscribe()
defer cancelSecond()
if got := hub.Clients(); got != 2 {
t.Fatalf("clients=%d, want 2", got)
}
hub.Broadcast(Event{Name: "scenario", ID: 3, Data: []byte(`{"version":3}`)})
for i, ch := range []<-chan Event{first, second} {
select {
case event := <-ch:
if event.Name != "scenario" || event.ID != 3 || string(event.Data) != `{"version":3}` {
t.Fatalf("client %d event=%+v", i, event)
}
case <-time.After(time.Second):
t.Fatalf("client %d timed out", i)
}
}
cancelFirst()
if got := hub.Clients(); got != 1 {
t.Fatalf("clients after unsubscribe=%d, want 1", got)
}
hub.Broadcast(Event{Name: "scenario", ID: 4})
select {
case event := <-second:
if event.ID != 4 {
t.Fatalf("second client event=%+v", event)
}
case <-time.After(time.Second):
t.Fatal("second client timed out")
}
}
func TestSlowClientDropsInsteadOfBlocking(t *testing.T) {
hub := NewHub(time.Hour)
slow, cancel := hub.Subscribe()
defer cancel()
// A subscriber that never reads must not stall the broadcaster.
done := make(chan struct{})
go func() {
for i := 1; i <= 20; i++ {
hub.Broadcast(Event{Name: "scenario", ID: i})
}
close(done)
}()
select {
case <-done:
case <-time.After(time.Second):
t.Fatal("Broadcast blocked on a slow client")
}
// The channel buffer is 16, so the first 16 events survive and the rest
// are dropped. State is versioned and re-readable, so a drop is safe.
for i := 1; i <= 16; i++ {
select {
case event := <-slow:
if event.ID != i {
t.Fatalf("buffered event %d has id=%d", i, event.ID)
}
default:
t.Fatalf("expected event %d to be buffered", i)
}
}
select {
case event := <-slow:
t.Fatalf("unexpected extra event %+v", event)
default:
}
}
func TestHeartbeat(t *testing.T) {
hub := NewHub(10 * time.Millisecond)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
go hub.Run(ctx)
events, unsubscribe := hub.Subscribe()
defer unsubscribe()
select {
case event := <-events:
if event.Name != "ping" {
t.Fatalf("event=%+v, want ping", event)
}
var payload map[string]string
if err := json.Unmarshal(event.Data, &payload); err != nil {
t.Fatalf("decode ping: %v", err)
}
if _, err := time.Parse(time.RFC3339, payload["t"]); err != nil {
t.Fatalf("ping time %q: %v", payload["t"], err)
}
case <-time.After(time.Second):
t.Fatal("no heartbeat within 1s")
}
}
func TestManyClients(t *testing.T) {
hub := NewHub(time.Hour)
const clients = 120
channels := make([]<-chan Event, clients)
cancels := make([]func(), clients)
for i := range channels {
channels[i], cancels[i] = hub.Subscribe()
defer cancels[i]()
}
hub.Broadcast(Event{Name: "scenario", ID: 9})
for i, ch := range channels {
select {
case event := <-ch:
if event.ID != 9 {
t.Fatalf("client %d event=%+v", i, event)
}
case <-time.After(time.Second):
t.Fatalf("client %d timed out", i)
}
}
}
+323
View File
@@ -0,0 +1,323 @@
// Package staffing implements the deterministic decision heuristic from
// CONTRACT.md §5. It never calls the model: it consumes forecast points and
// turns them into an explainable shift plan.
package staffing
import (
"fmt"
"math"
"sort"
"time"
"pulsecast/api/internal/model"
)
// Build creates a plan for one sensor/scenario/standard.
func Build(sensor, scenario, standard string, points []model.ForecastPoint, ctx model.ContextData) (model.StaffingResponse, error) {
perStaff, ok := visitorsPerStaff(standard)
if !ok {
return model.StaffingResponse{}, fmt.Errorf("unknown standard %q", standard)
}
loc, err := time.LoadLocation(model.StoreHours.TZ)
if err != nil {
return model.StaffingResponse{}, fmt.Errorf("load timezone: %w", err)
}
days, err := groupStoreHours(points, loc)
if err != nil {
return model.StaffingResponse{}, err
}
assumptions := model.StaffingAssumptions{
VisitorsPerStaffHour: perStaff,
SafetyFactor: model.SafetyFactor,
MinStaff: model.MinStaff,
ShiftLengthH: model.ShiftLengthHours,
LaborCostEURH: model.LaborCostEURPerHour,
StoreHours: model.StoreHoursSpec{
Open: "10:00",
Close: "20:00",
TZ: model.StoreHours.TZ,
},
}
var hours []model.StaffingHour
var shifts []model.Shift
requiredByDate := make(map[string][]int)
totalCost := 0.0
for _, day := range days {
// Required staff per hour first; blocks need maxima across the day.
required := make(map[int]int, len(day.hours))
for _, h := range day.hours {
req := int(math.Ceil(math.Max(0, h.point.V) / float64(perStaff) * model.SafetyFactor))
if req < model.MinStaff {
req = model.MinStaff
}
required[h.hour] = req
requiredByDate[day.date] = append(requiredByDate[day.date], req)
}
scheduled := make(map[int]int, len(day.hours))
for _, block := range blocks(day.hours) {
staff := 0
for _, h := range block.hours {
if req := required[h.hour]; req > staff {
staff = req
}
}
for _, h := range block.hours {
scheduled[h.hour] = staff
}
shifts = append(shifts, model.Shift{
Date: day.date,
Start: clock(block.start),
End: clock(block.end),
Staff: staff,
})
totalCost += float64(staff) * float64(block.minutes()) / 60 * model.LaborCostEURPerHour
}
for _, h := range day.hours {
req := required[h.hour]
sched := scheduled[h.hour]
coverage := "ok"
switch {
case sched < req:
coverage = "under"
case sched > req:
coverage = "over"
}
hours = append(hours, model.StaffingHour{
T: h.point.T.UTC(),
Footfall: h.point.V,
RequiredStaff: req,
ScheduledStaff: sched,
Coverage: coverage,
})
}
}
if len(hours) == 0 {
return model.StaffingResponse{}, fmt.Errorf("no store-hour forecast points")
}
summary := summarise(hours, requiredByDate, totalCost, loc)
why := explain(days, ctx, scenario, loc)
return model.StaffingResponse{
Sensor: sensor,
Scenario: scenario,
Standard: standard,
Assumptions: assumptions,
Hours: hours,
Shifts: shifts,
Summary: summary,
Why: why,
}, nil
}
func visitorsPerStaff(standard string) (int, bool) {
switch standard {
case "relaxed":
return model.VisitorsPerStaffRelaxed, true
case "standard":
return model.VisitorsPerStaffStandard, true
case "premium":
return model.VisitorsPerStaffPremium, true
default:
return 0, false
}
}
type hourPoint struct {
hour int
point model.ForecastPoint
}
type dayPlan struct {
date string
hours []hourPoint
}
// groupStoreHours keeps only points that fall inside 10:00–20:00 local time,
// first seven local dates, sorted chronologically.
func groupStoreHours(points []model.ForecastPoint, loc *time.Location) ([]dayPlan, error) {
type key struct {
date string
hour int
}
seen := make(map[key]model.ForecastPoint)
var dates []string
dateSet := make(map[string]bool)
for _, point := range points {
local := point.T.In(loc)
if local.Hour() < model.StoreHours.Open || local.Hour() >= model.StoreHours.Close {
continue
}
k := key{date: local.Format("2006-01-02"), hour: local.Hour()}
seen[k] = point
if !dateSet[k.date] {
dateSet[k.date] = true
dates = append(dates, k.date)
}
}
sort.Strings(dates)
if len(dates) > 7 {
dates = dates[:7]
}
days := make([]dayPlan, 0, len(dates))
for _, date := range dates {
day := dayPlan{date: date}
for hour := model.StoreHours.Open; hour < model.StoreHours.Close; hour++ {
if point, ok := seen[key{date: date, hour: hour}]; ok {
day.hours = append(day.hours, hourPoint{hour: hour, point: point})
}
}
// A day is only usable if every store hour has a forecast point.
if len(day.hours) == model.StoreHours.Close-model.StoreHours.Open {
days = append(days, day)
}
}
if len(days) == 0 {
return nil, fmt.Errorf("no complete store-day in forecast")
}
return days, nil
}
type block struct {
start int // local hour
end int // local hour, exclusive
hours []hourPoint
}
func (b block) minutes() int { return (b.end - b.start) * 60 }
// blocks walks the store day in 4-hour chunks; the final chunk is shorter
// (18:00–20:00) rather than extending past closing time.
func blocks(hours []hourPoint) []block {
var out []block
for start := model.StoreHours.Open; start < model.StoreHours.Close; start += model.ShiftLengthHours {
end := start + model.ShiftLengthHours
if end > model.StoreHours.Close {
end = model.StoreHours.Close
}
var inBlock []hourPoint
for _, h := range hours {
if h.hour >= start && h.hour < end {
inBlock = append(inBlock, h)
}
}
if len(inBlock) > 0 {
out = append(out, block{start: start, end: end, hours: inBlock})
}
}
return out
}
func summarise(hours []model.StaffingHour, requiredByDate map[string][]int, totalCost float64, loc *time.Location) model.StaffingSummary {
covered := 0
over := 0
under := 0
for _, h := range hours {
switch {
case h.ScheduledStaff >= h.RequiredStaff:
covered++
}
if h.ScheduledStaff > h.RequiredStaff {
over++
}
if h.ScheduledStaff < h.RequiredStaff {
under++
}
}
maxRequired := 0
for _, reqs := range requiredByDate {
for _, req := range reqs {
if req > maxRequired {
maxRequired = req
}
}
}
flatCost := float64(maxRequired) * float64(len(hours)) * model.LaborCostEURPerHour
coveragePct := 0.0
if len(hours) > 0 {
coveragePct = math.Round(float64(covered)/float64(len(hours))*1000) / 10
}
return model.StaffingSummary{
CoveragePct: coveragePct,
CostEUR: int(math.Round(totalCost)),
FlatScheduleCostEUR: int(math.Round(flatCost)),
OverstaffedHours: over,
UnderstaffedHours: under,
}
}
// explain names the observable weather/holiday context and the scenario
// assumptions. It does not claim causality.
func explain(days []dayPlan, ctx model.ContextData, scenario string, loc *time.Location) []string {
if len(days) == 0 {
return nil
}
first, _ := time.ParseInLocation("2006-01-02", days[0].date, loc)
last, _ := time.ParseInLocation("2006-01-02", days[len(days)-1].date, loc)
var why []string
for _, holiday := range ctx.Holidays {
hDate, err := time.ParseInLocation("2006-01-02", holiday.Date, loc)
if err != nil {
continue
}
if !hDate.Before(first) && !hDate.After(last) {
why = append(why, "Public holiday: "+holiday.Name+" ("+holiday.Date+")")
}
}
var precip float64
var tempSum float64
var n int
for _, point := range ctx.Weather.Forecast {
local := point.T.In(loc)
day := local.Format("2006-01-02")
if day < days[0].date || day > days[len(days)-1].date {
continue
}
precip += point.PrecipMM
tempSum += point.TempC
n++
}
if n > 0 {
avg := tempSum / float64(n)
switch {
case precip >= 5:
why = append(why, fmt.Sprintf("Wet week in the forecast (%.1f mm)", precip))
case precip >= 0.5:
why = append(why, fmt.Sprintf("Some rain in the forecast (%.1f mm)", precip))
default:
why = append(why, "Mostly dry week in the forecast")
}
why = append(why, fmt.Sprintf("Average forecast temperature %.0f°C", avg))
}
switch scenario {
case "sunny-saturday-market":
why = append(why, "Scenario assumes a sunny Saturday market uplift")
case "rainy-saturday":
why = append(why, "Scenario assumes a rainy Saturday")
case "weekday-event":
why = append(why, "Scenario assumes a weekday evening event uplift")
default:
why = append(why, "Base scenario: no weather delta or event uplift")
}
return why
}
func clock(hour int) string {
return fmt.Sprintf("%02d:00", hour)
}
+138
View File
@@ -0,0 +1,138 @@
package staffing
import (
"strings"
"testing"
"time"
"pulsecast/api/internal/model"
)
func weekPoints(t *testing.T, values map[int]float64) []model.ForecastPoint {
t.Helper()
return weekPointsForDay(t, -1, values)
}
// weekPointsForDay builds seven days of store-hour points. Hour overrides apply
// only to day (0 = Monday), or to every day when day is negative.
func weekPointsForDay(t *testing.T, day int, values map[int]float64) []model.ForecastPoint {
t.Helper()
loc, err := time.LoadLocation(model.StoreHours.TZ)
if err != nil {
t.Fatal(err)
}
start := time.Date(2026, 11, 16, model.StoreHours.Open, 0, 0, 0, loc)
var points []model.ForecastPoint
for d := 0; d < 7; d++ {
for hour := 0; hour < model.StoreHours.Close-model.StoreHours.Open; hour++ {
v := 25.0
if override, ok := values[hour]; ok && (day < 0 || day == d) {
v = override
}
points = append(points, model.ForecastPoint{
T: start.AddDate(0, 0, d).Add(time.Duration(hour) * time.Hour).UTC(),
V: v,
})
}
}
return points
}
func TestBuildStandardWeek(t *testing.T) {
points := weekPoints(t, nil)
ctx := model.ContextData{
Holidays: []model.Holiday{{Date: "2026-11-18", Name: "Testtag"}},
}
plan, err := Build("hn-bahnhof-01", "base", "standard", points, ctx)
if err != nil {
t.Fatalf("Build: %v", err)
}
if len(plan.Hours) != 70 {
t.Fatalf("hours=%d, want 70", len(plan.Hours))
}
if len(plan.Shifts) != 21 {
t.Fatalf("shifts=%d, want 21", len(plan.Shifts))
}
if plan.Assumptions.VisitorsPerStaffHour != 25 {
t.Errorf("visitors per staff=%d", plan.Assumptions.VisitorsPerStaffHour)
}
for _, hour := range plan.Hours {
// ceil(25 / 25 * 1.15) = 2
if hour.RequiredStaff != 2 || hour.ScheduledStaff != 2 {
t.Fatalf("hour %s required=%d scheduled=%d, want 2/2", hour.T, hour.RequiredStaff, hour.ScheduledStaff)
}
if hour.Coverage != "ok" {
t.Fatalf("hour %s coverage=%q", hour.T, hour.Coverage)
}
}
// 7 days * 10 hours * 2 staff * 16 EUR.
if plan.Summary.CostEUR != 2240 {
t.Errorf("cost=%d, want 2240", plan.Summary.CostEUR)
}
if plan.Summary.FlatScheduleCostEUR != 2240 {
t.Errorf("flat cost=%d, want 2240", plan.Summary.FlatScheduleCostEUR)
}
if plan.Summary.CoveragePct != 100 || plan.Summary.OverstaffedHours != 0 || plan.Summary.UnderstaffedHours != 0 {
t.Errorf("summary=%+v", plan.Summary)
}
if len(plan.Why) == 0 || !strings.Contains(strings.Join(plan.Why, "\n"), "Testtag") {
t.Errorf("why=%v, want the holiday driver", plan.Why)
}
}
func TestBuildShiftBlocksAndPeak(t *testing.T) {
// One 19:00 peak on Monday only; the rest of the week stays flat at 25.
points := weekPointsForDay(t, 0, map[int]float64{9: 1000})
plan, err := Build("hn-bahnhof-01", "base", "standard", points, model.ContextData{})
if err != nil {
t.Fatalf("Build: %v", err)
}
if len(plan.Shifts) != 21 {
t.Fatalf("shifts=%d, want 21", len(plan.Shifts))
}
first := plan.Shifts[0]
if first.Date != "2026-11-16" || first.Start != "10:00" || first.End != "14:00" || first.Staff != 2 {
t.Errorf("first shift=%+v", first)
}
last := plan.Shifts[2]
if last.Start != "18:00" || last.End != "20:00" || last.Staff != 46 {
t.Errorf("peak shift=%+v, want 18:00-20:00 staff 46", last)
}
// The peak block overstaffs 18:00 while 19:00 is exactly covered.
if plan.Summary.OverstaffedHours != 1 {
t.Errorf("overstaffed=%d, want 1", plan.Summary.OverstaffedHours)
}
if plan.Summary.UnderstaffedHours != 0 {
t.Errorf("understaffed=%d, want 0", plan.Summary.UnderstaffedHours)
}
if plan.Summary.CoveragePct != 100 {
t.Errorf("coverage=%v, want 100", plan.Summary.CoveragePct)
}
wantCost := 6*10*2*16 + (4*2+4*2+2*46)*16
if plan.Summary.CostEUR != wantCost {
t.Errorf("cost=%d, want %d", plan.Summary.CostEUR, wantCost)
}
maxRequired := 46
wantFlat := maxRequired * 70 * 16
if plan.Summary.FlatScheduleCostEUR != wantFlat {
t.Errorf("flat cost=%d, want %d", plan.Summary.FlatScheduleCostEUR, wantFlat)
}
}
func TestBuildUnknownStandard(t *testing.T) {
if _, err := Build("s", "base", "luxury", weekPoints(t, nil), model.ContextData{}); err == nil {
t.Fatal("expected an error for an unknown standard")
}
}
func TestBuildRequiresACompleteStoreDay(t *testing.T) {
points := []model.ForecastPoint{{
T: time.Date(2026, 11, 16, 2, 0, 0, 0, time.UTC),
V: 10,
}}
if _, err := Build("s", "base", "standard", points, model.ContextData{}); err == nil {
t.Fatal("expected an error without store-hour points")
}
}
+189
View File
@@ -0,0 +1,189 @@
// Package store loads the baked JSON artifacts described in CONTRACT.md §4.
// The data is immutable after Load; all accessors are safe for concurrent use.
package store
import (
"encoding/json"
"errors"
"fmt"
"os"
"path/filepath"
"sort"
"strings"
"pulsecast/api/internal/model"
)
// Store is the in-memory baked dataset.
type Store struct {
meta model.Meta
sensors []model.Sensor
sensorBy map[string]model.Sensor
series map[string][]model.Point
forecasts map[string]map[string]map[string][]model.ForecastPoint
context model.ContextData
}
// Load reads every artifact from dir. It returns a usable (possibly partial)
// store together with a joined error so callers can start the API and let
// /api/readyz report 503 instead of crash-looping.
func Load(dir string) (*Store, error) {
s := &Store{
sensorBy: make(map[string]model.Sensor),
series: make(map[string][]model.Point),
forecasts: make(map[string]map[string]map[string][]model.ForecastPoint),
}
var errs []error
if err := readJSON(filepath.Join(dir, "sensors.json"), &s.sensors); err != nil {
errs = append(errs, err)
}
sort.Slice(s.sensors, func(i, j int) bool { return s.sensors[i].ID < s.sensors[j].ID })
for _, sensor := range s.sensors {
s.sensorBy[sensor.ID] = sensor
}
if err := readJSON(filepath.Join(dir, "metrics.json"), &s.meta); err != nil {
errs = append(errs, err)
}
if err := readJSON(filepath.Join(dir, "context.json"), &s.context); err != nil {
errs = append(errs, err)
}
if err := loadSeries(dir, s); err != nil {
errs = append(errs, err)
}
if err := readJSON(filepath.Join(dir, "forecasts.json"), &s.forecasts); err != nil {
errs = append(errs, err)
}
for sensorID, scenarios := range s.forecasts {
for scenario, horizons := range scenarios {
for horizon, points := range horizons {
sort.Slice(points, func(i, j int) bool { return points[i].T.Before(points[j].T) })
horizons[horizon] = points
}
scenarios[scenario] = horizons
}
s.forecasts[sensorID] = scenarios
}
return s, errors.Join(errs...)
}
func loadSeries(dir string, s *Store) error {
var errs []error
// Contract allows a single series.json mapping sensor id -> points.
var combined map[string][]model.Point
err := readJSON(filepath.Join(dir, "series.json"), &combined)
switch {
case err == nil:
for sensorID, points := range combined {
sort.Slice(points, func(i, j int) bool { return points[i].T.Before(points[j].T) })
s.series[sensorID] = points
}
case !errors.Is(err, os.ErrNotExist):
errs = append(errs, err)
}
// Contract also allows series/<id>.json; these override the combined file.
entries, err := os.ReadDir(filepath.Join(dir, "series"))
if err != nil {
if !errors.Is(err, os.ErrNotExist) {
errs = append(errs, fmt.Errorf("series dir: %w", err))
}
return errors.Join(errs...)
}
for _, entry := range entries {
if entry.IsDir() || !strings.HasSuffix(entry.Name(), ".json") {
continue
}
var points []model.Point
path := filepath.Join(dir, "series", entry.Name())
if err := readJSON(path, &points); err != nil {
errs = append(errs, err)
continue
}
sort.Slice(points, func(i, j int) bool { return points[i].T.Before(points[j].T) })
s.series[strings.TrimSuffix(entry.Name(), ".json")] = points
}
return errors.Join(errs...)
}
func readJSON(path string, dst any) error {
raw, err := os.ReadFile(path)
if err != nil {
return fmt.Errorf("read %s: %w", path, err)
}
if err := json.Unmarshal(raw, dst); err != nil {
return fmt.Errorf("decode %s: %w", path, err)
}
return nil
}
// Meta returns the model/data metadata.
func (s *Store) Meta() model.Meta { return s.meta }
// Sensors returns the sensors sorted by id.
func (s *Store) Sensors() []model.Sensor {
out := make([]model.Sensor, len(s.sensors))
copy(out, s.sensors)
return out
}
// Sensor looks up one sensor.
func (s *Store) Sensor(id string) (model.Sensor, bool) {
sensor, ok := s.sensorBy[id]
return sensor, ok
}
// Series returns the raw (15-minute) series for a sensor.
func (s *Store) Series(id string) ([]model.Point, bool) {
points, ok := s.series[id]
return points, ok
}
// Forecast returns baked points for sensor/scenario/horizon.
func (s *Store) Forecast(sensor, scenario, horizon string) ([]model.ForecastPoint, bool) {
scenarios, ok := s.forecasts[sensor]
if !ok {
return nil, false
}
horizons, ok := scenarios[scenario]
if !ok {
return nil, false
}
points, ok := horizons[horizon]
if !ok || len(points) == 0 {
return nil, false
}
return points, true
}
// Context returns the baked weather/holiday context.
func (s *Store) Context() model.ContextData { return s.context }
// Versions returns data, model and context version strings.
func (s *Store) Versions() (data, modelVersion, context string) {
return s.meta.DataVersion, s.meta.ModelVersion, s.meta.ContextVersion
}
// Ready reports whether the minimum baked set is present. FastAPI health is
// deliberately not part of readiness: the cache fallback is the safety net.
func (s *Store) Ready() bool {
if len(s.sensors) == 0 || s.meta.ModelVersion == "" || s.context.UpdatedAt.IsZero() {
return false
}
for _, sensor := range s.sensors {
if _, ok := s.Forecast(sensor.ID, "base", "7d"); ok {
return true
}
}
return false
}
// Len returns the number of loaded sensors (used in tests/logs).
func (s *Store) Len() int { return len(s.sensors) }
+65
View File
@@ -0,0 +1,65 @@
package store
import (
"testing"
)
func TestLoadFixtures(t *testing.T) {
st, err := Load("../../testdata/data")
if err != nil {
t.Fatalf("Load: %v", err)
}
if !st.Ready() {
t.Fatal("Ready()=false for the fixture dataset")
}
if st.Len() != 8 {
t.Fatalf("Len()=%d, want 8", st.Len())
}
sensors := st.Sensors()
for i := 1; i < len(sensors); i++ {
if sensors[i-1].ID >= sensors[i].ID {
t.Fatalf("sensors not sorted: %q then %q", sensors[i-1].ID, sensors[i].ID)
}
}
if _, ok := st.Sensor("hn-bahnhof-01"); !ok {
t.Fatal("missing hn-bahnhof-01")
}
if _, ok := st.Sensor("nope"); ok {
t.Fatal("unexpected sensor nope")
}
if points, ok := st.Series("hn-bahnhof-01"); !ok || len(points) == 0 {
t.Fatalf("series: ok=%v points=%d", ok, len(points))
}
if points, ok := st.Forecast("hn-bahnhof-01", "sunny-saturday-market", "7d"); !ok || len(points) != 168 {
t.Fatalf("forecast: ok=%v points=%d", ok, len(points))
}
if _, ok := st.Forecast("hn-bahnhof-01", "base", "2h"); ok {
t.Fatal("unexpected horizon 2h")
}
if ctx := st.Context(); ctx.UpdatedAt.IsZero() || len(ctx.Weather.Forecast) == 0 || len(ctx.Holidays) == 0 {
t.Fatalf("context incomplete: %+v", ctx)
}
data, modelVersion, context := st.Versions()
if data == "" || modelVersion == "" || context == "" {
t.Fatalf("versions: data=%q model=%q context=%q", data, modelVersion, context)
}
}
func TestLoadMissingDirectoryIsPartial(t *testing.T) {
st, err := Load(t.TempDir())
if err == nil {
t.Fatal("expected an error for an empty data dir")
}
if st == nil {
t.Fatal("Load returned a nil store; handlers need a usable store")
}
if st.Ready() {
t.Fatal("Ready()=true without data")
}
if st.Len() != 0 {
t.Fatalf("Len()=%d, want 0", st.Len())
}
}
+4
View File
@@ -0,0 +1,4 @@
{
"$schema": "https://opencode.ai/config.json",
"model": "opencode-go/deepseek-v4.1-flash"
}
+1
View File
@@ -0,0 +1 @@
{"weather":{"now":{"t":"2026-11-14T03:00:00Z","temp_c":8.9,"precip_mm":0.0,"cloud_pct":80,"wind_kmh":11.0,"humidity_pct":79},"forecast":[{"t":"2026-11-14T04:00:00Z","temp_c":2.6,"precip_mm":0.0,"cloud_pct":80,"wind_kmh":9.4,"humidity_pct":77},{"t":"2026-11-14T05:00:00Z","temp_c":3.3,"precip_mm":0.0,"cloud_pct":84,"wind_kmh":11.2,"humidity_pct":84},{"t":"2026-11-14T06:00:00Z","temp_c":4.2,"precip_mm":0.0,"cloud_pct":65,"wind_kmh":8.4,"humidity_pct":88},{"t":"2026-11-14T07:00:00Z","temp_c":5.3,"precip_mm":0.0,"cloud_pct":76,"wind_kmh":16.7,"humidity_pct":82},{"t":"2026-11-14T08:00:00Z","temp_c":6.5,"precip_mm":0.0,"cloud_pct":87,"wind_kmh":16.1,"humidity_pct":79},{"t":"2026-11-14T09:00:00Z","temp_c":7.7,"precip_mm":0.0,"cloud_pct":76,"wind_kmh":16.5,"humidity_pct":75},{"t":"2026-11-14T10:00:00Z","temp_c":8.8,"precip_mm":0.0,"cloud_pct":60,"wind_kmh":8.8,"humidity_pct":78},{"t":"2026-11-14T11:00:00Z","temp_c":9.7,"precip_mm":0.0,"cloud_pct":85,"wind_kmh":16.4,"humidity_pct":73},{"t":"2026-11-14T12:00:00Z","temp_c":10.4,"precip_mm":0.0,"cloud_pct":79,"wind_kmh":12.7,"humidity_pct":76},{"t":"2026-11-14T13:00:00Z","temp_c":10.8,"precip_mm":0.0,"cloud_pct":78,"wind_kmh":12.4,"humidity_pct":75},{"t":"2026-11-14T14:00:00Z","temp_c":11.0,"precip_mm":0.0,"cloud_pct":70,"wind_kmh":10.0,"humidity_pct":71},{"t":"2026-11-14T15:00:00Z","temp_c":10.8,"precip_mm":0.0,"cloud_pct":78,"wind_kmh":11.5,"humidity_pct":87},{"t":"2026-11-14T16:00:00Z","temp_c":10.4,"precip_mm":0.0,"cloud_pct":70,"wind_kmh":14.6,"humidity_pct":91},{"t":"2026-11-14T17:00:00Z","temp_c":9.7,"precip_mm":0.0,"cloud_pct":68,"wind_kmh":7.1,"humidity_pct":79},{"t":"2026-11-14T18:00:00Z","temp_c":8.8,"precip_mm":0.0,"cloud_pct":77,"wind_kmh":10.8,"humidity_pct":82},{"t":"2026-11-14T19:00:00Z","temp_c":7.7,"precip_mm":0.0,"cloud_pct":63,"wind_kmh":16.7,"humidity_pct":89},{"t":"2026-11-14T20:00:00Z","temp_c":6.5,"precip_mm":0.0,"cloud_pct":81,"wind_kmh":10.7,"humidity_pct":83},{"t":"2026-11-14T21:00:00Z","temp_c":5.3,"precip_mm":0.0,"cloud_pct":80,"wind_kmh":13.5,"humidity_pct":75},{"t":"2026-11-14T22:00:00Z","temp_c":4.2,"precip_mm":0.0,"cloud_pct":68,"wind_kmh":16.6,"humidity_pct":87},{"t":"2026-11-14T23:00:00Z","temp_c":3.3,"precip_mm":0.0,"cloud_pct":84,"wind_kmh":16.8,"humidity_pct":82},{"t":"2026-11-15T00:00:00Z","temp_c":2.6,"precip_mm":0.0,"cloud_pct":61,"wind_kmh":11.6,"humidity_pct":78},{"t":"2026-11-15T01:00:00Z","temp_c":2.2,"precip_mm":0.0,"cloud_pct":66,"wind_kmh":12.2,"humidity_pct":75},{"t":"2026-11-15T02:00:00Z","temp_c":2.0,"precip_mm":0.0,"cloud_pct":66,"wind_kmh":13.3,"humidity_pct":73},{"t":"2026-11-15T03:00:00Z","temp_c":2.2,"precip_mm":0.0,"cloud_pct":62,"wind_kmh":7.1,"humidity_pct":81},{"t":"2026-11-15T04:00:00Z","temp_c":2.6,"precip_mm":0.0,"cloud_pct":74,"wind_kmh":7.9,"humidity_pct":77},{"t":"2026-11-15T05:00:00Z","temp_c":3.3,"precip_mm":0.0,"cloud_pct":87,"wind_kmh":8.7,"humidity_pct":82},{"t":"2026-11-15T06:00:00Z","temp_c":4.2,"precip_mm":0.0,"cloud_pct":70,"wind_kmh":16.3,"humidity_pct":86},{"t":"2026-11-15T07:00:00Z","temp_c":5.3,"precip_mm":0.0,"cloud_pct":75,"wind_kmh":16.5,"humidity_pct":76},{"t":"2026-11-15T08:00:00Z","temp_c":6.5,"precip_mm":0.0,"cloud_pct":89,"wind_kmh":14.3,"humidity_pct":72},{"t":"2026-11-15T09:00:00Z","temp_c":7.7,"precip_mm":0.0,"cloud_pct":70,"wind_kmh":15.0,"humidity_pct":73},{"t":"2026-11-15T10:00:00Z","temp_c":8.8,"precip_mm":0.0,"cloud_pct":71,"wind_kmh":9.5,"humidity_pct":78},{"t":"2026-11-15T11:00:00Z","temp_c":9.7,"precip_mm":0.0,"cloud_pct":62,"wind_kmh":7.6,"humidity_pct":89},{"t":"2026-11-15T12:00:00Z","temp_c":10.4,"precip_mm":0.0,"cloud_pct":85,"wind_kmh":10.1,"humidity_pct":86},{"t":"2026-11-15T13:00:00Z","temp_c":10.8,"precip_mm":0.0,"cloud_pct":88,"wind_kmh":9.0,"humidity_pct":87},{"t":"2026-11-15T14:00:00Z","temp_c":11.0,"precip_mm":0.0,"cloud_pct":71,"wind_kmh":8.9,"humidity_pct":76},{"t":"2026-11-15T15:00:00Z","temp_c":10.8,"precip_mm":0.0,"cloud_pct":75,"wind_kmh":10.8,"humidity_pct":83},{"t":"2026-11-15T16:00:00Z","temp_c":10.4,"precip_mm":0.0,"cloud_pct":75,"wind_kmh":9.3,"humidity_pct":75},{"t":"2026-11-15T17:00:00Z","temp_c":9.7,"precip_mm":0.0,"cloud_pct":83,"wind_kmh":16.3,"humidity_pct":85},{"t":"2026-11-15T18:00:00Z","temp_c":8.8,"precip_mm":0.0,"cloud_pct":62,"wind_kmh":15.9,"humidity_pct":78},{"t":"2026-11-15T19:00:00Z","temp_c":7.7,"precip_mm":0.0,"cloud_pct":66,"wind_kmh":14.6,"humidity_pct":74},{"t":"2026-11-15T20:00:00Z","temp_c":6.5,"precip_mm":0.0,"cloud_pct":86,"wind_kmh":9.3,"humidity_pct":79},{"t":"2026-11-15T21:00:00Z","temp_c":5.3,"precip_mm":0.0,"cloud_pct":75,"wind_kmh":11.5,"humidity_pct":81},{"t":"2026-11-15T22:00:00Z","temp_c":4.2,"precip_mm":0.0,"cloud_pct":66,"wind_kmh":16.8,"humidity_pct":81},{"t":"2026-11-15T23:00:00Z","temp_c":3.3,"precip_mm":0.0,"cloud_pct":70,"wind_kmh":10.9,"humidity_pct":90},{"t":"2026-11-16T00:00:00Z","temp_c":2.6,"precip_mm":0.0,"cloud_pct":72,"wind_kmh":7.9,"humidity_pct":72},{"t":"2026-11-16T01:00:00Z","temp_c":2.2,"precip_mmLine truncated
+1
View File
@@ -0,0 +1 @@
{"hn-bahnhof-01":{"base":{"48h":[{"t":"2026-11-16T00:00:00Z","v":3.9,"lo":2.9,"hi":5.2},{"t":"2026-11-16T01:00:00Z","v":3.9,"lo":2.9,"hi":5.2},{"t":"2026-11-16T02:00:00Z","v":3.9,"lo":2.9,"hi":5.1},{"t":"2026-11-16T03:00:00Z","v":4.0,"lo":2.9,"hi":5.2},{"t":"2026-11-16T04:00:00Z","v":3.9,"lo":2.9,"hi":5.2},{"t":"2026-11-16T05:00:00Z","v":10.7,"lo":7.9,"hi":14.0},{"t":"2026-11-16T06:00:00Z","v":15.0,"lo":11.1,"hi":19.7},{"t":"2026-11-16T07:00:00Z","v":18.2,"lo":13.5,"hi":23.9},{"t":"2026-11-16T08:00:00Z","v":22.3,"lo":16.5,"hi":29.3},{"t":"2026-11-16T09:00:00Z","v":30.3,"lo":22.4,"hi":39.7},{"t":"2026-11-16T10:00:00Z","v":30.3,"lo":22.4,"hi":39.7},{"t":"2026-11-16T11:00:00Z","v":33.0,"lo":24.4,"hi":43.2},{"t":"2026-11-16T12:00:00Z","v":32.0,"lo":23.7,"hi":41.9},{"t":"2026-11-16T13:00:00Z","v":24.3,"lo":18.0,"hi":31.8},{"t":"2026-11-16T14:00:00Z","v":24.7,"lo":18.3,"hi":32.4},{"t":"2026-11-16T15:00:00Z","v":23.8,"lo":17.6,"hi":31.2},{"t":"2026-11-16T16:00:00Z","v":31.1,"lo":23.0,"hi":40.8},{"t":"2026-11-16T17:00:00Z","v":28.4,"lo":21.0,"hi":37.2},{"t":"2026-11-16T18:00:00Z","v":31.7,"lo":23.4,"hi":41.5},{"t":"2026-11-16T19:00:00Z","v":14.9,"lo":11.0,"hi":19.6},{"t":"2026-11-16T20:00:00Z","v":14.2,"lo":10.5,"hi":18.6},{"t":"2026-11-16T21:00:00Z","v":12.9,"lo":9.6,"hi":16.9},{"t":"2026-11-16T22:00:00Z","v":6.4,"lo":4.8,"hi":8.4},{"t":"2026-11-16T23:00:00Z","v":3.5,"lo":2.6,"hi":4.6},{"t":"2026-11-17T00:00:00Z","v":3.6,"lo":2.7,"hi":4.8},{"t":"2026-11-17T01:00:00Z","v":4.0,"lo":2.9,"hi":5.2},{"t":"2026-11-17T02:00:00Z","v":3.9,"lo":2.9,"hi":5.1},{"t":"2026-11-17T03:00:00Z","v":3.7,"lo":2.7,"hi":4.8},{"t":"2026-11-17T04:00:00Z","v":3.7,"lo":2.8,"hi":4.9},{"t":"2026-11-17T05:00:00Z","v":10.4,"lo":7.7,"hi":13.6},{"t":"2026-11-17T06:00:00Z","v":16.3,"lo":12.1,"hi":21.4},{"t":"2026-11-17T07:00:00Z","v":20.4,"lo":15.1,"hi":26.7},{"t":"2026-11-17T08:00:00Z","v":23.1,"lo":17.1,"hi":30.2},{"t":"2026-11-17T09:00:00Z","v":30.6,"lo":22.7,"hi":40.1},{"t":"2026-11-17T10:00:00Z","v":31.0,"lo":22.9,"hi":40.6},{"t":"2026-11-17T11:00:00Z","v":32.2,"lo":23.8,"hi":42.2},{"t":"2026-11-17T12:00:00Z","v":32.6,"lo":24.1,"hi":42.7},{"t":"2026-11-17T13:00:00Z","v":24.9,"lo":18.4,"hi":32.6},{"t":"2026-11-17T14:00:00Z","v":24.7,"lo":18.3,"hi":32.3},{"t":"2026-11-17T15:00:00Z","v":24.0,"lo":17.8,"hi":31.5},{"t":"2026-11-17T16:00:00Z","v":31.3,"lo":23.2,"hi":41.1},{"t":"2026-11-17T17:00:00Z","v":29.9,"lo":22.2,"hi":39.2},{"t":"2026-11-17T18:00:00Z","v":29.0,"lo":21.4,"hi":38.0},{"t":"2026-11-17T19:00:00Z","v":14.1,"lo":10.5,"hi":18.5},{"t":"2026-11-17T20:00:00Z","v":13.3,"lo":9.8,"hi":17.4},{"t":"2026-11-17T21:00:00Z","v":13.0,"lo":9.6,"hi":17.0},{"t":"2026-11-17T22:00:00Z","v":5.8,"lo":4.3,"hi":7.6},{"t":"2026-11-17T23:00:00Z","v":3.9,"lo":2.9,"hi":5.1}],"7d":[{"t":"2026-11-16T00:00:00Z","v":3.9,"lo":2.9,"hi":5.2},{"t":"2026-11-16T01:00:00Z","v":3.9,"lo":2.9,"hi":5.2},{"t":"2026-11-16T02:00:00Z","v":3.9,"lo":2.9,"hi":5.1},{"t":"2026-11-16T03:00:00Z","v":4.0,"lo":2.9,"hi":5.2},{"t":"2026-11-16T04:00:00Z","v":3.9,"lo":2.9,"hi":5.2},{"t":"2026-11-16T05:00:00Z","v":10.7,"lo":7.9,"hi":14.0},{"t":"2026-11-16T06:00:00Z","v":15.0,"lo":11.1,"hi":19.7},{"t":"2026-11-16T07:00:00Z","v":18.2,"lo":13.5,"hi":23.9},{"t":"2026-11-16T08:00:00Z","v":22.3,"lo":16.5,"hi":29.3},{"t":"2026-11-16T09:00:00Z","v":30.3,"lo":22.4,"hi":39.7},{"t":"2026-11-16T10:00:00Z","v":30.3,"lo":22.4,"hi":39.7},{"t":"2026-11-16T11:00:00Z","v":33.0,"lo":24.4,"hi":43.2},{"t":"2026-11-16T12:00:00Z","v":32.0,"lo":23.7,"hi":41.9},{"t":"2026-11-16T13:00:00Z","v":24.3,"lo":18.0,"hi":31.8},{"t":"2026-11-16T14:00:00Z","v":24.7,"lo":18.3,"hi":32.4},{"t":"2026-11-16T15:00:00Z","v":23.8,"lo":17.6,"hi":31.2},{"t":"2026-11-16T16:00:00Z","v":31.1,"lo":23.0,"hi":40.8},{"t":"2026-11-16T17:00:00Z","v":28.4,"lo":21.0,"hi":37.2},{"t":"2026-11-16T18:00:00Z","v":31.7,"lo":23.4,"hi":41.5},{"t":"2026-11-16T19:00:00Z","v":14.9,"lo":11.0,"hi":19.6},{"t":"2026-11-16T20:00:00Z","v":14.2,"lo":10.5,"hi":18.6},{"t":"2026-11-16T21:00:00Z","v":12.9,"lo":9.6,"hi":16.9},{"t":"2026-11-16T22:00:00Z","v":6.4,"lo":4.8,"hi":8.4},{"t":"2026-11-16T23:00:00Z","v":3.5,"lo":2.6,"hi":4.6},{"t":"2026-11-17T00:00:00Z","v":3.6,"lo":2.7,"hi":4.8},{"t":"2026-11-17T01:00:00Z","v":4.0,"lo":2.9,"hi":5.2},{"t":"2026-11-17T02:00:00Z","v":3.9,"lo":2.9,"hi":5.1},{"t":"2026-11-17T03:00:00Z","v":3.7,"lo":2.7,"hi":4.8},{"t":"2026-11-17T04:00:00Z","v":3.7,"lo":2.8,"hi":4.9},{"t":"2026-11-17T05:00:00Z","v":10.4,"lo":7.7,"hi":13.6},{"t":"2026-11-17T06:00:00Z","v":16.3,"lo":12.1,"hi":21.4},{"t":"2026-11-17T07:00:00Z","v":20.4,"lo":15.1,"hi":26.7},{"t":"2026-11-17T08:00:00Z","v":23.1,"lo":17.1,"hi":30.2},{"t":"2026-11-17T09:00:00Z","v":30.6,"lo":22.7,"hi":40.1},{"t":"2026-11-17T10:00:00Z","v":31.0,"lo":22.9,"hi":40.6},{"t":"2026-11-17T11:00:00Z","v":32.2,"lo":23.8,"hi":42.2},{"t":"2026-11-17T12:00:00Z","v":32.6,"lo":24.1,"hi":42.7},{"t":"2026-11-17T13:00:00Z","v":24.9,"lo":18.4,"hi":32.6},{"t":"2026-11-17T14:00:00Z","v":24.7,"lo":18.3,"hi":32.3}Line truncated
+24
View File
@@ -0,0 +1,24 @@
{
"data_version": "2026-11-07T23:51:00Z",
"model_version": "histgb-2026-11-14",
"context_version": "2026-11-14T03:00:00Z",
"coverage": {
"sensors": 8,
"from": "2026-06-12T00:00:00Z",
"to": "2026-11-07T23:51:00Z",
"cadence_min": 15
},
"metrics": {
"model": "weather",
"mae": 3.36,
"wape": 27.8,
"r2": 0.779,
"baseline_mae": 5.4,
"baseline_wape": 44.7
},
"limits": [
"estimated devices, not people",
"8 sensors in a 580 m cluster",
"observed weather in training; forecast weather in scenarios"
]
}
+74
View File
@@ -0,0 +1,74 @@
[
{
"id": "hn-bahnhof-01",
"name": "Bahnhof",
"lat": 49.1429,
"lon": 9.2076,
"mean": 24.2,
"p95": 88.2,
"battery": 71
},
{
"id": "hn-deutschhof-01",
"name": "Deutschhof",
"lat": 49.1397,
"lon": 9.2149,
"mean": 14.0,
"p95": 49.6,
"battery": null
},
{
"id": "hn-kaiserstrasse-01",
"name": "Kaiserstra\u00dfe",
"lat": 49.1419,
"lon": 9.2096,
"mean": 21.1,
"p95": 74.1,
"battery": 64
},
{
"id": "hn-marktplatz-01",
"name": "Marktplatz",
"lat": 49.1426,
"lon": 9.212,
"mean": 17.9,
"p95": 63.8,
"battery": 83
},
{
"id": "hn-neckar-01",
"name": "Neckarufer",
"lat": 49.1448,
"lon": 9.2087,
"mean": 9.4,
"p95": 35.4,
"battery": 92
},
{
"id": "hn-rathaus-01",
"name": "Rathaus",
"lat": 49.1422,
"lon": 9.2131,
"mean": 15.6,
"p95": 55.9,
"battery": 58
},
{
"id": "hn-stadtgalerie-01",
"name": "Stadtgalerie",
"lat": 49.1427,
"lon": 9.2109,
"mean": 22.6,
"p95": 67.2,
"battery": 87
},
{
"id": "hn-theater-01",
"name": "Theater",
"lat": 49.1402,
"lon": 9.2124,
"mean": 11.7,
"p95": 41.7,
"battery": 49
}
]
+1
View File
@@ -0,0 +1 @@
{"hn-bahnhof-01":[{"t":"2026-10-25T00:00:00Z","v":3.6},{"t":"2026-10-25T00:15:00Z","v":4.1},{"t":"2026-10-25T00:30:00Z","v":4.4},{"t":"2026-10-25T00:45:00Z","v":4.0},{"t":"2026-10-25T01:00:00Z","v":3.7},{"t":"2026-10-25T01:15:00Z","v":3.6},{"t":"2026-10-25T01:30:00Z","v":4.3},{"t":"2026-10-25T01:45:00Z","v":3.8},{"t":"2026-10-25T02:00:00Z","v":4.5},{"t":"2026-10-25T02:15:00Z","v":3.7},{"t":"2026-10-25T02:30:00Z","v":4.4},{"t":"2026-10-25T02:45:00Z","v":4.3},{"t":"2026-10-25T03:00:00Z","v":4.2},{"t":"2026-10-25T03:15:00Z","v":4.1},{"t":"2026-10-25T03:30:00Z","v":3.9},{"t":"2026-10-25T03:45:00Z","v":3.8},{"t":"2026-10-25T04:00:00Z","v":3.8},{"t":"2026-10-25T04:15:00Z","v":3.7},{"t":"2026-10-25T04:30:00Z","v":4.4},{"t":"2026-10-25T04:45:00Z","v":4.1},{"t":"2026-10-25T05:00:00Z","v":12.8},{"t":"2026-10-25T05:15:00Z","v":12.7},{"t":"2026-10-25T05:30:00Z","v":12.9},{"t":"2026-10-25T05:45:00Z","v":11.4},{"t":"2026-10-25T06:00:00Z","v":16.3},{"t":"2026-10-25T06:15:00Z","v":17.5},{"t":"2026-10-25T06:30:00Z","v":17.3},{"t":"2026-10-25T06:45:00Z","v":17.0},{"t":"2026-10-25T07:00:00Z","v":23.5},{"t":"2026-10-25T07:15:00Z","v":23.5},{"t":"2026-10-25T07:30:00Z","v":20.4},{"t":"2026-10-25T07:45:00Z","v":19.5},{"t":"2026-10-25T08:00:00Z","v":26.7},{"t":"2026-10-25T08:15:00Z","v":25.3},{"t":"2026-10-25T08:30:00Z","v":28.2},{"t":"2026-10-25T08:45:00Z","v":23.6},{"t":"2026-10-25T09:00:00Z","v":30.1},{"t":"2026-10-25T09:15:00Z","v":31.2},{"t":"2026-10-25T09:30:00Z","v":30.4},{"t":"2026-10-25T09:45:00Z","v":33.7},{"t":"2026-10-25T10:00:00Z","v":37.2},{"t":"2026-10-25T10:15:00Z","v":32.1},{"t":"2026-10-25T10:30:00Z","v":36.9},{"t":"2026-10-25T10:45:00Z","v":30.6},{"t":"2026-10-25T11:00:00Z","v":35.9},{"t":"2026-10-25T11:15:00Z","v":31.7},{"t":"2026-10-25T11:30:00Z","v":30.7},{"t":"2026-10-25T11:45:00Z","v":35.4},{"t":"2026-10-25T12:00:00Z","v":36.0},{"t":"2026-10-25T12:15:00Z","v":31.3},{"t":"2026-10-25T12:30:00Z","v":30.0},{"t":"2026-10-25T12:45:00Z","v":32.9},{"t":"2026-10-25T13:00:00Z","v":27.5},{"t":"2026-10-25T13:15:00Z","v":26.5},{"t":"2026-10-25T13:30:00Z","v":28.1},{"t":"2026-10-25T13:45:00Z","v":29.8},{"t":"2026-10-25T14:00:00Z","v":26.4},{"t":"2026-10-25T14:15:00Z","v":26.5},{"t":"2026-10-25T14:30:00Z","v":29.2},{"t":"2026-10-25T14:45:00Z","v":29.3},{"t":"2026-10-25T15:00:00Z","v":30.5},{"t":"2026-10-25T15:15:00Z","v":30.7},{"t":"2026-10-25T15:30:00Z","v":27.4},{"t":"2026-10-25T15:45:00Z","v":25.2},{"t":"2026-10-25T16:00:00Z","v":31.8},{"t":"2026-10-25T16:15:00Z","v":28.9},{"t":"2026-10-25T16:30:00Z","v":33.3},{"t":"2026-10-25T16:45:00Z","v":32.8},{"t":"2026-10-25T17:00:00Z","v":33.7},{"t":"2026-10-25T17:15:00Z","v":31.5},{"t":"2026-10-25T17:30:00Z","v":33.8},{"t":"2026-10-25T17:45:00Z","v":31.9},{"t":"2026-10-25T18:00:00Z","v":29.9},{"t":"2026-10-25T18:15:00Z","v":32.6},{"t":"2026-10-25T18:30:00Z","v":31.8},{"t":"2026-10-25T18:45:00Z","v":32.6},{"t":"2026-10-25T19:00:00Z","v":16.7},{"t":"2026-10-25T19:15:00Z","v":15.7},{"t":"2026-10-25T19:30:00Z","v":16.2},{"t":"2026-10-25T19:45:00Z","v":15.8},{"t":"2026-10-25T20:00:00Z","v":15.8},{"t":"2026-10-25T20:15:00Z","v":14.4},{"t":"2026-10-25T20:30:00Z","v":16.5},{"t":"2026-10-25T20:45:00Z","v":15.7},{"t":"2026-10-25T21:00:00Z","v":16.7},{"t":"2026-10-25T21:15:00Z","v":13.8},{"t":"2026-10-25T21:30:00Z","v":16.7},{"t":"2026-10-25T21:45:00Z","v":14.2},{"t":"2026-10-25T22:00:00Z","v":7.2},{"t":"2026-10-25T22:15:00Z","v":6.5},{"t":"2026-10-25T22:30:00Z","v":7.1},{"t":"2026-10-25T22:45:00Z","v":5.9},{"t":"2026-10-25T23:00:00Z","v":3.6},{"t":"2026-10-25T23:15:00Z","v":4.1},{"t":"2026-10-25T23:30:00Z","v":3.9},{"t":"2026-10-25T23:45:00Z","v":3.7},{"t":"2026-10-26T00:00:00Z","v":3.4},{"t":"2026-10-26T00:15:00Z","v":3.5},{"t":"2026-10-26T00:30:00Z","v":4.0},{"t":"2026-10-26T00:45:00Z","v":3.7},{"t":"2026-10-26T01:00:00Z","v":3.9},{"t":"2026-10-26T01:15:00Z","v":3.7},{"t":"2026-10-26T01:30:00Z","v":4.0},{"t":"2026-10-26T01:45:00Z","v":3.9},{"t":"2026-10-26T02:00:00Z","v":3.5},{"t":"2026-10-26T02:15:00Z","v":3.9},{"t":"2026-10-26T02:30:00Z","v":4.0},{"t":"2026-10-26T02:45:00Z","v":3.5},{"t":"2026-10-26T03:00:00Z","v":4.2},{"t":"2026-10-26T03:15:00Z","v":3.3},{"t":"2026-10-26T03:30:00Z","v":4.1},{"t":"2026-10-26T03:45:00Z","v":3.3},{"t":"2026-10-26T04:00:00Z","v":3.6},{"t":"2026-10-26T04:15:00Z","v":3.7},{"t":"2026-10-26T04:30:00Z","v":4.1},{"t":"2026-10-26T04:45:00Z","v":3.3},{"t":"2026-10-26T05:00:00Z","v":11.8},{"t":"2026-10-26T05:15:00Z","v":11.8},{"t":"2026-10-26T05:30:00Z","v":10.2},{"t":"2026-10-26T05:45:00Z","v":11.6},{"t":"2026-10-26T06:00:00Z","v":13.7},{"t":"2026-10-26T06:15:00Z","v":15.1},{"t":"2026-10-26T06:30:00Z","v":15.0},{"t":"2026-10-26T06:45:00Z","v":15.7},{"t":"2026-10-26T07:00:00Z","v":20.6},{"t":"2026-10-26T07:15:00Z","v":19.8},{"t":"2026-10-26T07:30:00Z","v":17.6},{"t":"2026-10-26T07:45:00Z","v":18.1},{"t":"2026-10-26T08:00:00Z","v":22.7},{"t":"2026-10-26T08:15:00Z","v":23.1},{"t":"2026-10-26T08:30:00Z","v":21.3},{"t":"2026-10-26T08:45:00Z","v":22.7},{"t":"2026-10Line truncated