Files
galaxy-game/gateway/internal/backendclient/games_commands.go
T
Ilia Denisov 601970b028
Tests · Go / test (push) Successful in 2m27s
Tests · UI / test (push) Waiting to run
Tests · Integration / integration (pull_request) Successful in 1m45s
Tests · Go / test (pull_request) Successful in 3m13s
Tests · UI / test (pull_request) Successful in 3m8s
refactor(game): lock-free storage, remove /command, flatten engine wrapper
Three-stage refactor of the game-engine plumbing (game logic untouched):

Stage 1 — lock-free persistence + admin serialisation. Remove the file
lock from repo/fs (the .lock file, the Read/Write-vs-*Safe duality and the
dead ReadSafe polling) and replace the two-step rename with a single atomic
rename so concurrent reads are torn-free without a lock. Serialise the
state-mutating admin writers (init/turn/banish) with one shared router
LimitMiddleware, rewritten to block on the request context instead of a
racy shared 100ms timer.

Stage 2 — remove the obsolete immediate-command path end to end. Players
submit through PUT /api/v1/order; the legacy PUT /api/v1/command path is
deleted across game (route, handler, 24 command factories, Ctrl), backend
(Commands handler/route, engineclient.ExecuteCommands), gateway (dispatch +
executeUserGamesCommand + routing entry), the FlatBuffers/model contract
(UserGamesCommand[Response]) and transcoder, plus every affected
OpenAPI/README/FUNCTIONAL/ARCHITECTURE doc. The integration proxy test is
converted to the order path.

Stage 3 — flatten the REST->engine wrapper. Replace the executor adapter,
the controller package functions and RepoController with one concrete
controller.Service; drop the single-implementation Repo and Storage
interfaces (repo.Repo / fs.FS are now concrete). Handlers depend on a thin
handler.Engine seam and own the domain->REST projection; storage is
resolved once at startup instead of per request.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-05-30 13:37:07 +02:00

278 lines
12 KiB
Go

