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,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
|
||||
}
|
||||
Reference in new issue
Block a user