125 lines
3.7 KiB
Go
125 lines
3.7 KiB
Go
// 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"
|
|
"strings"
|
|
"time"
|
|
|
|
"pulsecast/api/internal/model"
|
|
)
|
|
|
|
// DefaultTimeout is the contract limit for a live prediction.
|
|
const DefaultTimeout = 1500 * time.Millisecond
|
|
|
|
// Client talks to the FastAPI ML service.
|
|
type Client struct {
|
|
baseURL string
|
|
http *http.Client
|
|
}
|
|
|
|
// New returns a client for baseURL (for example http://localhost:8000).
|
|
func New(baseURL string, timeout time.Duration) *Client {
|
|
if timeout <= 0 {
|
|
timeout = DefaultTimeout
|
|
}
|
|
return &Client{
|
|
baseURL: strings.TrimRight(baseURL, "/"),
|
|
http: &http.Client{Timeout: timeout},
|
|
}
|
|
}
|
|
|
|
// 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"`
|
|
}
|
|
|
|
// Predict calls POST /predict and returns the forecast points.
|
|
func (c *Client) Predict(ctx context.Context, req PredictRequest) ([]model.ForecastPoint, error) {
|
|
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 len(out.Points) == 0 {
|
|
return nil, fmt.Errorf("ml: predict returned no points")
|
|
}
|
|
return out.Points, nil
|
|
}
|
|
|
|
// 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
|
|
}
|
|
|
|
func (c *Client) post(ctx context.Context, path string, body, dst any) error {
|
|
raw, err := json.Marshal(body)
|
|
if err != nil {
|
|
return 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)
|
|
}
|
|
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)
|
|
}
|
|
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)))
|
|
}
|
|
if err := json.NewDecoder(io.LimitReader(resp.Body, 32<<20)).Decode(dst); err != nil {
|
|
return fmt.Errorf("ml: decode %s: %w", path, err)
|
|
}
|
|
return nil
|
|
}
|