feat: API skeleton, SSE, staffing and tests

This commit is contained in:
Noel Sabia committed 2026-11-14 04:23:43 +01:00
1 parent 907164f972
commit f284969a4b
14 files changed
+1355 -54

No files matched your search

+40 -24
View File
@@ -52,39 +52,43 @@ type WeatherInput struct {
// SimulateRequest mirrors CONTRACT.md §3 POST /simulate.
type SimulateRequest struct {
Scenario string `json:"scenario"`
Scenario string `json:"scenario"`
Weather model.WeatherInput `json:"weather"`
Sensors string `json:"sensors"`
Sensors string `json:"sensors"`
}
// Predict calls POST /predict and returns the forecast points.
// 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 := c.post(ctx, "/predict", req, &out); err != nil {
return nil, err
}
if out.Points == nil {
// The contract says "the same points array"; accept a bare array too.
var points []model.ForecastPoint
if err := c.post(ctx, "/predict", req, &points); err == nil && len(points) > 0 {
out.Points = 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
}
if len(out.Points) == 0 {
return nil, fmt.Errorf("ml: predict returned no points")
var points []model.ForecastPoint
if err := json.Unmarshal(raw, &points); err == nil && len(points) > 0 {
return points, nil
}
return out.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"`
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
@@ -96,29 +100,41 @@ func (c *Client) Simulate(ctx context.Context, req SimulateRequest) (map[string]
}
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 fmt.Errorf("ml: encode request: %w", err)
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 fmt.Errorf("ml: build request: %w", err)
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 fmt.Errorf("ml: %s: %w", path, err)
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 fmt.Errorf("ml: %s: status %d: %s", path, resp.StatusCode, strings.TrimSpace(string(snippet)))
return nil, fmt.Errorf("ml: %s: status %d: %s", path, resp.StatusCode, strings.TrimSpace(string(snippet)))
}
if err := json.NewDecoder(io.LimitReader(resp.Body, 32<<20)).Decode(dst); err != nil {
return fmt.Errorf("ml: decode %s: %w", path, err)
raw, err = io.ReadAll(io.LimitReader(resp.Body, 32<<20))
if err != nil {
return nil, fmt.Errorf("ml: read %s: %w", path, err)
}
return nil
return raw, nil
}
+127
View File
@@ -0,0 +1,127 @@
package ml
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"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)
}
}