chore: bootstrap api-go scaffold

This commit is contained in:
Noel Sabia committed 2026-11-14 04:16:22 +01:00
1 parent aa26549bd1
commit 907164f972
18 files changed
+1919

No files matched your search

+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
}
+183
View File
@@ -0,0 +1,183 @@
// 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"
"log/slog"
"net/http"
"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/staffing"
"pulsecast/api/internal/store"
)
// MLClient is the FastAPI surface the 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)
}
// 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("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/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 {
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)
})
}
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)
}