feat: PreZero priority API proxy #4
No files matched your search
@@ -0,0 +1,97 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"pulsecast/api/internal/model"
|
||||
)
|
||||
|
||||
// PreZero query defaults and bounds from PREZERO_API_CONTRACT.md §3.
|
||||
const (
|
||||
defaultPreZeroLimit = 50
|
||||
maxPreZeroLimit = 500
|
||||
)
|
||||
|
||||
// PreZeroPriorities are the accepted tier filters.
|
||||
var PreZeroPriorities = []string{"high", "medium", "low"}
|
||||
|
||||
// handlePreZeroSummary proxies GET /api/prezero/summary to FastAPI.
|
||||
func (s *Server) handlePreZeroSummary(w http.ResponseWriter, r *http.Request) {
|
||||
if s.prezero == nil {
|
||||
writeError(w, http.StatusBadGateway, "ml_unavailable", "FastAPI PreZero client is not configured")
|
||||
return
|
||||
}
|
||||
status, body, err := s.prezero.PreZeroSummary(r.Context())
|
||||
if err != nil {
|
||||
slog.Warn("prezero summary proxy failed", "error", err)
|
||||
writeError(w, http.StatusBadGateway, "ml_unavailable", "FastAPI is unavailable")
|
||||
return
|
||||
}
|
||||
relayMLResponse(w, status, body)
|
||||
}
|
||||
|
||||
// handlePreZeroPriority proxies GET /api/prezero/priority. The query is
|
||||
// validated here so bad input never reaches FastAPI.
|
||||
func (s *Server) handlePreZeroPriority(w http.ResponseWriter, r *http.Request) {
|
||||
query := r.URL.Query()
|
||||
|
||||
priority := query.Get("priority")
|
||||
if priority != "" && !model.Contains(PreZeroPriorities, priority) {
|
||||
writeError(w, http.StatusBadRequest, "bad_request", "priority must be high, medium or low")
|
||||
return
|
||||
}
|
||||
|
||||
limit := defaultPreZeroLimit
|
||||
if raw := query.Get("limit"); raw != "" {
|
||||
parsed, err := strconv.Atoi(raw)
|
||||
if err != nil || parsed < 1 || parsed > maxPreZeroLimit {
|
||||
writeError(w, http.StatusBadRequest, "bad_request", "limit must be an integer between 1 and 500")
|
||||
return
|
||||
}
|
||||
limit = parsed
|
||||
}
|
||||
|
||||
offset := 0
|
||||
if raw := query.Get("offset"); raw != "" {
|
||||
parsed, err := strconv.Atoi(raw)
|
||||
if err != nil || parsed < 0 {
|
||||
writeError(w, http.StatusBadRequest, "bad_request", "offset must be an integer greater than or equal to 0")
|
||||
return
|
||||
}
|
||||
offset = parsed
|
||||
}
|
||||
|
||||
if s.prezero == nil {
|
||||
writeError(w, http.StatusBadGateway, "ml_unavailable", "FastAPI PreZero client is not configured")
|
||||
return
|
||||
}
|
||||
status, body, err := s.prezero.PreZeroPriority(r.Context(), priority, limit, offset)
|
||||
if err != nil {
|
||||
slog.Warn("prezero priority proxy failed", "priority", priority, "error", err)
|
||||
writeError(w, http.StatusBadGateway, "ml_unavailable", "FastAPI is unavailable")
|
||||
return
|
||||
}
|
||||
relayMLResponse(w, status, body)
|
||||
}
|
||||
|
||||
// handlePreZeroContainer proxies GET /api/prezero/containers/{location_id}.
|
||||
func (s *Server) handlePreZeroContainer(w http.ResponseWriter, r *http.Request) {
|
||||
locationID := r.PathValue("location_id")
|
||||
if locationID == "" {
|
||||
writeError(w, http.StatusNotFound, "not_found", "container not found")
|
||||
return
|
||||
}
|
||||
if s.prezero == nil {
|
||||
writeError(w, http.StatusBadGateway, "ml_unavailable", "FastAPI PreZero client is not configured")
|
||||
return
|
||||
}
|
||||
status, body, err := s.prezero.PreZeroContainer(r.Context(), locationID)
|
||||
if err != nil {
|
||||
slog.Warn("prezero container proxy failed", "location_id", locationID, "error", err)
|
||||
writeError(w, http.StatusBadGateway, "ml_unavailable", "FastAPI is unavailable")
|
||||
return
|
||||
}
|
||||
relayMLResponse(w, status, body)
|
||||
}
|
||||
@@ -0,0 +1,336 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// stubPreZero implements MLClient (through the embedded stubML) and
|
||||
// PreZeroClient, so New's optional type assertion picks it up.
|
||||
type stubPreZero struct {
|
||||
*stubML
|
||||
calls atomic.Int32
|
||||
|
||||
summaryFn func(context.Context) (int, []byte, error)
|
||||
priorityFn func(context.Context, string, int, int) (int, []byte, error)
|
||||
containerFn func(context.Context, string) (int, []byte, error)
|
||||
|
||||
gotPriority string
|
||||
gotLimit int
|
||||
gotOffset int
|
||||
gotLocation string
|
||||
}
|
||||
|
||||
func newStubPreZero() *stubPreZero {
|
||||
return &stubPreZero{stubML: &stubML{}}
|
||||
}
|
||||
|
||||
func (s *stubPreZero) PreZeroSummary(ctx context.Context) (int, []byte, error) {
|
||||
s.calls.Add(1)
|
||||
if s.summaryFn == nil {
|
||||
return 0, nil, errors.New("ml unavailable")
|
||||
}
|
||||
return s.summaryFn(ctx)
|
||||
}
|
||||
|
||||
func (s *stubPreZero) PreZeroPriority(ctx context.Context, priority string, limit, offset int) (int, []byte, error) {
|
||||
s.calls.Add(1)
|
||||
s.gotPriority, s.gotLimit, s.gotOffset = priority, limit, offset
|
||||
if s.priorityFn == nil {
|
||||
return 0, nil, errors.New("ml unavailable")
|
||||
}
|
||||
return s.priorityFn(ctx, priority, limit, offset)
|
||||
}
|
||||
|
||||
func (s *stubPreZero) PreZeroContainer(ctx context.Context, locationID string) (int, []byte, error) {
|
||||
s.calls.Add(1)
|
||||
s.gotLocation = locationID
|
||||
if s.containerFn == nil {
|
||||
return 0, nil, errors.New("ml unavailable")
|
||||
}
|
||||
return s.containerFn(ctx, locationID)
|
||||
}
|
||||
|
||||
func newPreZeroServer(t *testing.T, client MLClient) *httptest.Server {
|
||||
t.Helper()
|
||||
_, ts := newTestServer(t, client, nil)
|
||||
return ts
|
||||
}
|
||||
|
||||
// getRaw is getJSON's byte-preserving sibling: the PreZero tests assert that
|
||||
// the upstream body passes through unchanged.
|
||||
func getRaw(t *testing.T, url string) (*http.Response, []byte) {
|
||||
t.Helper()
|
||||
resp, err := http.Get(url)
|
||||
if err != nil {
|
||||
t.Fatalf("GET %s: %v", url, err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
raw, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
t.Fatalf("read GET %s: %v", url, err)
|
||||
}
|
||||
return resp, raw
|
||||
}
|
||||
|
||||
func TestPreZeroSummaryPassthrough(t *testing.T) {
|
||||
const body = `{"meta":{"rows":11701,"containers":449},"summary":{"priority_counts":{"high":88,"medium":248,"low":113}}}`
|
||||
stub := newStubPreZero()
|
||||
stub.summaryFn = func(context.Context) (int, []byte, error) {
|
||||
return http.StatusOK, []byte(body), nil
|
||||
}
|
||||
ts := newPreZeroServer(t, stub)
|
||||
|
||||
resp, raw := getRaw(t, ts.URL+"/api/prezero/summary")
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
t.Fatalf("summary status=%d body=%s, want 200", resp.StatusCode, raw)
|
||||
}
|
||||
if got := resp.Header.Get("Content-Type"); got != "application/json; charset=utf-8" {
|
||||
t.Errorf("summary Content-Type=%q, want JSON", got)
|
||||
}
|
||||
if string(raw) != body {
|
||||
t.Fatalf("summary body=%s, want exact passthrough", raw)
|
||||
}
|
||||
var decoded struct {
|
||||
Summary struct {
|
||||
PriorityCounts map[string]int `json:"priority_counts"`
|
||||
} `json:"summary"`
|
||||
}
|
||||
if err := json.Unmarshal(raw, &decoded); err != nil {
|
||||
t.Fatalf("decode summary: %v", err)
|
||||
}
|
||||
if decoded.Summary.PriorityCounts["high"] != 88 ||
|
||||
decoded.Summary.PriorityCounts["medium"] != 248 ||
|
||||
decoded.Summary.PriorityCounts["low"] != 113 {
|
||||
t.Fatalf("priority counts=%v", decoded.Summary.PriorityCounts)
|
||||
}
|
||||
if got := stub.calls.Load(); got != 1 {
|
||||
t.Fatalf("client calls=%d, want 1", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPreZeroPriorityForwardsQuery(t *testing.T) {
|
||||
stub := newStubPreZero()
|
||||
stub.priorityFn = func(context.Context, string, int, int) (int, []byte, error) {
|
||||
return http.StatusOK, []byte(`{"total":88,"count":3,"offset":10,"limit":3,"containers":[{"location_id":"a"},{"location_id":"b"},{"location_id":"c"}]}`), nil
|
||||
}
|
||||
ts := newPreZeroServer(t, stub)
|
||||
|
||||
resp, raw := getRaw(t, ts.URL+"/api/prezero/priority?priority=high&limit=3&offset=10")
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
t.Fatalf("priority status=%d body=%s, want 200", resp.StatusCode, raw)
|
||||
}
|
||||
if stub.gotPriority != "high" || stub.gotLimit != 3 || stub.gotOffset != 10 {
|
||||
t.Fatalf("forwarded priority=%q limit=%d offset=%d, want high/3/10",
|
||||
stub.gotPriority, stub.gotLimit, stub.gotOffset)
|
||||
}
|
||||
var body struct {
|
||||
Total int `json:"total"`
|
||||
Count int `json:"count"`
|
||||
Containers []struct {
|
||||
LocationID string `json:"location_id"`
|
||||
} `json:"containers"`
|
||||
}
|
||||
if err := json.Unmarshal(raw, &body); err != nil {
|
||||
t.Fatalf("decode priority: %v", err)
|
||||
}
|
||||
if body.Total != 88 || body.Count != 3 || len(body.Containers) != 3 {
|
||||
t.Fatalf("priority body=%+v", body)
|
||||
}
|
||||
|
||||
// Omitted query parameters use the contract defaults.
|
||||
getRaw(t, ts.URL+"/api/prezero/priority")
|
||||
if stub.gotPriority != "" || stub.gotLimit != 50 || stub.gotOffset != 0 {
|
||||
t.Fatalf("defaults forwarded priority=%q limit=%d offset=%d, want empty/50/0",
|
||||
stub.gotPriority, stub.gotLimit, stub.gotOffset)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPreZeroPriorityValidationSkipsClient(t *testing.T) {
|
||||
stub := newStubPreZero()
|
||||
stub.priorityFn = func(context.Context, string, int, int) (int, []byte, error) {
|
||||
return http.StatusOK, []byte(`{"containers":[]}`), nil
|
||||
}
|
||||
ts := newPreZeroServer(t, stub)
|
||||
|
||||
for _, query := range []string{
|
||||
"priority=urgent",
|
||||
"priority=HIGH",
|
||||
"limit=0",
|
||||
"limit=501",
|
||||
"limit=-1",
|
||||
"limit=abc",
|
||||
"limit=1.5",
|
||||
"offset=-1",
|
||||
"offset=abc",
|
||||
} {
|
||||
resp, raw := getRaw(t, ts.URL+"/api/prezero/priority?"+query)
|
||||
if resp.StatusCode != http.StatusBadRequest {
|
||||
t.Errorf("%s: status=%d body=%s, want 400", query, resp.StatusCode, raw)
|
||||
continue
|
||||
}
|
||||
var envelope struct {
|
||||
Error struct {
|
||||
Code string `json:"code"`
|
||||
Message string `json:"message"`
|
||||
} `json:"error"`
|
||||
}
|
||||
if err := json.Unmarshal(raw, &envelope); err != nil {
|
||||
t.Errorf("%s: decode error envelope: %v", query, err)
|
||||
continue
|
||||
}
|
||||
if envelope.Error.Code != "bad_request" || envelope.Error.Message == "" {
|
||||
t.Errorf("%s: error envelope=%+v", query, envelope.Error)
|
||||
}
|
||||
}
|
||||
if got := stub.calls.Load(); got != 0 {
|
||||
t.Fatalf("client calls=%d for invalid queries, want 0", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPreZeroContainerPassthrough(t *testing.T) {
|
||||
const locationID = "eecbf6fa-decf-46da-b110-bf014e7c181d"
|
||||
stub := newStubPreZero()
|
||||
stub.containerFn = func(_ context.Context, locationID string) (int, []byte, error) {
|
||||
if locationID == "eecbf6fa-decf-46da-b110-bf014e7c181d" {
|
||||
return http.StatusOK, []byte(`{"container":{"location_id":"eecbf6fa-decf-46da-b110-bf014e7c181d","priority":"high"},"readings":[{"date":"2026-09-29"}]}`), nil
|
||||
}
|
||||
return http.StatusNotFound, []byte(`{"error":{"code":"not_found","message":"container not found"}}`), nil
|
||||
}
|
||||
ts := newPreZeroServer(t, stub)
|
||||
|
||||
resp, raw := getRaw(t, ts.URL+"/api/prezero/containers/"+locationID)
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
t.Fatalf("container status=%d body=%s, want 200", resp.StatusCode, raw)
|
||||
}
|
||||
if stub.gotLocation != locationID {
|
||||
t.Errorf("forwarded location=%q, want %q", stub.gotLocation, locationID)
|
||||
}
|
||||
var body struct {
|
||||
Container struct {
|
||||
LocationID string `json:"location_id"`
|
||||
Priority string `json:"priority"`
|
||||
} `json:"container"`
|
||||
}
|
||||
if err := json.Unmarshal(raw, &body); err != nil {
|
||||
t.Fatalf("decode container: %v", err)
|
||||
}
|
||||
if body.Container.LocationID != locationID || body.Container.Priority != "high" {
|
||||
t.Fatalf("container=%+v", body.Container)
|
||||
}
|
||||
|
||||
resp, raw = getRaw(t, ts.URL+"/api/prezero/containers/unknown-id")
|
||||
if resp.StatusCode != http.StatusNotFound {
|
||||
t.Fatalf("unknown container status=%d body=%s, want 404", resp.StatusCode, raw)
|
||||
}
|
||||
if !json.Valid(raw) {
|
||||
t.Fatalf("unknown container body is not JSON: %s", raw)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPreZeroUnavailableReturns502(t *testing.T) {
|
||||
failing := newStubPreZero()
|
||||
failing.summaryFn = func(context.Context) (int, []byte, error) {
|
||||
return 0, nil, errors.New("connection refused")
|
||||
}
|
||||
failing.priorityFn = func(context.Context, string, int, int) (int, []byte, error) {
|
||||
return 0, nil, errors.New("connection refused")
|
||||
}
|
||||
failing.containerFn = func(context.Context, string) (int, []byte, error) {
|
||||
return 0, nil, errors.New("connection refused")
|
||||
}
|
||||
ts := newPreZeroServer(t, failing)
|
||||
|
||||
for _, path := range []string{
|
||||
"/api/prezero/summary",
|
||||
"/api/prezero/priority?priority=high",
|
||||
"/api/prezero/containers/abc",
|
||||
} {
|
||||
resp, raw := getRaw(t, ts.URL+path)
|
||||
if resp.StatusCode != http.StatusBadGateway {
|
||||
t.Errorf("%s: status=%d body=%s, want 502", path, resp.StatusCode, raw)
|
||||
continue
|
||||
}
|
||||
var envelope struct {
|
||||
Error struct {
|
||||
Code string `json:"code"`
|
||||
} `json:"error"`
|
||||
}
|
||||
if err := json.Unmarshal(raw, &envelope); err != nil || envelope.Error.Code != "ml_unavailable" {
|
||||
t.Errorf("%s: error=%+v err=%v, want ml_unavailable", path, envelope.Error, err)
|
||||
}
|
||||
}
|
||||
|
||||
// Prediction-only stubs do not implement PreZeroClient; that is also 502.
|
||||
unconfigured := newPreZeroServer(t, &stubML{})
|
||||
for _, path := range []string{
|
||||
"/api/prezero/summary",
|
||||
"/api/prezero/priority",
|
||||
"/api/prezero/containers/abc",
|
||||
} {
|
||||
resp, raw := getRaw(t, unconfigured.URL+path)
|
||||
if resp.StatusCode != http.StatusBadGateway {
|
||||
t.Errorf("unconfigured %s: status=%d body=%s, want 502", path, resp.StatusCode, raw)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestPreZeroRouting(t *testing.T) {
|
||||
stub := newStubPreZero()
|
||||
stub.summaryFn = func(context.Context) (int, []byte, error) {
|
||||
return http.StatusOK, []byte(`{}`), nil
|
||||
}
|
||||
stub.priorityFn = func(context.Context, string, int, int) (int, []byte, error) {
|
||||
return http.StatusOK, []byte(`{}`), nil
|
||||
}
|
||||
stub.containerFn = func(context.Context, string) (int, []byte, error) {
|
||||
return http.StatusOK, []byte(`{}`), nil
|
||||
}
|
||||
ts := newPreZeroServer(t, stub)
|
||||
|
||||
for _, path := range []string{
|
||||
"/api/prezero/summary",
|
||||
"/api/prezero/priority",
|
||||
"/api/prezero/containers/abc",
|
||||
} {
|
||||
req, err := http.NewRequest(http.MethodPost, ts.URL+path, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
t.Fatalf("POST %s: %v", path, err)
|
||||
}
|
||||
resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusMethodNotAllowed {
|
||||
t.Errorf("POST %s status=%d, want 405", path, resp.StatusCode)
|
||||
}
|
||||
if allow := resp.Header.Get("Allow"); allow != "GET" {
|
||||
t.Errorf("POST %s Allow=%q, want GET", path, allow)
|
||||
}
|
||||
}
|
||||
|
||||
for _, path := range []string{
|
||||
"/api/prezero",
|
||||
"/api/prezero/unknown",
|
||||
"/api/prezero/containers/",
|
||||
"/api/prezero/containers/a/b",
|
||||
} {
|
||||
resp, raw := getRaw(t, ts.URL+path)
|
||||
if resp.StatusCode != http.StatusNotFound {
|
||||
t.Errorf("GET %s status=%d body=%s, want 404", path, resp.StatusCode, raw)
|
||||
}
|
||||
if !json.Valid(raw) {
|
||||
t.Errorf("GET %s body is not JSON: %s", path, raw)
|
||||
}
|
||||
}
|
||||
if got := stub.calls.Load(); got != 0 {
|
||||
t.Fatalf("client calls=%d for unroutable requests, want 0", got)
|
||||
}
|
||||
}
|
||||
+40
-11
@@ -34,11 +34,20 @@ type TrainClient interface {
|
||||
TrainStatus(ctx context.Context, jobID string) (int, []byte, error)
|
||||
}
|
||||
|
||||
// PreZeroClient is the optional FastAPI PreZero read-only surface. Like
|
||||
// TrainClient it is separate so prediction-only stubs keep working.
|
||||
type PreZeroClient interface {
|
||||
PreZeroSummary(ctx context.Context) (int, []byte, error)
|
||||
PreZeroPriority(ctx context.Context, priority string, limit, offset int) (int, []byte, error)
|
||||
PreZeroContainer(ctx context.Context, locationID string) (int, []byte, error)
|
||||
}
|
||||
|
||||
// Server holds process-wide state. One instance per pod.
|
||||
type Server struct {
|
||||
cfg config.Config
|
||||
cache *cache.Cache
|
||||
ml MLClient
|
||||
prezero PreZeroClient
|
||||
hub *sse.Hub
|
||||
scenario *scenario.State
|
||||
loc *time.Location
|
||||
@@ -61,10 +70,15 @@ func New(cfg config.Config, snapshots *cache.Cache, client MLClient, hub *sse.Hu
|
||||
if cfg.MLTimeout <= 0 {
|
||||
cfg.MLTimeout = ml.DefaultTimeout
|
||||
}
|
||||
var prezero PreZeroClient
|
||||
if pc, ok := client.(PreZeroClient); ok {
|
||||
prezero = pc
|
||||
}
|
||||
return &Server{
|
||||
cfg: cfg,
|
||||
cache: snapshots,
|
||||
ml: client,
|
||||
prezero: prezero,
|
||||
hub: hub,
|
||||
scenario: scenario.New(),
|
||||
loc: loc,
|
||||
@@ -89,23 +103,28 @@ func (s *Server) Handler() http.Handler {
|
||||
mux.HandleFunc("POST /api/scenario", s.requireControlAuth(s.handleScenarioPost))
|
||||
mux.HandleFunc("POST /api/train", s.requireControlAuth(s.handleTrain))
|
||||
mux.HandleFunc("GET /api/train/{job_id}", s.requireControlAuth(s.handleTrainStatus))
|
||||
mux.HandleFunc("GET /api/prezero/summary", s.handlePreZeroSummary)
|
||||
mux.HandleFunc("GET /api/prezero/priority", s.handlePreZeroPriority)
|
||||
mux.HandleFunc("GET /api/prezero/containers/{location_id}", s.handlePreZeroContainer)
|
||||
mux.HandleFunc("GET /api/stream", s.handleStream)
|
||||
|
||||
return s.recoverer(s.withCORS(s.routeCheck(mux)))
|
||||
}
|
||||
|
||||
var methodTable = map[string][]string{
|
||||
"/api/healthz": {"GET"},
|
||||
"/api/readyz": {"GET"},
|
||||
"/api/meta": {"GET"},
|
||||
"/api/sensors": {"GET"},
|
||||
"/api/series": {"GET"},
|
||||
"/api/context": {"GET"},
|
||||
"/api/forecast": {"GET"},
|
||||
"/api/staffing": {"GET"},
|
||||
"/api/scenario": {"GET", "POST"},
|
||||
"/api/train": {"POST"},
|
||||
"/api/stream": {"GET"},
|
||||
"/api/healthz": {"GET"},
|
||||
"/api/readyz": {"GET"},
|
||||
"/api/meta": {"GET"},
|
||||
"/api/sensors": {"GET"},
|
||||
"/api/series": {"GET"},
|
||||
"/api/context": {"GET"},
|
||||
"/api/forecast": {"GET"},
|
||||
"/api/staffing": {"GET"},
|
||||
"/api/scenario": {"GET", "POST"},
|
||||
"/api/train": {"POST"},
|
||||
"/api/prezero/summary": {"GET"},
|
||||
"/api/prezero/priority": {"GET"},
|
||||
"/api/stream": {"GET"},
|
||||
}
|
||||
|
||||
// routeCheck keeps unknown routes and methods in the JSON error envelope;
|
||||
@@ -116,6 +135,9 @@ func (s *Server) routeCheck(next http.Handler) http.Handler {
|
||||
if !ok && isTrainJobPath(r.URL.Path) {
|
||||
methods, ok = []string{"GET"}, true
|
||||
}
|
||||
if !ok && isPreZeroContainerPath(r.URL.Path) {
|
||||
methods, ok = []string{"GET"}, true
|
||||
}
|
||||
if !ok {
|
||||
writeError(w, http.StatusNotFound, "not_found", "route not found")
|
||||
return
|
||||
@@ -135,6 +157,13 @@ func isTrainJobPath(path string) bool {
|
||||
return found && jobID != "" && !strings.Contains(jobID, "/")
|
||||
}
|
||||
|
||||
// isPreZeroContainerPath matches exactly one location id after
|
||||
// /api/prezero/containers/.
|
||||
func isPreZeroContainerPath(path string) bool {
|
||||
locationID, found := strings.CutPrefix(path, "/api/prezero/containers/")
|
||||
return found && locationID != "" && !strings.Contains(locationID, "/")
|
||||
}
|
||||
|
||||
func joinMethods(methods []string) string {
|
||||
out := ""
|
||||
for i, method := range methods {
|
||||
|
||||
@@ -11,6 +11,7 @@ import (
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
@@ -176,6 +177,28 @@ func (c *Client) TrainStatus(ctx context.Context, jobID string) (int, []byte, er
|
||||
return c.controlRequest(ctx, http.MethodGet, "/train/"+url.PathEscape(jobID), "", nil)
|
||||
}
|
||||
|
||||
// PreZeroSummary proxies GET /prezero/summary.
|
||||
func (c *Client) PreZeroSummary(ctx context.Context) (int, []byte, error) {
|
||||
return c.controlRequest(ctx, http.MethodGet, "/prezero/summary", "", nil)
|
||||
}
|
||||
|
||||
// PreZeroPriority proxies GET /prezero/priority. priority may be empty to
|
||||
// return every tier; limit and offset are always forwarded.
|
||||
func (c *Client) PreZeroPriority(ctx context.Context, priority string, limit, offset int) (int, []byte, error) {
|
||||
query := url.Values{}
|
||||
if priority != "" {
|
||||
query.Set("priority", priority)
|
||||
}
|
||||
query.Set("limit", strconv.Itoa(limit))
|
||||
query.Set("offset", strconv.Itoa(offset))
|
||||
return c.controlRequest(ctx, http.MethodGet, "/prezero/priority?"+query.Encode(), "", nil)
|
||||
}
|
||||
|
||||
// PreZeroContainer proxies GET /prezero/containers/{location_id}.
|
||||
func (c *Client) PreZeroContainer(ctx context.Context, locationID string) (int, []byte, error) {
|
||||
return c.controlRequest(ctx, http.MethodGet, "/prezero/containers/"+url.PathEscape(locationID), "", nil)
|
||||
}
|
||||
|
||||
// controlRequest performs a training/control request and returns the raw
|
||||
// upstream status and body. Non-2xx responses are not errors: the proxy
|
||||
// forwards them so clients see FastAPI's 400/404/409 semantics.
|
||||
|
||||
@@ -305,3 +305,71 @@ func TestTrainStatusForwardsJobIDAndUpstreamError(t *testing.T) {
|
||||
t.Fatalf("status=%d body=%s, want forwarded 404", status, body)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPreZeroClientsForwardRouteQueryAndStatus(t *testing.T) {
|
||||
var gotPaths, gotQueries []string
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodGet {
|
||||
t.Errorf("method=%s, want GET", r.Method)
|
||||
}
|
||||
gotPaths = append(gotPaths, r.URL.Path)
|
||||
gotQueries = append(gotQueries, r.URL.RawQuery)
|
||||
switch {
|
||||
case r.URL.Path == "/prezero/summary":
|
||||
_, _ = w.Write([]byte(`{"summary":{"priority_counts":{"high":88}}}`))
|
||||
case r.URL.Path == "/prezero/priority":
|
||||
_, _ = w.Write([]byte(`{"total":88,"count":1,"containers":[]}`))
|
||||
case r.URL.Path == "/prezero/containers/known-id":
|
||||
_, _ = w.Write([]byte(`{"container":{"location_id":"known-id"}}`))
|
||||
default:
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
_, _ = w.Write([]byte(`{"error":{"code":"not_found","message":"container not found"}}`))
|
||||
}
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
client := New(srv.URL, time.Second)
|
||||
status, body, err := client.PreZeroSummary(context.Background())
|
||||
if err != nil || status != http.StatusOK || !strings.Contains(string(body), `"high":88`) {
|
||||
t.Fatalf("summary status=%d body=%s err=%v", status, body, err)
|
||||
}
|
||||
|
||||
status, body, err = client.PreZeroPriority(context.Background(), "high", 3, 10)
|
||||
if err != nil || status != http.StatusOK || !strings.Contains(string(body), `"total":88`) {
|
||||
t.Fatalf("priority status=%d body=%s err=%v", status, body, err)
|
||||
}
|
||||
if _, _, err := client.PreZeroPriority(context.Background(), "", 50, 0); err != nil {
|
||||
t.Fatalf("priority defaults: %v", err)
|
||||
}
|
||||
|
||||
status, body, err = client.PreZeroContainer(context.Background(), "known-id")
|
||||
if err != nil || status != http.StatusOK || !strings.Contains(string(body), "known-id") {
|
||||
t.Fatalf("container status=%d body=%s err=%v", status, body, err)
|
||||
}
|
||||
status, body, err = client.PreZeroContainer(context.Background(), "missing")
|
||||
if err != nil {
|
||||
t.Fatalf("container missing: %v", err)
|
||||
}
|
||||
if status != http.StatusNotFound || !strings.Contains(string(body), "container not found") {
|
||||
t.Fatalf("container missing status=%d body=%s, want forwarded 404", status, body)
|
||||
}
|
||||
|
||||
wantPaths := []string{
|
||||
"/prezero/summary",
|
||||
"/prezero/priority",
|
||||
"/prezero/priority",
|
||||
"/prezero/containers/known-id",
|
||||
"/prezero/containers/missing",
|
||||
}
|
||||
for i, want := range wantPaths {
|
||||
if gotPaths[i] != want {
|
||||
t.Errorf("request %d path=%q, want %q", i, gotPaths[i], want)
|
||||
}
|
||||
}
|
||||
wantQueries := []string{"", "limit=3&offset=10&priority=high", "limit=50&offset=0", "", ""}
|
||||
for i, want := range wantQueries {
|
||||
if gotQueries[i] != want {
|
||||
t.Errorf("request %d query=%q, want %q", i, gotQueries[i], want)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user