// 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) }