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) }
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
{
|
||||||
|
"$schema": "https://opencode.ai/config.json",
|
||||||
|
"model": "opencode-go/deepseek-v4.1-flash"
|
||||||
|
}
|
||||||
Vendored
+1
@@ -0,0 +1 @@
|
|||||||
|
{"weather":{"now":{"t":"2026-11-14T03:00:00Z","temp_c":8.9,"precip_mm":0.0,"cloud_pct":80,"wind_kmh":11.0,"humidity_pct":79},"forecast":[{"t":"2026-11-14T04:00:00Z","temp_c":2.6,"precip_mm":0.0,"cloud_pct":80,"wind_kmh":9.4,"humidity_pct":77},{"t":"2026-11-14T05:00:00Z","temp_c":3.3,"precip_mm":0.0,"cloud_pct":84,"wind_kmh":11.2,"humidity_pct":84},{"t":"2026-11-14T06:00:00Z","temp_c":4.2,"precip_mm":0.0,"cloud_pct":65,"wind_kmh":8.4,"humidity_pct":88},{"t":"2026-11-14T07:00:00Z","temp_c":5.3,"precip_mm":0.0,"cloud_pct":76,"wind_kmh":16.7,"humidity_pct":82},{"t":"2026-11-14T08:00:00Z","temp_c":6.5,"precip_mm":0.0,"cloud_pct":87,"wind_kmh":16.1,"humidity_pct":79},{"t":"2026-11-14T09:00:00Z","temp_c":7.7,"precip_mm":0.0,"cloud_pct":76,"wind_kmh":16.5,"humidity_pct":75},{"t":"2026-11-14T10:00:00Z","temp_c":8.8,"precip_mm":0.0,"cloud_pct":60,"wind_kmh":8.8,"humidity_pct":78},{"t":"2026-11-14T11:00:00Z","temp_c":9.7,"precip_mm":0.0,"cloud_pct":85,"wind_kmh":16.4,"humidity_pct":73},{"t":"2026-11-14T12:00:00Z","temp_c":10.4,"precip_mm":0.0,"cloud_pct":79,"wind_kmh":12.7,"humidity_pct":76},{"t":"2026-11-14T13:00:00Z","temp_c":10.8,"precip_mm":0.0,"cloud_pct":78,"wind_kmh":12.4,"humidity_pct":75},{"t":"2026-11-14T14:00:00Z","temp_c":11.0,"precip_mm":0.0,"cloud_pct":70,"wind_kmh":10.0,"humidity_pct":71},{"t":"2026-11-14T15:00:00Z","temp_c":10.8,"precip_mm":0.0,"cloud_pct":78,"wind_kmh":11.5,"humidity_pct":87},{"t":"2026-11-14T16:00:00Z","temp_c":10.4,"precip_mm":0.0,"cloud_pct":70,"wind_kmh":14.6,"humidity_pct":91},{"t":"2026-11-14T17:00:00Z","temp_c":9.7,"precip_mm":0.0,"cloud_pct":68,"wind_kmh":7.1,"humidity_pct":79},{"t":"2026-11-14T18:00:00Z","temp_c":8.8,"precip_mm":0.0,"cloud_pct":77,"wind_kmh":10.8,"humidity_pct":82},{"t":"2026-11-14T19:00:00Z","temp_c":7.7,"precip_mm":0.0,"cloud_pct":63,"wind_kmh":16.7,"humidity_pct":89},{"t":"2026-11-14T20:00:00Z","temp_c":6.5,"precip_mm":0.0,"cloud_pct":81,"wind_kmh":10.7,"humidity_pct":83},{"t":"2026-11-14T21:00:00Z","temp_c":5.3,"precip_mm":0.0,"cloud_pct":80,"wind_kmh":13.5,"humidity_pct":75},{"t":"2026-11-14T22:00:00Z","temp_c":4.2,"precip_mm":0.0,"cloud_pct":68,"wind_kmh":16.6,"humidity_pct":87},{"t":"2026-11-14T23:00:00Z","temp_c":3.3,"precip_mm":0.0,"cloud_pct":84,"wind_kmh":16.8,"humidity_pct":82},{"t":"2026-11-15T00:00:00Z","temp_c":2.6,"precip_mm":0.0,"cloud_pct":61,"wind_kmh":11.6,"humidity_pct":78},{"t":"2026-11-15T01:00:00Z","temp_c":2.2,"precip_mm":0.0,"cloud_pct":66,"wind_kmh":12.2,"humidity_pct":75},{"t":"2026-11-15T02:00:00Z","temp_c":2.0,"precip_mm":0.0,"cloud_pct":66,"wind_kmh":13.3,"humidity_pct":73},{"t":"2026-11-15T03:00:00Z","temp_c":2.2,"precip_mm":0.0,"cloud_pct":62,"wind_kmh":7.1,"humidity_pct":81},{"t":"2026-11-15T04:00:00Z","temp_c":2.6,"precip_mm":0.0,"cloud_pct":74,"wind_kmh":7.9,"humidity_pct":77},{"t":"2026-11-15T05:00:00Z","temp_c":3.3,"precip_mm":0.0,"cloud_pct":87,"wind_kmh":8.7,"humidity_pct":82},{"t":"2026-11-15T06:00:00Z","temp_c":4.2,"precip_mm":0.0,"cloud_pct":70,"wind_kmh":16.3,"humidity_pct":86},{"t":"2026-11-15T07:00:00Z","temp_c":5.3,"precip_mm":0.0,"cloud_pct":75,"wind_kmh":16.5,"humidity_pct":76},{"t":"2026-11-15T08:00:00Z","temp_c":6.5,"precip_mm":0.0,"cloud_pct":89,"wind_kmh":14.3,"humidity_pct":72},{"t":"2026-11-15T09:00:00Z","temp_c":7.7,"precip_mm":0.0,"cloud_pct":70,"wind_kmh":15.0,"humidity_pct":73},{"t":"2026-11-15T10:00:00Z","temp_c":8.8,"precip_mm":0.0,"cloud_pct":71,"wind_kmh":9.5,"humidity_pct":78},{"t":"2026-11-15T11:00:00Z","temp_c":9.7,"precip_mm":0.0,"cloud_pct":62,"wind_kmh":7.6,"humidity_pct":89},{"t":"2026-11-15T12:00:00Z","temp_c":10.4,"precip_mm":0.0,"cloud_pct":85,"wind_kmh":10.1,"humidity_pct":86},{"t":"2026-11-15T13:00:00Z","temp_c":10.8,"precip_mm":0.0,"cloud_pct":88,"wind_kmh":9.0,"humidity_pct":87},{"t":"2026-11-15T14:00:00Z","temp_c":11.0,"precip_mm":0.0,"cloud_pct":71,"wind_kmh":8.9,"humidity_pct":76},{"t":"2026-11-15T15:00:00Z","temp_c":10.8,"precip_mm":0.0,"cloud_pct":75,"wind_kmh":10.8,"humidity_pct":83},{"t":"2026-11-15T16:00:00Z","temp_c":10.4,"precip_mm":0.0,"cloud_pct":75,"wind_kmh":9.3,"humidity_pct":75},{"t":"2026-11-15T17:00:00Z","temp_c":9.7,"precip_mm":0.0,"cloud_pct":83,"wind_kmh":16.3,"humidity_pct":85},{"t":"2026-11-15T18:00:00Z","temp_c":8.8,"precip_mm":0.0,"cloud_pct":62,"wind_kmh":15.9,"humidity_pct":78},{"t":"2026-11-15T19:00:00Z","temp_c":7.7,"precip_mm":0.0,"cloud_pct":66,"wind_kmh":14.6,"humidity_pct":74},{"t":"2026-11-15T20:00:00Z","temp_c":6.5,"precip_mm":0.0,"cloud_pct":86,"wind_kmh":9.3,"humidity_pct":79},{"t":"2026-11-15T21:00:00Z","temp_c":5.3,"precip_mm":0.0,"cloud_pct":75,"wind_kmh":11.5,"humidity_pct":81},{"t":"2026-11-15T22:00:00Z","temp_c":4.2,"precip_mm":0.0,"cloud_pct":66,"wind_kmh":16.8,"humidity_pct":81},{"t":"2026-11-15T23:00:00Z","temp_c":3.3,"precip_mm":0.0,"cloud_pct":70,"wind_kmh":10.9,"humidity_pct":90},{"t":"2026-11-16T00:00:00Z","temp_c":2.6,"precip_mm":0.0,"cloud_pct":72,"wind_kmh":7.9,"humidity_pct":72},{"t":"2026-11-16T01:00:00Z","temp_c":2.2,"precip_mmLine truncated
|
||||||
Vendored
+1
@@ -0,0 +1 @@
|
|||||||
|
{"hn-bahnhof-01":{"base":{"48h":[{"t":"2026-11-16T00:00:00Z","v":3.9,"lo":2.9,"hi":5.2},{"t":"2026-11-16T01:00:00Z","v":3.9,"lo":2.9,"hi":5.2},{"t":"2026-11-16T02:00:00Z","v":3.9,"lo":2.9,"hi":5.1},{"t":"2026-11-16T03:00:00Z","v":4.0,"lo":2.9,"hi":5.2},{"t":"2026-11-16T04:00:00Z","v":3.9,"lo":2.9,"hi":5.2},{"t":"2026-11-16T05:00:00Z","v":10.7,"lo":7.9,"hi":14.0},{"t":"2026-11-16T06:00:00Z","v":15.0,"lo":11.1,"hi":19.7},{"t":"2026-11-16T07:00:00Z","v":18.2,"lo":13.5,"hi":23.9},{"t":"2026-11-16T08:00:00Z","v":22.3,"lo":16.5,"hi":29.3},{"t":"2026-11-16T09:00:00Z","v":30.3,"lo":22.4,"hi":39.7},{"t":"2026-11-16T10:00:00Z","v":30.3,"lo":22.4,"hi":39.7},{"t":"2026-11-16T11:00:00Z","v":33.0,"lo":24.4,"hi":43.2},{"t":"2026-11-16T12:00:00Z","v":32.0,"lo":23.7,"hi":41.9},{"t":"2026-11-16T13:00:00Z","v":24.3,"lo":18.0,"hi":31.8},{"t":"2026-11-16T14:00:00Z","v":24.7,"lo":18.3,"hi":32.4},{"t":"2026-11-16T15:00:00Z","v":23.8,"lo":17.6,"hi":31.2},{"t":"2026-11-16T16:00:00Z","v":31.1,"lo":23.0,"hi":40.8},{"t":"2026-11-16T17:00:00Z","v":28.4,"lo":21.0,"hi":37.2},{"t":"2026-11-16T18:00:00Z","v":31.7,"lo":23.4,"hi":41.5},{"t":"2026-11-16T19:00:00Z","v":14.9,"lo":11.0,"hi":19.6},{"t":"2026-11-16T20:00:00Z","v":14.2,"lo":10.5,"hi":18.6},{"t":"2026-11-16T21:00:00Z","v":12.9,"lo":9.6,"hi":16.9},{"t":"2026-11-16T22:00:00Z","v":6.4,"lo":4.8,"hi":8.4},{"t":"2026-11-16T23:00:00Z","v":3.5,"lo":2.6,"hi":4.6},{"t":"2026-11-17T00:00:00Z","v":3.6,"lo":2.7,"hi":4.8},{"t":"2026-11-17T01:00:00Z","v":4.0,"lo":2.9,"hi":5.2},{"t":"2026-11-17T02:00:00Z","v":3.9,"lo":2.9,"hi":5.1},{"t":"2026-11-17T03:00:00Z","v":3.7,"lo":2.7,"hi":4.8},{"t":"2026-11-17T04:00:00Z","v":3.7,"lo":2.8,"hi":4.9},{"t":"2026-11-17T05:00:00Z","v":10.4,"lo":7.7,"hi":13.6},{"t":"2026-11-17T06:00:00Z","v":16.3,"lo":12.1,"hi":21.4},{"t":"2026-11-17T07:00:00Z","v":20.4,"lo":15.1,"hi":26.7},{"t":"2026-11-17T08:00:00Z","v":23.1,"lo":17.1,"hi":30.2},{"t":"2026-11-17T09:00:00Z","v":30.6,"lo":22.7,"hi":40.1},{"t":"2026-11-17T10:00:00Z","v":31.0,"lo":22.9,"hi":40.6},{"t":"2026-11-17T11:00:00Z","v":32.2,"lo":23.8,"hi":42.2},{"t":"2026-11-17T12:00:00Z","v":32.6,"lo":24.1,"hi":42.7},{"t":"2026-11-17T13:00:00Z","v":24.9,"lo":18.4,"hi":32.6},{"t":"2026-11-17T14:00:00Z","v":24.7,"lo":18.3,"hi":32.3},{"t":"2026-11-17T15:00:00Z","v":24.0,"lo":17.8,"hi":31.5},{"t":"2026-11-17T16:00:00Z","v":31.3,"lo":23.2,"hi":41.1},{"t":"2026-11-17T17:00:00Z","v":29.9,"lo":22.2,"hi":39.2},{"t":"2026-11-17T18:00:00Z","v":29.0,"lo":21.4,"hi":38.0},{"t":"2026-11-17T19:00:00Z","v":14.1,"lo":10.5,"hi":18.5},{"t":"2026-11-17T20:00:00Z","v":13.3,"lo":9.8,"hi":17.4},{"t":"2026-11-17T21:00:00Z","v":13.0,"lo":9.6,"hi":17.0},{"t":"2026-11-17T22:00:00Z","v":5.8,"lo":4.3,"hi":7.6},{"t":"2026-11-17T23:00:00Z","v":3.9,"lo":2.9,"hi":5.1}],"7d":[{"t":"2026-11-16T00:00:00Z","v":3.9,"lo":2.9,"hi":5.2},{"t":"2026-11-16T01:00:00Z","v":3.9,"lo":2.9,"hi":5.2},{"t":"2026-11-16T02:00:00Z","v":3.9,"lo":2.9,"hi":5.1},{"t":"2026-11-16T03:00:00Z","v":4.0,"lo":2.9,"hi":5.2},{"t":"2026-11-16T04:00:00Z","v":3.9,"lo":2.9,"hi":5.2},{"t":"2026-11-16T05:00:00Z","v":10.7,"lo":7.9,"hi":14.0},{"t":"2026-11-16T06:00:00Z","v":15.0,"lo":11.1,"hi":19.7},{"t":"2026-11-16T07:00:00Z","v":18.2,"lo":13.5,"hi":23.9},{"t":"2026-11-16T08:00:00Z","v":22.3,"lo":16.5,"hi":29.3},{"t":"2026-11-16T09:00:00Z","v":30.3,"lo":22.4,"hi":39.7},{"t":"2026-11-16T10:00:00Z","v":30.3,"lo":22.4,"hi":39.7},{"t":"2026-11-16T11:00:00Z","v":33.0,"lo":24.4,"hi":43.2},{"t":"2026-11-16T12:00:00Z","v":32.0,"lo":23.7,"hi":41.9},{"t":"2026-11-16T13:00:00Z","v":24.3,"lo":18.0,"hi":31.8},{"t":"2026-11-16T14:00:00Z","v":24.7,"lo":18.3,"hi":32.4},{"t":"2026-11-16T15:00:00Z","v":23.8,"lo":17.6,"hi":31.2},{"t":"2026-11-16T16:00:00Z","v":31.1,"lo":23.0,"hi":40.8},{"t":"2026-11-16T17:00:00Z","v":28.4,"lo":21.0,"hi":37.2},{"t":"2026-11-16T18:00:00Z","v":31.7,"lo":23.4,"hi":41.5},{"t":"2026-11-16T19:00:00Z","v":14.9,"lo":11.0,"hi":19.6},{"t":"2026-11-16T20:00:00Z","v":14.2,"lo":10.5,"hi":18.6},{"t":"2026-11-16T21:00:00Z","v":12.9,"lo":9.6,"hi":16.9},{"t":"2026-11-16T22:00:00Z","v":6.4,"lo":4.8,"hi":8.4},{"t":"2026-11-16T23:00:00Z","v":3.5,"lo":2.6,"hi":4.6},{"t":"2026-11-17T00:00:00Z","v":3.6,"lo":2.7,"hi":4.8},{"t":"2026-11-17T01:00:00Z","v":4.0,"lo":2.9,"hi":5.2},{"t":"2026-11-17T02:00:00Z","v":3.9,"lo":2.9,"hi":5.1},{"t":"2026-11-17T03:00:00Z","v":3.7,"lo":2.7,"hi":4.8},{"t":"2026-11-17T04:00:00Z","v":3.7,"lo":2.8,"hi":4.9},{"t":"2026-11-17T05:00:00Z","v":10.4,"lo":7.7,"hi":13.6},{"t":"2026-11-17T06:00:00Z","v":16.3,"lo":12.1,"hi":21.4},{"t":"2026-11-17T07:00:00Z","v":20.4,"lo":15.1,"hi":26.7},{"t":"2026-11-17T08:00:00Z","v":23.1,"lo":17.1,"hi":30.2},{"t":"2026-11-17T09:00:00Z","v":30.6,"lo":22.7,"hi":40.1},{"t":"2026-11-17T10:00:00Z","v":31.0,"lo":22.9,"hi":40.6},{"t":"2026-11-17T11:00:00Z","v":32.2,"lo":23.8,"hi":42.2},{"t":"2026-11-17T12:00:00Z","v":32.6,"lo":24.1,"hi":42.7},{"t":"2026-11-17T13:00:00Z","v":24.9,"lo":18.4,"hi":32.6},{"t":"2026-11-17T14:00:00Z","v":24.7,"lo":18.3,"hi":32.3}Line truncated
|
||||||
Vendored
+24
@@ -0,0 +1,24 @@
|
|||||||
|
{
|
||||||
|
"data_version": "2026-11-07T23:51:00Z",
|
||||||
|
"model_version": "histgb-2026-11-14",
|
||||||
|
"context_version": "2026-11-14T03:00:00Z",
|
||||||
|
"coverage": {
|
||||||
|
"sensors": 8,
|
||||||
|
"from": "2026-06-12T00:00:00Z",
|
||||||
|
"to": "2026-11-07T23:51:00Z",
|
||||||
|
"cadence_min": 15
|
||||||
|
},
|
||||||
|
"metrics": {
|
||||||
|
"model": "weather",
|
||||||
|
"mae": 3.36,
|
||||||
|
"wape": 27.8,
|
||||||
|
"r2": 0.779,
|
||||||
|
"baseline_mae": 5.4,
|
||||||
|
"baseline_wape": 44.7
|
||||||
|
},
|
||||||
|
"limits": [
|
||||||
|
"estimated devices, not people",
|
||||||
|
"8 sensors in a 580 m cluster",
|
||||||
|
"observed weather in training; forecast weather in scenarios"
|
||||||
|
]
|
||||||
|
}
|
||||||
Vendored
+74
@@ -0,0 +1,74 @@
|
|||||||
|
[
|
||||||
|
{
|
||||||
|
"id": "hn-bahnhof-01",
|
||||||
|
"name": "Bahnhof",
|
||||||
|
"lat": 49.1429,
|
||||||
|
"lon": 9.2076,
|
||||||
|
"mean": 24.2,
|
||||||
|
"p95": 88.2,
|
||||||
|
"battery": 71
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "hn-deutschhof-01",
|
||||||
|
"name": "Deutschhof",
|
||||||
|
"lat": 49.1397,
|
||||||
|
"lon": 9.2149,
|
||||||
|
"mean": 14.0,
|
||||||
|
"p95": 49.6,
|
||||||
|
"battery": null
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "hn-kaiserstrasse-01",
|
||||||
|
"name": "Kaiserstra\u00dfe",
|
||||||
|
"lat": 49.1419,
|
||||||
|
"lon": 9.2096,
|
||||||
|
"mean": 21.1,
|
||||||
|
"p95": 74.1,
|
||||||
|
"battery": 64
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "hn-marktplatz-01",
|
||||||
|
"name": "Marktplatz",
|
||||||
|
"lat": 49.1426,
|
||||||
|
"lon": 9.212,
|
||||||
|
"mean": 17.9,
|
||||||
|
"p95": 63.8,
|
||||||
|
"battery": 83
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "hn-neckar-01",
|
||||||
|
"name": "Neckarufer",
|
||||||
|
"lat": 49.1448,
|
||||||
|
"lon": 9.2087,
|
||||||
|
"mean": 9.4,
|
||||||
|
"p95": 35.4,
|
||||||
|
"battery": 92
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "hn-rathaus-01",
|
||||||
|
"name": "Rathaus",
|
||||||
|
"lat": 49.1422,
|
||||||
|
"lon": 9.2131,
|
||||||
|
"mean": 15.6,
|
||||||
|
"p95": 55.9,
|
||||||
|
"battery": 58
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "hn-stadtgalerie-01",
|
||||||
|
"name": "Stadtgalerie",
|
||||||
|
"lat": 49.1427,
|
||||||
|
"lon": 9.2109,
|
||||||
|
"mean": 22.6,
|
||||||
|
"p95": 67.2,
|
||||||
|
"battery": 87
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "hn-theater-01",
|
||||||
|
"name": "Theater",
|
||||||
|
"lat": 49.1402,
|
||||||
|
"lon": 9.2124,
|
||||||
|
"mean": 11.7,
|
||||||
|
"p95": 41.7,
|
||||||
|
"battery": 49
|
||||||
|
}
|
||||||
|
]
|
||||||
Vendored
+1
@@ -0,0 +1 @@
|
|||||||
|
{"hn-bahnhof-01":[{"t":"2026-10-25T00:00:00Z","v":3.6},{"t":"2026-10-25T00:15:00Z","v":4.1},{"t":"2026-10-25T00:30:00Z","v":4.4},{"t":"2026-10-25T00:45:00Z","v":4.0},{"t":"2026-10-25T01:00:00Z","v":3.7},{"t":"2026-10-25T01:15:00Z","v":3.6},{"t":"2026-10-25T01:30:00Z","v":4.3},{"t":"2026-10-25T01:45:00Z","v":3.8},{"t":"2026-10-25T02:00:00Z","v":4.5},{"t":"2026-10-25T02:15:00Z","v":3.7},{"t":"2026-10-25T02:30:00Z","v":4.4},{"t":"2026-10-25T02:45:00Z","v":4.3},{"t":"2026-10-25T03:00:00Z","v":4.2},{"t":"2026-10-25T03:15:00Z","v":4.1},{"t":"2026-10-25T03:30:00Z","v":3.9},{"t":"2026-10-25T03:45:00Z","v":3.8},{"t":"2026-10-25T04:00:00Z","v":3.8},{"t":"2026-10-25T04:15:00Z","v":3.7},{"t":"2026-10-25T04:30:00Z","v":4.4},{"t":"2026-10-25T04:45:00Z","v":4.1},{"t":"2026-10-25T05:00:00Z","v":12.8},{"t":"2026-10-25T05:15:00Z","v":12.7},{"t":"2026-10-25T05:30:00Z","v":12.9},{"t":"2026-10-25T05:45:00Z","v":11.4},{"t":"2026-10-25T06:00:00Z","v":16.3},{"t":"2026-10-25T06:15:00Z","v":17.5},{"t":"2026-10-25T06:30:00Z","v":17.3},{"t":"2026-10-25T06:45:00Z","v":17.0},{"t":"2026-10-25T07:00:00Z","v":23.5},{"t":"2026-10-25T07:15:00Z","v":23.5},{"t":"2026-10-25T07:30:00Z","v":20.4},{"t":"2026-10-25T07:45:00Z","v":19.5},{"t":"2026-10-25T08:00:00Z","v":26.7},{"t":"2026-10-25T08:15:00Z","v":25.3},{"t":"2026-10-25T08:30:00Z","v":28.2},{"t":"2026-10-25T08:45:00Z","v":23.6},{"t":"2026-10-25T09:00:00Z","v":30.1},{"t":"2026-10-25T09:15:00Z","v":31.2},{"t":"2026-10-25T09:30:00Z","v":30.4},{"t":"2026-10-25T09:45:00Z","v":33.7},{"t":"2026-10-25T10:00:00Z","v":37.2},{"t":"2026-10-25T10:15:00Z","v":32.1},{"t":"2026-10-25T10:30:00Z","v":36.9},{"t":"2026-10-25T10:45:00Z","v":30.6},{"t":"2026-10-25T11:00:00Z","v":35.9},{"t":"2026-10-25T11:15:00Z","v":31.7},{"t":"2026-10-25T11:30:00Z","v":30.7},{"t":"2026-10-25T11:45:00Z","v":35.4},{"t":"2026-10-25T12:00:00Z","v":36.0},{"t":"2026-10-25T12:15:00Z","v":31.3},{"t":"2026-10-25T12:30:00Z","v":30.0},{"t":"2026-10-25T12:45:00Z","v":32.9},{"t":"2026-10-25T13:00:00Z","v":27.5},{"t":"2026-10-25T13:15:00Z","v":26.5},{"t":"2026-10-25T13:30:00Z","v":28.1},{"t":"2026-10-25T13:45:00Z","v":29.8},{"t":"2026-10-25T14:00:00Z","v":26.4},{"t":"2026-10-25T14:15:00Z","v":26.5},{"t":"2026-10-25T14:30:00Z","v":29.2},{"t":"2026-10-25T14:45:00Z","v":29.3},{"t":"2026-10-25T15:00:00Z","v":30.5},{"t":"2026-10-25T15:15:00Z","v":30.7},{"t":"2026-10-25T15:30:00Z","v":27.4},{"t":"2026-10-25T15:45:00Z","v":25.2},{"t":"2026-10-25T16:00:00Z","v":31.8},{"t":"2026-10-25T16:15:00Z","v":28.9},{"t":"2026-10-25T16:30:00Z","v":33.3},{"t":"2026-10-25T16:45:00Z","v":32.8},{"t":"2026-10-25T17:00:00Z","v":33.7},{"t":"2026-10-25T17:15:00Z","v":31.5},{"t":"2026-10-25T17:30:00Z","v":33.8},{"t":"2026-10-25T17:45:00Z","v":31.9},{"t":"2026-10-25T18:00:00Z","v":29.9},{"t":"2026-10-25T18:15:00Z","v":32.6},{"t":"2026-10-25T18:30:00Z","v":31.8},{"t":"2026-10-25T18:45:00Z","v":32.6},{"t":"2026-10-25T19:00:00Z","v":16.7},{"t":"2026-10-25T19:15:00Z","v":15.7},{"t":"2026-10-25T19:30:00Z","v":16.2},{"t":"2026-10-25T19:45:00Z","v":15.8},{"t":"2026-10-25T20:00:00Z","v":15.8},{"t":"2026-10-25T20:15:00Z","v":14.4},{"t":"2026-10-25T20:30:00Z","v":16.5},{"t":"2026-10-25T20:45:00Z","v":15.7},{"t":"2026-10-25T21:00:00Z","v":16.7},{"t":"2026-10-25T21:15:00Z","v":13.8},{"t":"2026-10-25T21:30:00Z","v":16.7},{"t":"2026-10-25T21:45:00Z","v":14.2},{"t":"2026-10-25T22:00:00Z","v":7.2},{"t":"2026-10-25T22:15:00Z","v":6.5},{"t":"2026-10-25T22:30:00Z","v":7.1},{"t":"2026-10-25T22:45:00Z","v":5.9},{"t":"2026-10-25T23:00:00Z","v":3.6},{"t":"2026-10-25T23:15:00Z","v":4.1},{"t":"2026-10-25T23:30:00Z","v":3.9},{"t":"2026-10-25T23:45:00Z","v":3.7},{"t":"2026-10-26T00:00:00Z","v":3.4},{"t":"2026-10-26T00:15:00Z","v":3.5},{"t":"2026-10-26T00:30:00Z","v":4.0},{"t":"2026-10-26T00:45:00Z","v":3.7},{"t":"2026-10-26T01:00:00Z","v":3.9},{"t":"2026-10-26T01:15:00Z","v":3.7},{"t":"2026-10-26T01:30:00Z","v":4.0},{"t":"2026-10-26T01:45:00Z","v":3.9},{"t":"2026-10-26T02:00:00Z","v":3.5},{"t":"2026-10-26T02:15:00Z","v":3.9},{"t":"2026-10-26T02:30:00Z","v":4.0},{"t":"2026-10-26T02:45:00Z","v":3.5},{"t":"2026-10-26T03:00:00Z","v":4.2},{"t":"2026-10-26T03:15:00Z","v":3.3},{"t":"2026-10-26T03:30:00Z","v":4.1},{"t":"2026-10-26T03:45:00Z","v":3.3},{"t":"2026-10-26T04:00:00Z","v":3.6},{"t":"2026-10-26T04:15:00Z","v":3.7},{"t":"2026-10-26T04:30:00Z","v":4.1},{"t":"2026-10-26T04:45:00Z","v":3.3},{"t":"2026-10-26T05:00:00Z","v":11.8},{"t":"2026-10-26T05:15:00Z","v":11.8},{"t":"2026-10-26T05:30:00Z","v":10.2},{"t":"2026-10-26T05:45:00Z","v":11.6},{"t":"2026-10-26T06:00:00Z","v":13.7},{"t":"2026-10-26T06:15:00Z","v":15.1},{"t":"2026-10-26T06:30:00Z","v":15.0},{"t":"2026-10-26T06:45:00Z","v":15.7},{"t":"2026-10-26T07:00:00Z","v":20.6},{"t":"2026-10-26T07:15:00Z","v":19.8},{"t":"2026-10-26T07:30:00Z","v":17.6},{"t":"2026-10-26T07:45:00Z","v":18.1},{"t":"2026-10-26T08:00:00Z","v":22.7},{"t":"2026-10-26T08:15:00Z","v":23.1},{"t":"2026-10-26T08:30:00Z","v":21.3},{"t":"2026-10-26T08:45:00Z","v":22.7},{"t":"2026-10Line truncated
|
||||||
Reference in new issue
Block a user