package backendclient
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"net/url"
"strings"
"galaxy/gateway/internal/downstream"
ordermodel "galaxy/model/order"
reportmodel "galaxy/model/report"
gamerest "galaxy/model/rest"
"galaxy/transcoder"
"github.com/google/uuid"
)
// ExecuteGameCommand routes one authenticated `user.games.*` command
// into backend's `/api/v1/user/games/{game_id}/*` endpoints. Order
// requests transcode the typed FB-payload into the JSON shape the
// engine expects (a `gamerest.Command` with empty actor — backend
// rebinds the actor from the runtime player mapping). Report requests
// transcode the response Report from JSON back to FB.
func (c *RESTClient) ExecuteGameCommand(ctx context.Context, command downstream.AuthenticatedCommand) (downstream.UnaryResult, error) {
if c == nil || c.httpClient == nil {
return downstream.UnaryResult{}, errors.New("backendclient: execute game command: nil client")
}
if ctx == nil {
return downstream.UnaryResult{}, errors.New("backendclient: execute game command: nil context")
}
if err := ctx.Err(); err != nil {
return downstream.UnaryResult{}, err
}
if strings.TrimSpace(command.UserID) == "" {
return downstream.UnaryResult{}, errors.New("backendclient: execute game command: user_id must not be empty")
}
switch command.MessageType {
case ordermodel.MessageTypeUserGamesOrder:
req, err := transcoder.PayloadToUserGamesOrder(command.PayloadBytes)
if err != nil {
return downstream.UnaryResult{}, fmt.Errorf("backendclient: execute game command %q: %w", command.MessageType, err)
}
return c.executeUserGamesOrder(ctx, command.UserID, req)
case ordermodel.MessageTypeUserGamesOrderGet:
req, err := transcoder.PayloadToUserGamesOrderGet(command.PayloadBytes)
if err != nil {
return downstream.UnaryResult{}, fmt.Errorf("backendclient: execute game command %q: %w", command.MessageType, err)
}
return c.executeUserGamesOrderGet(ctx, command.UserID, req)
case reportmodel.MessageTypeUserGamesReport:
req, err := transcoder.PayloadToGameReportRequest(command.PayloadBytes)
if err != nil {
return downstream.UnaryResult{}, fmt.Errorf("backendclient: execute game command %q: %w", command.MessageType, err)
}
return c.executeUserGamesReport(ctx, command.UserID, req)
case reportmodel.MessageTypeUserGamesBattle:
req, err := transcoder.PayloadToGameBattleRequest(command.PayloadBytes)
if err != nil {
return downstream.UnaryResult{}, fmt.Errorf("backendclient: execute game command %q: %w", command.MessageType, err)
}
return c.executeUserGamesBattle(ctx, command.UserID, req)
default:
return downstream.UnaryResult{}, fmt.Errorf("backendclient: execute game command: unsupported message type %q", command.MessageType)
}
}
func (c *RESTClient) executeUserGamesOrder(ctx context.Context, userID string, req *ordermodel.UserGamesOrder) (downstream.UnaryResult, error) {
if req.GameID == uuid.Nil {
return downstream.UnaryResult{}, errors.New("execute user.games.order: game_id must not be empty")
}
body, err := buildEngineCommandBody(req.Commands)
if err != nil {
return downstream.UnaryResult{}, fmt.Errorf("execute user.games.order: %w", err)
}
target := c.baseURL + "/api/v1/user/games/" + url.PathEscape(req.GameID.String()) + "/orders"
respBody, status, err := c.do(ctx, http.MethodPost, target, userID, body)
if err != nil {
return downstream.UnaryResult{}, fmt.Errorf("execute user.games.order: %w", err)
}
return projectUserGamesOrderResponse(status, respBody)
}
func (c *RESTClient) executeUserGamesOrderGet(ctx context.Context, userID string, req *ordermodel.UserGamesOrderGet) (downstream.UnaryResult, error) {
if req.GameID == uuid.Nil {
return downstream.UnaryResult{}, errors.New("execute user.games.order.get: game_id must not be empty")
}
if req.Turn < 0 {
return downstream.UnaryResult{}, fmt.Errorf("execute user.games.order.get: turn must be non-negative, got %d", req.Turn)
}
target := fmt.Sprintf("%s/api/v1/user/games/%s/orders?turn=%d", c.baseURL, url.PathEscape(req.GameID.String()), req.Turn)
respBody, status, err := c.do(ctx, http.MethodGet, target, userID, nil)
if err != nil {
return downstream.UnaryResult{}, fmt.Errorf("execute user.games.order.get: %w", err)
}
return projectUserGamesOrderGetResponse(status, respBody)
}
func (c *RESTClient) executeUserGamesReport(ctx context.Context, userID string, req *reportmodel.GameReportRequest) (downstream.UnaryResult, error) {
if req.GameID == uuid.Nil {
return downstream.UnaryResult{}, errors.New("execute user.games.report: game_id must not be empty")
}
target := fmt.Sprintf("%s/api/v1/user/games/%s/reports/%d", c.baseURL, url.PathEscape(req.GameID.String()), req.Turn)
respBody, status, err := c.do(ctx, http.MethodGet, target, userID, nil)
if err != nil {
return downstream.UnaryResult{}, fmt.Errorf("execute user.games.report: %w", err)
}
return projectUserGamesReportResponse(status, respBody)
}
func (c *RESTClient) executeUserGamesBattle(ctx context.Context, userID string, req *reportmodel.GameBattleRequest) (downstream.UnaryResult, error) {
if req.GameID == uuid.Nil {
return downstream.UnaryResult{}, errors.New("execute user.games.battle: game_id must not be empty")
}
if req.BattleID == uuid.Nil {
return downstream.UnaryResult{}, errors.New("execute user.games.battle: battle_id must not be empty")
}
target := fmt.Sprintf("%s/api/v1/user/games/%s/battles/%d/%s",
c.baseURL,
url.PathEscape(req.GameID.String()),
req.Turn,
url.PathEscape(req.BattleID.String()),
)
respBody, status, err := c.do(ctx, http.MethodGet, target, userID, nil)
if err != nil {
return downstream.UnaryResult{}, fmt.Errorf("execute user.games.battle: %w", err)
}
return projectUserGamesBattleResponse(status, respBody)
}
// buildEngineCommandBody serialises a slice of typed commands into the
// JSON shape expected by backend's command/order handlers (a
// `gamerest.Command` with the actor field left empty — backend rebinds
// it from the runtime player mapping before forwarding to the engine).
func buildEngineCommandBody(commands []ordermodel.DecodableCommand) (gamerest.Command, error) {
raw := make([]json.RawMessage, len(commands))
for i, cmd := range commands {
encoded, err := json.Marshal(cmd)
if err != nil {
return gamerest.Command{}, fmt.Errorf("encode command %d: %w", i, err)
}
raw[i] = encoded
}
return gamerest.Command{Actor: "", Commands: raw}, nil
}
// projectUserGamesOrderResponse decodes the engine's `PUT /api/v1/order`
// JSON body (forwarded by backend) and re-encodes it as a FlatBuffers
// `UserGamesOrderResponse` envelope. The body carries per-command
// `cmdApplied` / `cmdErrorCode` plus the engine-assigned `updatedAt`,
// all of which round-trip into FB unchanged. An empty body falls back
// to a typed empty envelope so the gateway can ack a successful but
// unstructured 2xx without surfacing an error.
func projectUserGamesOrderResponse(statusCode int, payload []byte) (downstream.UnaryResult, error) {
switch {
case statusCode >= 200 && statusCode < 300:
var parsed *ordermodel.UserGamesOrder
if len(payload) > 0 {
decoded, jsonErr := transcoder.JSONToUserGamesOrder(payload)
if jsonErr != nil {
return downstream.UnaryResult{}, fmt.Errorf("decode engine order response: %w", jsonErr)
}
parsed = decoded
}
encoded, err := transcoder.UserGamesOrderResponseToPayload(parsed)
if err != nil {
return downstream.UnaryResult{}, fmt.Errorf("encode order response payload: %w", err)
}
return downstream.UnaryResult{
ResultCode: userCommandResultCodeOK,
PayloadBytes: encoded,
}, nil
case statusCode == http.StatusServiceUnavailable:
return downstream.UnaryResult{}, downstream.ErrDownstreamUnavailable
case statusCode >= 400 && statusCode <= 599:
return projectUserBackendError(statusCode, payload)
default:
return downstream.UnaryResult{}, fmt.Errorf("unexpected HTTP status %d", statusCode)
}
}
// projectUserGamesOrderGetResponse decodes the engine's
// `GET /api/v1/order` JSON body and re-encodes it as a FlatBuffers
// `UserGamesOrderGetResponse` envelope. A `204 No Content` from the
// engine surfaces as `found = false` with no embedded order; `200`
// surfaces as `found = true` with the decoded order.
func projectUserGamesOrderGetResponse(statusCode int, payload []byte) (downstream.UnaryResult, error) {
switch {
case statusCode == http.StatusNoContent:
encoded, err := transcoder.UserGamesOrderGetResponseToPayload(nil, false)
if err != nil {
return downstream.UnaryResult{}, fmt.Errorf("encode order get response payload: %w", err)
}
return downstream.UnaryResult{
ResultCode: userCommandResultCodeOK,
PayloadBytes: encoded,
}, nil
case statusCode >= 200 && statusCode < 300:
decoded, err := transcoder.JSONToUserGamesOrder(payload)
if err != nil {
return downstream.UnaryResult{}, fmt.Errorf("decode engine order get response: %w", err)
}
encoded, err := transcoder.UserGamesOrderGetResponseToPayload(decoded, true)
if err != nil {
return downstream.UnaryResult{}, fmt.Errorf("encode order get response payload: %w", err)
}
return downstream.UnaryResult{
ResultCode: userCommandResultCodeOK,
PayloadBytes: encoded,
}, nil
case statusCode == http.StatusServiceUnavailable:
return downstream.UnaryResult{}, downstream.ErrDownstreamUnavailable
case statusCode >= 400 && statusCode <= 599:
return projectUserBackendError(statusCode, payload)
default:
return downstream.UnaryResult{}, fmt.Errorf("unexpected HTTP status %d", statusCode)
}
}
// projectUserGamesReportResponse decodes the engine's Report JSON
// payload (forwarded verbatim by backend) and re-encodes it as a
// FlatBuffers Report for the signed-gRPC client.
func projectUserGamesReportResponse(statusCode int, payload []byte) (downstream.UnaryResult, error) {
switch {
case statusCode == http.StatusOK:
var report reportmodel.Report
if err := json.Unmarshal(payload, &report); err != nil {
return downstream.UnaryResult{}, fmt.Errorf("decode engine report: %w", err)
}
encoded, err := transcoder.ReportToPayload(&report)
if err != nil {
return downstream.UnaryResult{}, fmt.Errorf("encode report payload: %w", err)
}
return downstream.UnaryResult{
ResultCode: userCommandResultCodeOK,
PayloadBytes: encoded,
}, nil
case statusCode == http.StatusServiceUnavailable:
return downstream.UnaryResult{}, downstream.ErrDownstreamUnavailable
case statusCode >= 400 && statusCode <= 599:
return projectUserBackendError(statusCode, payload)
default:
return downstream.UnaryResult{}, fmt.Errorf("unexpected HTTP status %d", statusCode)
}
}
// projectUserGamesBattleResponse decodes the engine's BattleReport JSON
// payload (forwarded by backend's user.games.battle proxy) and
// re-encodes it as a FlatBuffers BattleReport for the signed-gRPC
// client. 404 from backend surfaces as the canonical `not_found`
// gateway error so the UI can render its "battle not found" state.
func projectUserGamesBattleResponse(statusCode int, payload []byte) (downstream.UnaryResult, error) {
switch {
case statusCode == http.StatusOK:
var report reportmodel.BattleReport
if err := json.Unmarshal(payload, &report); err != nil {
return downstream.UnaryResult{}, fmt.Errorf("decode engine battle report: %w", err)
}
encoded, err := transcoder.BattleReportToPayload(&report)
if err != nil {
return downstream.UnaryResult{}, fmt.Errorf("encode battle report payload: %w", err)
}
return downstream.UnaryResult{
ResultCode: userCommandResultCodeOK,
PayloadBytes: encoded,
}, nil
case statusCode == http.StatusServiceUnavailable:
return downstream.UnaryResult{}, downstream.ErrDownstreamUnavailable
case statusCode >= 400 && statusCode <= 599:
return projectUserBackendError(statusCode, payload)
default:
return downstream.UnaryResult{}, fmt.Errorf("unexpected HTTP status %d", statusCode)
}
}