Files
api-go/internal/api/handlers_train.go
T

116 lines
3.8 KiB
Go

package api
import (
"bytes"
"context"
"encoding/json"
"io"
"log/slog"
"mime"
"net/http"
"pulsecast/api/internal/ml"
"pulsecast/api/internal/model"
)
// maxTrainBody bounds an uploaded CSV. The raw dataset is ~18 MB; 64 MB leaves
// room for a larger export without letting the API accept unbounded bodies.
const maxTrainBody = 64 << 20
// handleTrain proxies POST /api/train to FastAPI. The request is queued there,
// so this handler only validates the JSON form and relays the 202/409 response.
func (s *Server) handleTrain(w http.ResponseWriter, r *http.Request) {
trainer, ok := s.ml.(TrainClient)
if !ok {
writeError(w, http.StatusBadGateway, "ml_unavailable", "FastAPI training client is not configured")
return
}
r.Body = http.MaxBytesReader(w, r.Body, maxTrainBody)
mediaType, _, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
if err != nil {
writeError(w, http.StatusBadRequest, "bad_request", "Content-Type must be application/json or multipart/form-data")
return
}
switch mediaType {
case "application/json":
var req ml.TrainRequest
if err := decodeJSON(r, &req); err != nil {
writeError(w, http.StatusBadRequest, "bad_request", "invalid JSON body")
return
}
if req.Path == "" {
writeError(w, http.StatusBadRequest, "bad_request", "path is required")
return
}
if req.Model == "" {
req.Model = "small"
}
if !model.Contains(ml.TrainModels, req.Model) {
writeError(w, http.StatusBadRequest, "bad_request", "model must be small or forecast")
return
}
raw, err := json.Marshal(req)
if err != nil {
writeError(w, http.StatusInternalServerError, "internal", "failed to encode request")
return
}
s.relayTrain(r.Context(), trainer, w, "application/json", bytes.NewReader(raw))
case "multipart/form-data":
// Forward the stream unchanged: file and model fields belong to FastAPI.
s.relayTrain(r.Context(), trainer, w, r.Header.Get("Content-Type"), r.Body)
default:
writeError(w, http.StatusBadRequest, "bad_request", "Content-Type must be application/json or multipart/form-data")
}
}
// handleTrainStatus proxies GET /api/train/{job_id}.
func (s *Server) handleTrainStatus(w http.ResponseWriter, r *http.Request) {
trainer, ok := s.ml.(TrainClient)
if !ok {
writeError(w, http.StatusBadGateway, "ml_unavailable", "FastAPI training client is not configured")
return
}
jobID := r.PathValue("job_id")
if jobID == "" {
writeError(w, http.StatusNotFound, "not_found", "training job not found")
return
}
status, body, err := trainer.TrainStatus(r.Context(), jobID)
if err != nil {
slog.Warn("train status proxy failed", "job_id", jobID, "error", err)
writeError(w, http.StatusBadGateway, "ml_unavailable", "FastAPI is unavailable")
return
}
relayMLResponse(w, status, body)
}
func (s *Server) relayTrain(ctx context.Context, trainer TrainClient, w http.ResponseWriter, contentType string, body io.Reader) {
status, raw, err := trainer.Train(ctx, contentType, body)
if err != nil {
slog.Warn("train proxy failed", "error", err)
writeError(w, http.StatusBadGateway, "ml_unavailable", "FastAPI is unavailable")
return
}
relayMLResponse(w, status, raw)
}
// relayMLResponse forwards FastAPI's status and JSON body. A non-JSON upstream
// body is converted to the contract error envelope instead of leaking HTML.
func relayMLResponse(w http.ResponseWriter, status int, body []byte) {
if status < 100 || status > 599 {
writeError(w, http.StatusBadGateway, "bad_gateway", "FastAPI returned an invalid status")
return
}
body = bytes.TrimSpace(body)
if len(body) == 0 || !json.Valid(body) {
writeError(w, http.StatusBadGateway, "bad_gateway", "FastAPI returned a non-JSON response")
return
}
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(status)
_, _ = w.Write(body)
}