chore: bootstrap api-go scaffold
This commit is contained in:
1 parent
aa26549bd1
commit
907164f972
18 files changed
+1919
No files matched your search
@@ -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,
|
||||
})
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
// Package config reads runtime configuration from the environment.
|
||||
package config
|
||||
|
||||
import (
|
||||
"os"
|
||||
"strconv"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Config is the process configuration.
|
||||
type Config struct {
|
||||
Addr string
|
||||
DataDir string
|
||||
FastAPIURL string
|
||||
ControlUser string
|
||||
ControlPass string
|
||||
Heartbeat time.Duration
|
||||
MLTimeout time.Duration
|
||||
}
|
||||
|
||||
// Load reads configuration from env with local-development defaults.
|
||||
// CONTROL_USER / CONTROL_PASS have no defaults: POST /api/scenario fails
|
||||
// closed when they are unset.
|
||||
func Load() Config {
|
||||
port := getenv("PORT", "8080")
|
||||
return Config{
|
||||
Addr: ":" + port,
|
||||
DataDir: getenv("DATA_DIR", "testdata/data"),
|
||||
FastAPIURL: getenv("FASTAPI_URL", "http://localhost:8000"),
|
||||
ControlUser: os.Getenv("CONTROL_USER"),
|
||||
ControlPass: os.Getenv("CONTROL_PASS"),
|
||||
Heartbeat: durationEnv("SSE_HEARTBEAT", 15*time.Second),
|
||||
MLTimeout: durationEnv("ML_TIMEOUT", 1500*time.Millisecond),
|
||||
}
|
||||
}
|
||||
|
||||
// ControlAuthConfigured reports whether both control credentials exist.
|
||||
func (c Config) ControlAuthConfigured() bool {
|
||||
return c.ControlUser != "" && c.ControlPass != ""
|
||||
}
|
||||
|
||||
func getenv(key, fallback string) string {
|
||||
if v := os.Getenv(key); v != "" {
|
||||
return v
|
||||
}
|
||||
return fallback
|
||||
}
|
||||
|
||||
func durationEnv(key string, fallback time.Duration) time.Duration {
|
||||
raw := os.Getenv(key)
|
||||
if raw == "" {
|
||||
return fallback
|
||||
}
|
||||
if d, err := time.ParseDuration(raw); err == nil && d > 0 {
|
||||
return d
|
||||
}
|
||||
// Also accept a plain number of seconds for operational convenience.
|
||||
if secs, err := strconv.Atoi(raw); err == nil && secs > 0 {
|
||||
return time.Duration(secs) * time.Second
|
||||
}
|
||||
return fallback
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
// 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
|
||||
}
|
||||
@@ -0,0 +1,248 @@
|
||||
// Package model contains the wire types shared by the HTTP handlers, the
|
||||
// baked-data store and the FastAPI client. JSON tags mirror CONTRACT.md.
|
||||
package model
|
||||
|
||||
import "time"
|
||||
|
||||
// Horizons and enums from CONTRACT.md §1.
|
||||
var (
|
||||
Horizons = []string{"15m", "1h", "48h", "7d"}
|
||||
Scenarios = []string{"base", "sunny-saturday-market", "rainy-saturday", "weekday-event"}
|
||||
Standards = []string{"relaxed", "standard", "premium"}
|
||||
)
|
||||
|
||||
// Contains reports whether v is in list.
|
||||
func Contains(list []string, v string) bool {
|
||||
for _, item := range list {
|
||||
if item == v {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// Sensor is one row of GET /api/sensors.
|
||||
type Sensor struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Lat float64 `json:"lat"`
|
||||
Lon float64 `json:"lon"`
|
||||
Mean float64 `json:"mean"`
|
||||
P95 float64 `json:"p95"`
|
||||
Battery *int `json:"battery"`
|
||||
}
|
||||
|
||||
// Point is one observed series point.
|
||||
type Point struct {
|
||||
T time.Time `json:"t"`
|
||||
V float64 `json:"v"`
|
||||
}
|
||||
|
||||
// ForecastPoint is one forecast point with its 80% band.
|
||||
type ForecastPoint struct {
|
||||
T time.Time `json:"t"`
|
||||
V float64 `json:"v"`
|
||||
Lo float64 `json:"lo"`
|
||||
Hi float64 `json:"hi"`
|
||||
}
|
||||
|
||||
// Coverage describes the training/observation window.
|
||||
type Coverage struct {
|
||||
Sensors int `json:"sensors"`
|
||||
From string `json:"from"`
|
||||
To string `json:"to"`
|
||||
CadenceMin int `json:"cadence_min"`
|
||||
}
|
||||
|
||||
// Metrics is the model card headline block exposed by GET /api/meta.
|
||||
type Metrics struct {
|
||||
Model string `json:"model"`
|
||||
MAE float64 `json:"mae"`
|
||||
WAPE float64 `json:"wape"`
|
||||
R2 float64 `json:"r2"`
|
||||
BaselineMAE float64 `json:"baseline_mae"`
|
||||
BaselineWAPE float64 `json:"baseline_wape"`
|
||||
}
|
||||
|
||||
// Meta is GET /api/meta.
|
||||
type Meta struct {
|
||||
DataVersion string `json:"data_version"`
|
||||
ModelVersion string `json:"model_version"`
|
||||
ContextVersion string `json:"context_version"`
|
||||
Coverage Coverage `json:"coverage"`
|
||||
Metrics Metrics `json:"metrics"`
|
||||
Limits []string `json:"limits"`
|
||||
}
|
||||
|
||||
// WeatherNow is the current conditions block.
|
||||
type WeatherNow struct {
|
||||
T time.Time `json:"t"`
|
||||
TempC float64 `json:"temp_c"`
|
||||
PrecipMM float64 `json:"precip_mm"`
|
||||
CloudPct int `json:"cloud_pct"`
|
||||
WindKMH float64 `json:"wind_kmh"`
|
||||
HumidityPct int `json:"humidity_pct"`
|
||||
}
|
||||
|
||||
// WeatherPoint is one forecast hour.
|
||||
type WeatherPoint struct {
|
||||
T time.Time `json:"t"`
|
||||
TempC float64 `json:"temp_c"`
|
||||
PrecipMM float64 `json:"precip_mm"`
|
||||
CloudPct int `json:"cloud_pct"`
|
||||
WindKMH float64 `json:"wind_kmh"`
|
||||
HumidityPct int `json:"humidity_pct"`
|
||||
}
|
||||
|
||||
// Weather groups current conditions and the hourly forecast.
|
||||
type Weather struct {
|
||||
Now WeatherNow `json:"now"`
|
||||
Forecast []WeatherPoint `json:"forecast"`
|
||||
}
|
||||
|
||||
// Holiday is one public holiday (Baden-Württemberg).
|
||||
type Holiday struct {
|
||||
Date string `json:"date"`
|
||||
Name string `json:"name"`
|
||||
}
|
||||
|
||||
// ContextData is the stored context artifact.
|
||||
type ContextData struct {
|
||||
Weather Weather `json:"weather"`
|
||||
Holidays []Holiday `json:"holidays"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
// ContextResponse is GET /api/context.
|
||||
type ContextResponse struct {
|
||||
Weather Weather `json:"weather"`
|
||||
Holidays []Holiday `json:"holidays"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
Cached bool `json:"cached"`
|
||||
}
|
||||
|
||||
// WeatherInput is the scenario weather override.
|
||||
type WeatherInput struct {
|
||||
TempDeltaC float64 `json:"temp_delta_c"`
|
||||
PrecipMM float64 `json:"precip_mm"`
|
||||
}
|
||||
|
||||
// EventInput is the scenario event override.
|
||||
type EventInput struct {
|
||||
Type string `json:"type"`
|
||||
Uplift float64 `json:"uplift"`
|
||||
}
|
||||
|
||||
// ScenarioInput is the scenario body from POST /api/scenario.
|
||||
type ScenarioInput struct {
|
||||
Scenario string `json:"scenario"`
|
||||
Weather WeatherInput `json:"weather"`
|
||||
Event EventInput `json:"event"`
|
||||
}
|
||||
|
||||
// ScenarioState is the current scenario plus its version.
|
||||
type ScenarioState struct {
|
||||
Version int `json:"version"`
|
||||
Scenario ScenarioInput `json:"scenario"`
|
||||
At time.Time `json:"at"`
|
||||
}
|
||||
|
||||
// ForecastResponse is GET /api/forecast.
|
||||
type ForecastResponse struct {
|
||||
Sensor string `json:"sensor"`
|
||||
Horizon string `json:"horizon"`
|
||||
Scenario string `json:"scenario"`
|
||||
Points []ForecastPoint `json:"points"`
|
||||
Cached bool `json:"cached"`
|
||||
DataVersion string `json:"data_version"`
|
||||
ModelVersion string `json:"model_version"`
|
||||
ContextVersion string `json:"context_version"`
|
||||
}
|
||||
|
||||
// Staffing assumptions, echoed in every plan.
|
||||
const (
|
||||
VisitorsPerStaffRelaxed = 35
|
||||
VisitorsPerStaffStandard = 25
|
||||
VisitorsPerStaffPremium = 18
|
||||
SafetyFactor = 1.15
|
||||
MinStaff = 1
|
||||
ShiftLengthHours = 4
|
||||
LaborCostEURPerHour = 16
|
||||
)
|
||||
|
||||
// StoreHours are local Europe/Berlin opening hours.
|
||||
var StoreHours = struct {
|
||||
Open int
|
||||
Close int
|
||||
TZ string
|
||||
}{Open: 10, Close: 20, TZ: "Europe/Berlin"}
|
||||
|
||||
// StaffingAssumptions is echoed in the plan so the UI can show them.
|
||||
type StaffingAssumptions struct {
|
||||
VisitorsPerStaffHour int `json:"visitors_per_staff_hour"`
|
||||
SafetyFactor float64 `json:"safety_factor"`
|
||||
MinStaff int `json:"min_staff"`
|
||||
ShiftLengthH int `json:"shift_length_h"`
|
||||
LaborCostEURH int `json:"labor_cost_eur_h"`
|
||||
StoreHours StoreHoursSpec `json:"store_hours"`
|
||||
}
|
||||
|
||||
// StoreHoursSpec is the display form of the opening hours.
|
||||
type StoreHoursSpec struct {
|
||||
Open string `json:"open"`
|
||||
Close string `json:"close"`
|
||||
TZ string `json:"tz"`
|
||||
}
|
||||
|
||||
// StaffingHour is one hour of the plan.
|
||||
type StaffingHour struct {
|
||||
T time.Time `json:"t"`
|
||||
Footfall float64 `json:"footfall"`
|
||||
RequiredStaff int `json:"required_staff"`
|
||||
ScheduledStaff int `json:"scheduled_staff"`
|
||||
Coverage string `json:"coverage"`
|
||||
}
|
||||
|
||||
// Shift is one contiguous shift block.
|
||||
type Shift struct {
|
||||
Date string `json:"date"`
|
||||
Start string `json:"start"`
|
||||
End string `json:"end"`
|
||||
Staff int `json:"staff"`
|
||||
}
|
||||
|
||||
// StaffingSummary is the plan headline block.
|
||||
type StaffingSummary struct {
|
||||
CoveragePct float64 `json:"coverage_pct"`
|
||||
CostEUR int `json:"cost_eur"`
|
||||
FlatScheduleCostEUR int `json:"flat_schedule_cost_eur"`
|
||||
OverstaffedHours int `json:"overstaffed_hours"`
|
||||
UnderstaffedHours int `json:"understaffed_hours"`
|
||||
}
|
||||
|
||||
// StaffingResponse is GET /api/staffing.
|
||||
type StaffingResponse struct {
|
||||
Sensor string `json:"sensor"`
|
||||
Scenario string `json:"scenario"`
|
||||
Standard string `json:"standard"`
|
||||
Assumptions StaffingAssumptions `json:"assumptions"`
|
||||
Hours []StaffingHour `json:"hours"`
|
||||
Shifts []Shift `json:"shifts"`
|
||||
Summary StaffingSummary `json:"summary"`
|
||||
Why []string `json:"why"`
|
||||
Cached bool `json:"cached"`
|
||||
DataVersion string `json:"data_version"`
|
||||
ModelVersion string `json:"model_version"`
|
||||
ContextVersion string `json:"context_version"`
|
||||
}
|
||||
|
||||
// ErrorBody is the canonical error envelope.
|
||||
type ErrorBody struct {
|
||||
Error ErrorDetail `json:"error"`
|
||||
}
|
||||
|
||||
// ErrorDetail is the inner error object.
|
||||
type ErrorDetail struct {
|
||||
Code string `json:"code"`
|
||||
Message string `json:"message"`
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
// Package scenario holds the single in-memory scenario state.
|
||||
package scenario
|
||||
|
||||
import (
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"pulsecast/api/internal/model"
|
||||
)
|
||||
|
||||
// State is safe for concurrent readers and writers.
|
||||
type State struct {
|
||||
mu sync.RWMutex
|
||||
current model.ScenarioState
|
||||
}
|
||||
|
||||
// New returns the initial base scenario at version 1.
|
||||
func New() *State {
|
||||
return &State{current: model.ScenarioState{
|
||||
Version: 1,
|
||||
Scenario: model.ScenarioInput{
|
||||
Scenario: "base",
|
||||
Weather: model.WeatherInput{},
|
||||
Event: model.EventInput{},
|
||||
},
|
||||
At: time.Now().UTC().Truncate(time.Second),
|
||||
}}
|
||||
}
|
||||
|
||||
// Get returns a consistent snapshot.
|
||||
func (s *State) Get() model.ScenarioState {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
return s.current
|
||||
}
|
||||
|
||||
// Set stores a new scenario and returns its snapshot.
|
||||
func (s *State) Set(in model.ScenarioInput) model.ScenarioState {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
s.current = model.ScenarioState{
|
||||
Version: s.current.Version + 1,
|
||||
Scenario: in,
|
||||
At: time.Now().UTC().Truncate(time.Second),
|
||||
}
|
||||
return s.current
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
// Package sse is a small fan-out hub for Server-Sent Events.
|
||||
package sse
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Event is one SSE message. ID is omitted when zero.
|
||||
type Event struct {
|
||||
Name string
|
||||
ID int
|
||||
Data []byte
|
||||
}
|
||||
|
||||
// Hub fans events out to every subscribed client and emits a heartbeat.
|
||||
type Hub struct {
|
||||
heartbeat time.Duration
|
||||
|
||||
mu sync.RWMutex
|
||||
clients map[chan Event]struct{}
|
||||
}
|
||||
|
||||
// NewHub returns a hub that pings every heartbeat (15 s in production).
|
||||
func NewHub(heartbeat time.Duration) *Hub {
|
||||
if heartbeat <= 0 {
|
||||
heartbeat = 15 * time.Second
|
||||
}
|
||||
return &Hub{
|
||||
heartbeat: heartbeat,
|
||||
clients: make(map[chan Event]struct{}),
|
||||
}
|
||||
}
|
||||
|
||||
// Run emits heartbeats until ctx is cancelled.
|
||||
func (h *Hub) Run(ctx context.Context) {
|
||||
ticker := time.NewTicker(h.heartbeat)
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-ticker.C:
|
||||
data, _ := json.Marshal(map[string]string{"t": time.Now().UTC().Truncate(time.Second).Format(time.RFC3339)})
|
||||
h.send(Event{Name: "ping", Data: data})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Subscribe registers a client. The returned cancel function must be called
|
||||
// when the request ends. The channel is never closed; cancelling drops it.
|
||||
func (h *Hub) Subscribe() (<-chan Event, func()) {
|
||||
ch := make(chan Event, 16)
|
||||
h.mu.Lock()
|
||||
h.clients[ch] = struct{}{}
|
||||
h.mu.Unlock()
|
||||
|
||||
var once sync.Once
|
||||
cancel := func() {
|
||||
once.Do(func() {
|
||||
h.mu.Lock()
|
||||
delete(h.clients, ch)
|
||||
h.mu.Unlock()
|
||||
})
|
||||
}
|
||||
return ch, cancel
|
||||
}
|
||||
|
||||
// Broadcast queues an event for every client. Slow clients drop the event
|
||||
// rather than blocking the broadcaster; scenario state is versioned and can
|
||||
// always be re-read with GET /api/scenario.
|
||||
func (h *Hub) Broadcast(event Event) { h.send(event) }
|
||||
|
||||
func (h *Hub) send(event Event) {
|
||||
h.mu.RLock()
|
||||
defer h.mu.RUnlock()
|
||||
for ch := range h.clients {
|
||||
select {
|
||||
case ch <- event:
|
||||
default:
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Clients reports the number of subscribed clients.
|
||||
func (h *Hub) Clients() int {
|
||||
h.mu.RLock()
|
||||
defer h.mu.RUnlock()
|
||||
return len(h.clients)
|
||||
}
|
||||
@@ -0,0 +1,323 @@
|
||||
// Package staffing implements the deterministic decision heuristic from
|
||||
// CONTRACT.md §5. It never calls the model: it consumes forecast points and
|
||||
// turns them into an explainable shift plan.
|
||||
package staffing
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math"
|
||||
"sort"
|
||||
"time"
|
||||
|
||||
"pulsecast/api/internal/model"
|
||||
)
|
||||
|
||||
// Build creates a plan for one sensor/scenario/standard.
|
||||
func Build(sensor, scenario, standard string, points []model.ForecastPoint, ctx model.ContextData) (model.StaffingResponse, error) {
|
||||
perStaff, ok := visitorsPerStaff(standard)
|
||||
if !ok {
|
||||
return model.StaffingResponse{}, fmt.Errorf("unknown standard %q", standard)
|
||||
}
|
||||
|
||||
loc, err := time.LoadLocation(model.StoreHours.TZ)
|
||||
if err != nil {
|
||||
return model.StaffingResponse{}, fmt.Errorf("load timezone: %w", err)
|
||||
}
|
||||
|
||||
days, err := groupStoreHours(points, loc)
|
||||
if err != nil {
|
||||
return model.StaffingResponse{}, err
|
||||
}
|
||||
|
||||
assumptions := model.StaffingAssumptions{
|
||||
VisitorsPerStaffHour: perStaff,
|
||||
SafetyFactor: model.SafetyFactor,
|
||||
MinStaff: model.MinStaff,
|
||||
ShiftLengthH: model.ShiftLengthHours,
|
||||
LaborCostEURH: model.LaborCostEURPerHour,
|
||||
StoreHours: model.StoreHoursSpec{
|
||||
Open: "10:00",
|
||||
Close: "20:00",
|
||||
TZ: model.StoreHours.TZ,
|
||||
},
|
||||
}
|
||||
|
||||
var hours []model.StaffingHour
|
||||
var shifts []model.Shift
|
||||
requiredByDate := make(map[string][]int)
|
||||
totalCost := 0.0
|
||||
|
||||
for _, day := range days {
|
||||
// Required staff per hour first; blocks need maxima across the day.
|
||||
required := make(map[int]int, len(day.hours))
|
||||
for _, h := range day.hours {
|
||||
req := int(math.Ceil(math.Max(0, h.point.V) / float64(perStaff) * model.SafetyFactor))
|
||||
if req < model.MinStaff {
|
||||
req = model.MinStaff
|
||||
}
|
||||
required[h.hour] = req
|
||||
requiredByDate[day.date] = append(requiredByDate[day.date], req)
|
||||
}
|
||||
|
||||
scheduled := make(map[int]int, len(day.hours))
|
||||
for _, block := range blocks(day.hours) {
|
||||
staff := 0
|
||||
for _, h := range block.hours {
|
||||
if req := required[h.hour]; req > staff {
|
||||
staff = req
|
||||
}
|
||||
}
|
||||
for _, h := range block.hours {
|
||||
scheduled[h.hour] = staff
|
||||
}
|
||||
shifts = append(shifts, model.Shift{
|
||||
Date: day.date,
|
||||
Start: clock(block.start),
|
||||
End: clock(block.end),
|
||||
Staff: staff,
|
||||
})
|
||||
totalCost += float64(staff) * float64(block.minutes()) / 60 * model.LaborCostEURPerHour
|
||||
}
|
||||
|
||||
for _, h := range day.hours {
|
||||
req := required[h.hour]
|
||||
sched := scheduled[h.hour]
|
||||
coverage := "ok"
|
||||
switch {
|
||||
case sched < req:
|
||||
coverage = "under"
|
||||
case sched > req:
|
||||
coverage = "over"
|
||||
}
|
||||
hours = append(hours, model.StaffingHour{
|
||||
T: h.point.T.UTC(),
|
||||
Footfall: h.point.V,
|
||||
RequiredStaff: req,
|
||||
ScheduledStaff: sched,
|
||||
Coverage: coverage,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
if len(hours) == 0 {
|
||||
return model.StaffingResponse{}, fmt.Errorf("no store-hour forecast points")
|
||||
}
|
||||
|
||||
summary := summarise(hours, requiredByDate, totalCost, loc)
|
||||
why := explain(days, ctx, scenario, loc)
|
||||
|
||||
return model.StaffingResponse{
|
||||
Sensor: sensor,
|
||||
Scenario: scenario,
|
||||
Standard: standard,
|
||||
Assumptions: assumptions,
|
||||
Hours: hours,
|
||||
Shifts: shifts,
|
||||
Summary: summary,
|
||||
Why: why,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func visitorsPerStaff(standard string) (int, bool) {
|
||||
switch standard {
|
||||
case "relaxed":
|
||||
return model.VisitorsPerStaffRelaxed, true
|
||||
case "standard":
|
||||
return model.VisitorsPerStaffStandard, true
|
||||
case "premium":
|
||||
return model.VisitorsPerStaffPremium, true
|
||||
default:
|
||||
return 0, false
|
||||
}
|
||||
}
|
||||
|
||||
type hourPoint struct {
|
||||
hour int
|
||||
point model.ForecastPoint
|
||||
}
|
||||
|
||||
type dayPlan struct {
|
||||
date string
|
||||
hours []hourPoint
|
||||
}
|
||||
|
||||
// groupStoreHours keeps only points that fall inside 10:00–20:00 local time,
|
||||
// first seven local dates, sorted chronologically.
|
||||
func groupStoreHours(points []model.ForecastPoint, loc *time.Location) ([]dayPlan, error) {
|
||||
type key struct {
|
||||
date string
|
||||
hour int
|
||||
}
|
||||
seen := make(map[key]model.ForecastPoint)
|
||||
var dates []string
|
||||
dateSet := make(map[string]bool)
|
||||
|
||||
for _, point := range points {
|
||||
local := point.T.In(loc)
|
||||
if local.Hour() < model.StoreHours.Open || local.Hour() >= model.StoreHours.Close {
|
||||
continue
|
||||
}
|
||||
k := key{date: local.Format("2006-01-02"), hour: local.Hour()}
|
||||
seen[k] = point
|
||||
if !dateSet[k.date] {
|
||||
dateSet[k.date] = true
|
||||
dates = append(dates, k.date)
|
||||
}
|
||||
}
|
||||
sort.Strings(dates)
|
||||
if len(dates) > 7 {
|
||||
dates = dates[:7]
|
||||
}
|
||||
|
||||
days := make([]dayPlan, 0, len(dates))
|
||||
for _, date := range dates {
|
||||
day := dayPlan{date: date}
|
||||
for hour := model.StoreHours.Open; hour < model.StoreHours.Close; hour++ {
|
||||
if point, ok := seen[key{date: date, hour: hour}]; ok {
|
||||
day.hours = append(day.hours, hourPoint{hour: hour, point: point})
|
||||
}
|
||||
}
|
||||
// A day is only usable if every store hour has a forecast point.
|
||||
if len(day.hours) == model.StoreHours.Close-model.StoreHours.Open {
|
||||
days = append(days, day)
|
||||
}
|
||||
}
|
||||
if len(days) == 0 {
|
||||
return nil, fmt.Errorf("no complete store-day in forecast")
|
||||
}
|
||||
return days, nil
|
||||
}
|
||||
|
||||
type block struct {
|
||||
start int // local hour
|
||||
end int // local hour, exclusive
|
||||
hours []hourPoint
|
||||
}
|
||||
|
||||
func (b block) minutes() int { return (b.end - b.start) * 60 }
|
||||
|
||||
// blocks walks the store day in 4-hour chunks; the final chunk is shorter
|
||||
// (18:00–20:00) rather than extending past closing time.
|
||||
func blocks(hours []hourPoint) []block {
|
||||
var out []block
|
||||
for start := model.StoreHours.Open; start < model.StoreHours.Close; start += model.ShiftLengthHours {
|
||||
end := start + model.ShiftLengthHours
|
||||
if end > model.StoreHours.Close {
|
||||
end = model.StoreHours.Close
|
||||
}
|
||||
var inBlock []hourPoint
|
||||
for _, h := range hours {
|
||||
if h.hour >= start && h.hour < end {
|
||||
inBlock = append(inBlock, h)
|
||||
}
|
||||
}
|
||||
if len(inBlock) > 0 {
|
||||
out = append(out, block{start: start, end: end, hours: inBlock})
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func summarise(hours []model.StaffingHour, requiredByDate map[string][]int, totalCost float64, loc *time.Location) model.StaffingSummary {
|
||||
covered := 0
|
||||
over := 0
|
||||
under := 0
|
||||
for _, h := range hours {
|
||||
switch {
|
||||
case h.ScheduledStaff >= h.RequiredStaff:
|
||||
covered++
|
||||
}
|
||||
if h.ScheduledStaff > h.RequiredStaff {
|
||||
over++
|
||||
}
|
||||
if h.ScheduledStaff < h.RequiredStaff {
|
||||
under++
|
||||
}
|
||||
}
|
||||
|
||||
maxRequired := 0
|
||||
for _, reqs := range requiredByDate {
|
||||
for _, req := range reqs {
|
||||
if req > maxRequired {
|
||||
maxRequired = req
|
||||
}
|
||||
}
|
||||
}
|
||||
flatCost := float64(maxRequired) * float64(len(hours)) * model.LaborCostEURPerHour
|
||||
|
||||
coveragePct := 0.0
|
||||
if len(hours) > 0 {
|
||||
coveragePct = math.Round(float64(covered)/float64(len(hours))*1000) / 10
|
||||
}
|
||||
|
||||
return model.StaffingSummary{
|
||||
CoveragePct: coveragePct,
|
||||
CostEUR: int(math.Round(totalCost)),
|
||||
FlatScheduleCostEUR: int(math.Round(flatCost)),
|
||||
OverstaffedHours: over,
|
||||
UnderstaffedHours: under,
|
||||
}
|
||||
}
|
||||
|
||||
// explain names the observable weather/holiday context and the scenario
|
||||
// assumptions. It does not claim causality.
|
||||
func explain(days []dayPlan, ctx model.ContextData, scenario string, loc *time.Location) []string {
|
||||
if len(days) == 0 {
|
||||
return nil
|
||||
}
|
||||
first, _ := time.ParseInLocation("2006-01-02", days[0].date, loc)
|
||||
last, _ := time.ParseInLocation("2006-01-02", days[len(days)-1].date, loc)
|
||||
|
||||
var why []string
|
||||
for _, holiday := range ctx.Holidays {
|
||||
hDate, err := time.ParseInLocation("2006-01-02", holiday.Date, loc)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
if !hDate.Before(first) && !hDate.After(last) {
|
||||
why = append(why, "Public holiday: "+holiday.Name+" ("+holiday.Date+")")
|
||||
}
|
||||
}
|
||||
|
||||
var precip float64
|
||||
var tempSum float64
|
||||
var n int
|
||||
for _, point := range ctx.Weather.Forecast {
|
||||
local := point.T.In(loc)
|
||||
day := local.Format("2006-01-02")
|
||||
if day < days[0].date || day > days[len(days)-1].date {
|
||||
continue
|
||||
}
|
||||
precip += point.PrecipMM
|
||||
tempSum += point.TempC
|
||||
n++
|
||||
}
|
||||
if n > 0 {
|
||||
avg := tempSum / float64(n)
|
||||
switch {
|
||||
case precip >= 5:
|
||||
why = append(why, fmt.Sprintf("Wet week in the forecast (%.1f mm)", precip))
|
||||
case precip >= 0.5:
|
||||
why = append(why, fmt.Sprintf("Some rain in the forecast (%.1f mm)", precip))
|
||||
default:
|
||||
why = append(why, "Mostly dry week in the forecast")
|
||||
}
|
||||
why = append(why, fmt.Sprintf("Average forecast temperature %.0f°C", avg))
|
||||
}
|
||||
|
||||
switch scenario {
|
||||
case "sunny-saturday-market":
|
||||
why = append(why, "Scenario assumes a sunny Saturday market uplift")
|
||||
case "rainy-saturday":
|
||||
why = append(why, "Scenario assumes a rainy Saturday")
|
||||
case "weekday-event":
|
||||
why = append(why, "Scenario assumes a weekday evening event uplift")
|
||||
default:
|
||||
why = append(why, "Base scenario: no weather delta or event uplift")
|
||||
}
|
||||
return why
|
||||
}
|
||||
|
||||
func clock(hour int) string {
|
||||
return fmt.Sprintf("%02d:00", hour)
|
||||
}
|
||||
@@ -0,0 +1,189 @@
|
||||
// Package store loads the baked JSON artifacts described in CONTRACT.md §4.
|
||||
// The data is immutable after Load; all accessors are safe for concurrent use.
|
||||
package store
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"pulsecast/api/internal/model"
|
||||
)
|
||||
|
||||
// Store is the in-memory baked dataset.
|
||||
type Store struct {
|
||||
meta model.Meta
|
||||
sensors []model.Sensor
|
||||
sensorBy map[string]model.Sensor
|
||||
series map[string][]model.Point
|
||||
forecasts map[string]map[string]map[string][]model.ForecastPoint
|
||||
context model.ContextData
|
||||
}
|
||||
|
||||
// Load reads every artifact from dir. It returns a usable (possibly partial)
|
||||
// store together with a joined error so callers can start the API and let
|
||||
// /api/readyz report 503 instead of crash-looping.
|
||||
func Load(dir string) (*Store, error) {
|
||||
s := &Store{
|
||||
sensorBy: make(map[string]model.Sensor),
|
||||
series: make(map[string][]model.Point),
|
||||
forecasts: make(map[string]map[string]map[string][]model.ForecastPoint),
|
||||
}
|
||||
|
||||
var errs []error
|
||||
|
||||
if err := readJSON(filepath.Join(dir, "sensors.json"), &s.sensors); err != nil {
|
||||
errs = append(errs, err)
|
||||
}
|
||||
sort.Slice(s.sensors, func(i, j int) bool { return s.sensors[i].ID < s.sensors[j].ID })
|
||||
for _, sensor := range s.sensors {
|
||||
s.sensorBy[sensor.ID] = sensor
|
||||
}
|
||||
|
||||
if err := readJSON(filepath.Join(dir, "metrics.json"), &s.meta); err != nil {
|
||||
errs = append(errs, err)
|
||||
}
|
||||
|
||||
if err := readJSON(filepath.Join(dir, "context.json"), &s.context); err != nil {
|
||||
errs = append(errs, err)
|
||||
}
|
||||
|
||||
if err := loadSeries(dir, s); err != nil {
|
||||
errs = append(errs, err)
|
||||
}
|
||||
|
||||
if err := readJSON(filepath.Join(dir, "forecasts.json"), &s.forecasts); err != nil {
|
||||
errs = append(errs, err)
|
||||
}
|
||||
for sensorID, scenarios := range s.forecasts {
|
||||
for scenario, horizons := range scenarios {
|
||||
for horizon, points := range horizons {
|
||||
sort.Slice(points, func(i, j int) bool { return points[i].T.Before(points[j].T) })
|
||||
horizons[horizon] = points
|
||||
}
|
||||
scenarios[scenario] = horizons
|
||||
}
|
||||
s.forecasts[sensorID] = scenarios
|
||||
}
|
||||
|
||||
return s, errors.Join(errs...)
|
||||
}
|
||||
|
||||
func loadSeries(dir string, s *Store) error {
|
||||
var errs []error
|
||||
|
||||
// Contract allows a single series.json mapping sensor id -> points.
|
||||
var combined map[string][]model.Point
|
||||
err := readJSON(filepath.Join(dir, "series.json"), &combined)
|
||||
switch {
|
||||
case err == nil:
|
||||
for sensorID, points := range combined {
|
||||
sort.Slice(points, func(i, j int) bool { return points[i].T.Before(points[j].T) })
|
||||
s.series[sensorID] = points
|
||||
}
|
||||
case !errors.Is(err, os.ErrNotExist):
|
||||
errs = append(errs, err)
|
||||
}
|
||||
|
||||
// Contract also allows series/<id>.json; these override the combined file.
|
||||
entries, err := os.ReadDir(filepath.Join(dir, "series"))
|
||||
if err != nil {
|
||||
if !errors.Is(err, os.ErrNotExist) {
|
||||
errs = append(errs, fmt.Errorf("series dir: %w", err))
|
||||
}
|
||||
return errors.Join(errs...)
|
||||
}
|
||||
for _, entry := range entries {
|
||||
if entry.IsDir() || !strings.HasSuffix(entry.Name(), ".json") {
|
||||
continue
|
||||
}
|
||||
var points []model.Point
|
||||
path := filepath.Join(dir, "series", entry.Name())
|
||||
if err := readJSON(path, &points); err != nil {
|
||||
errs = append(errs, err)
|
||||
continue
|
||||
}
|
||||
sort.Slice(points, func(i, j int) bool { return points[i].T.Before(points[j].T) })
|
||||
s.series[strings.TrimSuffix(entry.Name(), ".json")] = points
|
||||
}
|
||||
return errors.Join(errs...)
|
||||
}
|
||||
|
||||
func readJSON(path string, dst any) error {
|
||||
raw, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return fmt.Errorf("read %s: %w", path, err)
|
||||
}
|
||||
if err := json.Unmarshal(raw, dst); err != nil {
|
||||
return fmt.Errorf("decode %s: %w", path, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Meta returns the model/data metadata.
|
||||
func (s *Store) Meta() model.Meta { return s.meta }
|
||||
|
||||
// Sensors returns the sensors sorted by id.
|
||||
func (s *Store) Sensors() []model.Sensor {
|
||||
out := make([]model.Sensor, len(s.sensors))
|
||||
copy(out, s.sensors)
|
||||
return out
|
||||
}
|
||||
|
||||
// Sensor looks up one sensor.
|
||||
func (s *Store) Sensor(id string) (model.Sensor, bool) {
|
||||
sensor, ok := s.sensorBy[id]
|
||||
return sensor, ok
|
||||
}
|
||||
|
||||
// Series returns the raw (15-minute) series for a sensor.
|
||||
func (s *Store) Series(id string) ([]model.Point, bool) {
|
||||
points, ok := s.series[id]
|
||||
return points, ok
|
||||
}
|
||||
|
||||
// Forecast returns baked points for sensor/scenario/horizon.
|
||||
func (s *Store) Forecast(sensor, scenario, horizon string) ([]model.ForecastPoint, bool) {
|
||||
scenarios, ok := s.forecasts[sensor]
|
||||
if !ok {
|
||||
return nil, false
|
||||
}
|
||||
horizons, ok := scenarios[scenario]
|
||||
if !ok {
|
||||
return nil, false
|
||||
}
|
||||
points, ok := horizons[horizon]
|
||||
if !ok || len(points) == 0 {
|
||||
return nil, false
|
||||
}
|
||||
return points, true
|
||||
}
|
||||
|
||||
// Context returns the baked weather/holiday context.
|
||||
func (s *Store) Context() model.ContextData { return s.context }
|
||||
|
||||
// Versions returns data, model and context version strings.
|
||||
func (s *Store) Versions() (data, modelVersion, context string) {
|
||||
return s.meta.DataVersion, s.meta.ModelVersion, s.meta.ContextVersion
|
||||
}
|
||||
|
||||
// Ready reports whether the minimum baked set is present. FastAPI health is
|
||||
// deliberately not part of readiness: the cache fallback is the safety net.
|
||||
func (s *Store) Ready() bool {
|
||||
if len(s.sensors) == 0 || s.meta.ModelVersion == "" || s.context.UpdatedAt.IsZero() {
|
||||
return false
|
||||
}
|
||||
for _, sensor := range s.sensors {
|
||||
if _, ok := s.Forecast(sensor.ID, "base", "7d"); ok {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// Len returns the number of loaded sensors (used in tests/logs).
|
||||
func (s *Store) Len() int { return len(s.sensors) }
|
||||
Reference in new issue
Block a user