ebd156ece2
Tests · UI / test (push) Has been cancelled
Tests · Go / test (pull_request) Successful in 2m6s
Tests · Go / test (push) Successful in 2m7s
Tests · Integration / integration (pull_request) Successful in 1m47s
Tests · UI / test (pull_request) Failing after 3m42s
The Phase 27 BattleViewer was the last UI surface still issuing raw
fetch() against the backend REST contract (`/api/v1/user/games/...
/battles/...`). The dev-deploy gateway never proxied that path, so
the viewer worked only in tools/local-dev/. Move it onto the signed
ConnectRPC channel every other authenticated surface already uses.
Wire pieces:
- FBS GameBattleRequest in pkg/schema/fbs/battle.fbs, regenerated
Go + TS bindings.
- MessageTypeUserGamesBattle constant + GameBattleRequest struct in
pkg/model/report/messages.go.
- pkg/transcoder/battle.go gains GameBattleRequestToPayload and
PayloadToGameBattleRequest helpers.
- gateway games_commands.go switches on the new message type and
GETs /api/v1/user/games/{id}/battles/{turn}/{battle_id}; the JSON
response is re-encoded as a FlatBuffers BattleReport before being
returned. 404 from backend surfaces as the canonical `not_found`
gateway error.
- ui/frontend/src/api/battle-fetch.ts now builds the FBS request,
calls GalaxyClient.executeCommand, and decodes the FBS response
into the existing UI shape (Record<string,string> race/ship maps,
string-form UUID). BattleFetchError carries an HTTP-style status
derived from the result code so the active-view's not_found branch
keeps working.
- battle.svelte pulls the GalaxyClient from the in-game shell
context. While the layout's boot Promise.all is in flight the
effect stays in `loading` until the client handle becomes
non-null.
- ui/Makefile FBS_INPUTS gains battle.fbs.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
320 lines
14 KiB
Go
320 lines
14 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. Command
|
|
// and 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.MessageTypeUserGamesCommand:
|
|
req, err := transcoder.PayloadToUserGamesCommand(command.PayloadBytes)
|
|
if err != nil {
|
|
return downstream.UnaryResult{}, fmt.Errorf("backendclient: execute game command %q: %w", command.MessageType, err)
|
|
}
|
|
return c.executeUserGamesCommand(ctx, command.UserID, req)
|
|
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) executeUserGamesCommand(ctx context.Context, userID string, req *ordermodel.UserGamesCommand) (downstream.UnaryResult, error) {
|
|
if req.GameID == uuid.Nil {
|
|
return downstream.UnaryResult{}, errors.New("execute user.games.command: game_id must not be empty")
|
|
}
|
|
body, err := buildEngineCommandBody(req.Commands)
|
|
if err != nil {
|
|
return downstream.UnaryResult{}, fmt.Errorf("execute user.games.command: %w", err)
|
|
}
|
|
target := c.baseURL + "/api/v1/user/games/" + url.PathEscape(req.GameID.String()) + "/commands"
|
|
respBody, status, err := c.do(ctx, http.MethodPost, target, userID, body)
|
|
if err != nil {
|
|
return downstream.UnaryResult{}, fmt.Errorf("execute user.games.command: %w", err)
|
|
}
|
|
return projectUserGamesAckResponse(status, respBody, transcoder.EmptyUserGamesCommandResponsePayload)
|
|
}
|
|
|
|
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
|
|
}
|
|
|
|
// projectUserGamesAckResponse turns a backend response for the
|
|
// `user.games.command` route into a UnaryResult. Engine returns 204
|
|
// on success, so any 2xx status is treated as ok and answered with
|
|
// the empty typed FB envelope produced by ackBuilder.
|
|
func projectUserGamesAckResponse(statusCode int, payload []byte, ackBuilder func() []byte) (downstream.UnaryResult, error) {
|
|
switch {
|
|
case statusCode >= 200 && statusCode < 300:
|
|
return downstream.UnaryResult{
|
|
ResultCode: userCommandResultCodeOK,
|
|
PayloadBytes: ackBuilder(),
|
|
}, 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)
|
|
}
|
|
}
|
|
|
|
// 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)
|
|
}
|
|
}
|