Files
galaxy-game/backend/internal/server/handlers_user_games.go
T
Ilia Denisov 2ca47eb4df ui/phase-25: backend turn-cutoff guard + auto-pause + UI sync protocol
Backend now owns the turn-cutoff and pause guards the order tab
relies on: the scheduler flips runtime_status between
generation_in_progress and running around every engine tick, a
failed tick auto-pauses the game through OnRuntimeSnapshot, and a
new game.paused notification kind fans out alongside
game.turn.ready. The user-games handlers reject submits with
HTTP 409 turn_already_closed or game_paused depending on the
runtime state.

UI delegates auto-sync to a new OrderQueue: offline detection,
single retry on reconnect, conflict / paused classification.
OrderDraftStore surfaces conflictBanner / pausedBanner runes,
clears them on local mutation or on a game.turn.ready push via
resetForNewTurn. The order tab renders the matching banners and
the new conflict per-row badge; i18n bundles cover en + ru.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-11 22:00:16 +02:00

306 lines
10 KiB
Go

package server
import (
"context"
"encoding/json"
"errors"
"io"
"net/http"
"strconv"
"galaxy/backend/internal/engineclient"
"galaxy/backend/internal/runtime"
"galaxy/backend/internal/server/handlers"
"galaxy/backend/internal/server/httperr"
"galaxy/backend/internal/server/middleware/userid"
"galaxy/backend/internal/telemetry"
gamerest "galaxy/model/rest"
"github.com/gin-gonic/gin"
"go.uber.org/zap"
)
// UserGamesHandlers groups the engine-proxy handlers under
// `/api/v1/user/games/{game_id}/*`. The wiring connects them through
// `engineclient` against running engine containers.
type UserGamesHandlers struct {
runtime *runtime.Service
engine *engineclient.Client
logger *zap.Logger
}
// NewUserGamesHandlers constructs the handler set. When runtime or
// engine is nil, every handler returns 501 so the contract test still
// passes against a partially-wired router.
func NewUserGamesHandlers(rt *runtime.Service, engine *engineclient.Client, logger *zap.Logger) *UserGamesHandlers {
if logger == nil {
logger = zap.NewNop()
}
return &UserGamesHandlers{runtime: rt, engine: engine, logger: logger.Named("http.user.games")}
}
// Commands handles POST /api/v1/user/games/{game_id}/commands.
func (h *UserGamesHandlers) Commands() gin.HandlerFunc {
if h == nil || h.runtime == nil || h.engine == nil {
return handlers.NotImplemented("userGamesCommands")
}
return func(c *gin.Context) {
gameID, ok := parseGameIDParam(c)
if !ok {
return
}
userID, ok := userid.FromContext(c.Request.Context())
if !ok {
httperr.Abort(c, http.StatusBadRequest, httperr.CodeInvalidRequest, "user id missing")
return
}
body, err := io.ReadAll(c.Request.Body)
if err != nil {
httperr.Abort(c, http.StatusBadRequest, httperr.CodeInvalidRequest, "request body could not be read")
return
}
ctx := c.Request.Context()
if err := h.runtime.CheckOrdersAccept(ctx, gameID); err != nil {
respondGameProxyError(c, h.logger, "user games commands", ctx, err)
return
}
mapping, err := h.runtime.ResolvePlayerMapping(ctx, gameID, userID)
if err != nil {
respondGameProxyError(c, h.logger, "user games commands", ctx, err)
return
}
endpoint, err := h.runtime.EngineEndpoint(ctx, gameID)
if err != nil {
respondGameProxyError(c, h.logger, "user games commands", ctx, err)
return
}
payload, err := rebindActor(body, mapping.RaceName)
if err != nil {
httperr.Abort(c, http.StatusBadRequest, httperr.CodeInvalidRequest, "request body must be a JSON object")
return
}
resp, err := h.engine.ExecuteCommands(ctx, endpoint, payload)
if err != nil {
respondEngineProxyError(c, h.logger, "user games commands", ctx, resp, err)
return
}
c.Data(http.StatusOK, "application/json", resp)
}
}
// Orders handles POST /api/v1/user/games/{game_id}/orders.
func (h *UserGamesHandlers) Orders() gin.HandlerFunc {
if h == nil || h.runtime == nil || h.engine == nil {
return handlers.NotImplemented("userGamesOrders")
}
return func(c *gin.Context) {
gameID, ok := parseGameIDParam(c)
if !ok {
return
}
userID, ok := userid.FromContext(c.Request.Context())
if !ok {
httperr.Abort(c, http.StatusBadRequest, httperr.CodeInvalidRequest, "user id missing")
return
}
body, err := io.ReadAll(c.Request.Body)
if err != nil {
httperr.Abort(c, http.StatusBadRequest, httperr.CodeInvalidRequest, "request body could not be read")
return
}
ctx := c.Request.Context()
if err := h.runtime.CheckOrdersAccept(ctx, gameID); err != nil {
respondGameProxyError(c, h.logger, "user games orders", ctx, err)
return
}
mapping, err := h.runtime.ResolvePlayerMapping(ctx, gameID, userID)
if err != nil {
respondGameProxyError(c, h.logger, "user games orders", ctx, err)
return
}
endpoint, err := h.runtime.EngineEndpoint(ctx, gameID)
if err != nil {
respondGameProxyError(c, h.logger, "user games orders", ctx, err)
return
}
// Engine binds the order body into `gamerest.Command{Actor,
// Commands}` and rejects an empty actor with `notblank`, so
// backend rebinds the actor from the runtime player mapping
// before forwarding — the same rule as for the command
// handler. Per ARCHITECTURE.md §9 backend is the only caller
// of the engine, so the body never carries a client-supplied
// actor.
payload, err := rebindActor(body, mapping.RaceName)
if err != nil {
httperr.Abort(c, http.StatusBadRequest, httperr.CodeInvalidRequest, "request body must be a JSON object")
return
}
resp, err := h.engine.PutOrders(ctx, endpoint, payload)
if err != nil {
respondEngineProxyError(c, h.logger, "user games orders", ctx, resp, err)
return
}
c.Data(http.StatusOK, "application/json", resp)
}
}
// GetOrders handles GET /api/v1/user/games/{game_id}/orders?turn=N.
// Forwards to the engine's `GET /api/v1/order` with the player rebound
// from the runtime mapping. The query parameter `turn` is required
// and must be a non-negative integer; the engine itself enforces the
// same rule, but rejecting up-front saves a network hop.
//
// On `204 No Content` the handler answers `204` so the gateway can
// translate the FBS envelope to `found = false`. On `200` the
// engine's body is forwarded verbatim — the gateway re-encodes the
// JSON `UserGamesOrder` shape into FlatBuffers.
func (h *UserGamesHandlers) GetOrders() gin.HandlerFunc {
if h == nil || h.runtime == nil || h.engine == nil {
return handlers.NotImplemented("userGamesGetOrders")
}
return func(c *gin.Context) {
gameID, ok := parseGameIDParam(c)
if !ok {
return
}
turnRaw := c.Query("turn")
if turnRaw == "" {
httperr.Abort(c, http.StatusBadRequest, httperr.CodeInvalidRequest, "turn is required")
return
}
turn, err := strconv.Atoi(turnRaw)
if err != nil || turn < 0 {
httperr.Abort(c, http.StatusBadRequest, httperr.CodeInvalidRequest, "turn must be a non-negative integer")
return
}
userID, ok := userid.FromContext(c.Request.Context())
if !ok {
httperr.Abort(c, http.StatusBadRequest, httperr.CodeInvalidRequest, "user id missing")
return
}
ctx := c.Request.Context()
mapping, err := h.runtime.ResolvePlayerMapping(ctx, gameID, userID)
if err != nil {
respondGameProxyError(c, h.logger, "user games get orders", ctx, err)
return
}
endpoint, err := h.runtime.EngineEndpoint(ctx, gameID)
if err != nil {
respondGameProxyError(c, h.logger, "user games get orders", ctx, err)
return
}
body, status, err := h.engine.GetOrder(ctx, endpoint, mapping.RaceName, turn)
if err != nil {
respondEngineProxyError(c, h.logger, "user games get orders", ctx, body, err)
return
}
if status == http.StatusNoContent {
c.Status(http.StatusNoContent)
return
}
c.Data(http.StatusOK, "application/json", body)
}
}
// Report handles GET /api/v1/user/games/{game_id}/reports/{turn}.
func (h *UserGamesHandlers) Report() gin.HandlerFunc {
if h == nil || h.runtime == nil || h.engine == nil {
return handlers.NotImplemented("userGamesReport")
}
return func(c *gin.Context) {
gameID, ok := parseGameIDParam(c)
if !ok {
return
}
turnRaw := c.Param("turn")
turn, err := strconv.Atoi(turnRaw)
if err != nil || turn < 0 {
httperr.Abort(c, http.StatusBadRequest, httperr.CodeInvalidRequest, "turn must be a non-negative integer")
return
}
userID, ok := userid.FromContext(c.Request.Context())
if !ok {
httperr.Abort(c, http.StatusBadRequest, httperr.CodeInvalidRequest, "user id missing")
return
}
ctx := c.Request.Context()
mapping, err := h.runtime.ResolvePlayerMapping(ctx, gameID, userID)
if err != nil {
respondGameProxyError(c, h.logger, "user games report", ctx, err)
return
}
endpoint, err := h.runtime.EngineEndpoint(ctx, gameID)
if err != nil {
respondGameProxyError(c, h.logger, "user games report", ctx, err)
return
}
body, err := h.engine.GetReport(ctx, endpoint, mapping.RaceName, turn)
if err != nil {
respondEngineProxyError(c, h.logger, "user games report", ctx, body, err)
return
}
c.Data(http.StatusOK, "application/json", body)
}
}
// rebindActor decodes a JSON object from raw, sets `actor` to
// raceName, and re-encodes. Backend never trusts the actor field
// supplied by the client (per ARCHITECTURE.md §9).
func rebindActor(raw []byte, raceName string) (json.RawMessage, error) {
if len(raw) == 0 {
// Empty body — synthesise a minimal envelope so the engine
// receives a well-formed request.
return json.Marshal(gamerest.Command{Actor: raceName})
}
var generic map[string]json.RawMessage
if err := json.Unmarshal(raw, &generic); err != nil {
return nil, err
}
actor, _ := json.Marshal(raceName)
generic["actor"] = actor
return json.Marshal(generic)
}
func respondGameProxyError(c *gin.Context, logger *zap.Logger, op string, ctx context.Context, err error) {
switch {
case errors.Is(err, runtime.ErrNotFound):
httperr.Abort(c, http.StatusNotFound, httperr.CodeNotFound, "no runtime mapping for this user/game")
case errors.Is(err, runtime.ErrTurnAlreadyClosed):
httperr.Abort(c, http.StatusConflict, httperr.CodeTurnAlreadyClosed,
"turn already closed; orders are not accepted while the engine is producing")
case errors.Is(err, runtime.ErrGamePaused):
httperr.Abort(c, http.StatusConflict, httperr.CodeGamePaused,
"game is paused; orders are not accepted until it resumes")
case errors.Is(err, runtime.ErrConflict):
httperr.Abort(c, http.StatusConflict, httperr.CodeConflict, err.Error())
default:
logger.Error(op+" failed",
append(telemetry.TraceFieldsFromContext(ctx), zap.Error(err))...,
)
httperr.Abort(c, http.StatusInternalServerError, httperr.CodeInternalError, "internal error")
}
}
func respondEngineProxyError(c *gin.Context, logger *zap.Logger, op string, ctx context.Context, body []byte, err error) {
switch {
case errors.Is(err, engineclient.ErrEngineValidation):
if len(body) > 0 {
c.Data(http.StatusBadRequest, "application/json", body)
return
}
httperr.Abort(c, http.StatusBadRequest, httperr.CodeInvalidRequest, err.Error())
case errors.Is(err, engineclient.ErrEngineUnreachable):
httperr.Abort(c, http.StatusServiceUnavailable, httperr.CodeServiceUnavailable, "engine is unreachable")
case errors.Is(err, engineclient.ErrEngineProtocolViolation):
logger.Error(op+" engine protocol violation",
append(telemetry.TraceFieldsFromContext(ctx), zap.Error(err))...,
)
httperr.Abort(c, http.StatusBadGateway, httperr.CodeInternalError, "engine response was malformed")
default:
logger.Error(op+" failed",
append(telemetry.TraceFieldsFromContext(ctx), zap.Error(err))...,
)
httperr.Abort(c, http.StatusInternalServerError, httperr.CodeInternalError, "internal error")
}
}