Files
api-go/internal/api/server.go
T
Noel Sabia 7e9c2d9663
ci / check (push) Successful in 58s
ci / check (pull_request) Successful in 55s
feat: proxy PreZero priority endpoints to FastAPI
2026-11-14 17:50:53 +01:00

246 lines
8.2 KiB
Go

// Package api wires the HTTP handlers, scenario state, SSE hub and cache
// fallback into the Go service.
package api
import (
"context"
"encoding/json"
"io"
"log/slog"
"net/http"
"strings"
"sync"
"time"
"pulsecast/api/internal/cache"
"pulsecast/api/internal/config"
"pulsecast/api/internal/ml"
"pulsecast/api/internal/model"
"pulsecast/api/internal/scenario"
"pulsecast/api/internal/sse"
)
// 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)
}
// PreZeroClient is the optional FastAPI PreZero read-only surface. Like
// TrainClient it is separate so prediction-only stubs keep working.
type PreZeroClient interface {
PreZeroSummary(ctx context.Context) (int, []byte, error)
PreZeroPriority(ctx context.Context, priority string, limit, offset int) (int, []byte, error)
PreZeroContainer(ctx context.Context, locationID string) (int, []byte, error)
}
// Server holds process-wide state. One instance per pod.
type Server struct {
cfg config.Config
cache *cache.Cache
ml MLClient
prezero PreZeroClient
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
lastForecast map[string][]model.ForecastPoint // sensor|horizon|scenario -> last live points
}
// New builds a server. hub must be non-nil; main runs hub.Run.
func New(cfg config.Config, snapshots *cache.Cache, 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
}
var prezero PreZeroClient
if pc, ok := client.(PreZeroClient); ok {
prezero = pc
}
return &Server{
cfg: cfg,
cache: snapshots,
ml: client,
prezero: prezero,
hub: hub,
scenario: scenario.New(),
loc: loc,
now: time.Now,
staffing: make(map[string]model.StaffingResponse),
lastForecast: make(map[string][]model.ForecastPoint),
}
}
// 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/prezero/summary", s.handlePreZeroSummary)
mux.HandleFunc("GET /api/prezero/priority", s.handlePreZeroPriority)
mux.HandleFunc("GET /api/prezero/containers/{location_id}", s.handlePreZeroContainer)
mux.HandleFunc("GET /api/stream", s.handleStream)
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/prezero/summary": {"GET"},
"/api/prezero/priority": {"GET"},
"/api/stream": {"GET"},
}
// routeCheck keeps unknown routes and methods in the JSON error envelope;
// ServeMux would otherwise answer them in plain text.
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 && isPreZeroContainerPath(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, "/")
}
// isPreZeroContainerPath matches exactly one location id after
// /api/prezero/containers/.
func isPreZeroContainerPath(path string) bool {
locationID, found := strings.CutPrefix(path, "/api/prezero/containers/")
return found && locationID != "" && !strings.Contains(locationID, "/")
}
func joinMethods(methods []string) string {
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)
}
// meta snapshots the cache metadata once per response, so versions and the
// cache block cannot disagree when a refresh lands mid-request.
func (s *Server) meta() model.Meta {
if s.cache == nil {
return model.Meta{}
}
return s.cache.Meta()
}
// setVersions adds the contract's version headers.
func (s *Server) setVersions(w http.ResponseWriter) {
meta := s.meta()
w.Header().Set("X-Data-Version", meta.DataVersion)
w.Header().Set("X-Model-Version", meta.ModelVersion)
w.Header().Set("X-Context-Version", meta.ContextVersion)
}