feat: gamemaster
This commit is contained in:
@@ -0,0 +1,49 @@
|
||||
package orderput
|
||||
|
||||
// Stable error codes returned in `Result.ErrorCode`. The values match the
|
||||
// vocabulary frozen by `gamemaster/README.md §Error Model` and
|
||||
// `gamemaster/api/internal-openapi.yaml`. Stage 19's REST handler imports
|
||||
// these names rather than redeclare them; renaming any of them is a
|
||||
// contract change.
|
||||
const (
|
||||
// ErrorCodeInvalidRequest reports that the request envelope failed
|
||||
// structural validation (empty required field, malformed payload,
|
||||
// non-object payload, payload missing the `commands` array).
|
||||
ErrorCodeInvalidRequest = "invalid_request"
|
||||
|
||||
// ErrorCodeRuntimeNotFound reports that no `runtime_records` row
|
||||
// exists for the requested game id.
|
||||
ErrorCodeRuntimeNotFound = "runtime_not_found"
|
||||
|
||||
// ErrorCodeRuntimeNotRunning reports that the runtime exists but its
|
||||
// current status is not `running`. Hot-path orders are rejected
|
||||
// outside the running state to avoid racing with admin transitions
|
||||
// and turn generation.
|
||||
ErrorCodeRuntimeNotRunning = "runtime_not_running"
|
||||
|
||||
// ErrorCodeForbidden reports that the caller is not an active member
|
||||
// of the game, or that the (game_id, user_id) pair lacks a player
|
||||
// mapping.
|
||||
ErrorCodeForbidden = "forbidden"
|
||||
|
||||
// ErrorCodeEngineUnreachable reports that the engine /api/v1/order
|
||||
// call returned a 5xx status, timed out, or could not be dispatched.
|
||||
ErrorCodeEngineUnreachable = "engine_unreachable"
|
||||
|
||||
// ErrorCodeEngineValidationError reports that the engine returned
|
||||
// 4xx with a per-command result. The body is forwarded verbatim
|
||||
// through `Result.RawResponse`.
|
||||
ErrorCodeEngineValidationError = "engine_validation_error"
|
||||
|
||||
// ErrorCodeEngineProtocolViolation reports that the engine response
|
||||
// did not match the expected schema. Stage 19 maps this to 502.
|
||||
ErrorCodeEngineProtocolViolation = "engine_protocol_violation"
|
||||
|
||||
// ErrorCodeServiceUnavailable reports that a steady-state dependency
|
||||
// (PostgreSQL, Lobby) was unreachable for this call.
|
||||
ErrorCodeServiceUnavailable = "service_unavailable"
|
||||
|
||||
// ErrorCodeInternal reports an unexpected error not classified by
|
||||
// the other codes.
|
||||
ErrorCodeInternal = "internal_error"
|
||||
)
|
||||
@@ -0,0 +1,361 @@
|
||||
// Package orderput implements the player-order hot-path service owned by
|
||||
// Game Master. It accepts a verified `(game_id, user_id, payload)`
|
||||
// envelope from Edge Gateway, authorises the caller against the membership
|
||||
// cache, resolves `actor=race_name` from `player_mappings`, reshapes the
|
||||
// payload to the engine `CommandRequest{actor, cmd}` schema, and forwards
|
||||
// the call to the engine `/api/v1/order` endpoint.
|
||||
//
|
||||
// Lifecycle and error semantics follow `gamemaster/README.md §Hot Path →
|
||||
// Player commands and orders`. Design rationale is captured in
|
||||
// `gamemaster/docs/stage16-membership-cache-and-invalidation.md`.
|
||||
package orderput
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"galaxy/gamemaster/internal/domain/operation"
|
||||
"galaxy/gamemaster/internal/domain/playermapping"
|
||||
"galaxy/gamemaster/internal/domain/runtime"
|
||||
"galaxy/gamemaster/internal/logging"
|
||||
"galaxy/gamemaster/internal/ports"
|
||||
"galaxy/gamemaster/internal/service/membership"
|
||||
"galaxy/gamemaster/internal/telemetry"
|
||||
)
|
||||
|
||||
const (
|
||||
engineCallOp = "order"
|
||||
|
||||
membershipStatusActive = "active"
|
||||
|
||||
payloadCommandsKey = "commands"
|
||||
payloadCmdKey = "cmd"
|
||||
payloadActorKey = "actor"
|
||||
)
|
||||
|
||||
// Input stores the per-call arguments for one order-put operation. The
|
||||
// shape mirrors `PutOrdersRequest` from
|
||||
// `gamemaster/api/internal-openapi.yaml` plus the verified user identity
|
||||
// captured from the `X-User-ID` header by the Stage 19 handler.
|
||||
type Input struct {
|
||||
// GameID identifies the platform game the order targets.
|
||||
GameID string
|
||||
|
||||
// UserID identifies the platform user submitting the order. The
|
||||
// service derives `actor=race_name` from this value via
|
||||
// `player_mappings`.
|
||||
UserID string
|
||||
|
||||
// Payload stores the raw `PutOrdersRequest` body. The service
|
||||
// rewrites it to the engine `CommandRequest{actor, cmd}` shape
|
||||
// before forwarding.
|
||||
Payload json.RawMessage
|
||||
}
|
||||
|
||||
// Validate reports whether input carries the structural invariants the
|
||||
// service requires before any store is touched.
|
||||
func (input Input) Validate() error {
|
||||
if strings.TrimSpace(input.GameID) == "" {
|
||||
return fmt.Errorf("game id must not be empty")
|
||||
}
|
||||
if strings.TrimSpace(input.UserID) == "" {
|
||||
return fmt.Errorf("user id must not be empty")
|
||||
}
|
||||
if len(input.Payload) == 0 {
|
||||
return fmt.Errorf("payload must not be empty")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Result stores the deterministic outcome of one Handle call.
|
||||
type Result struct {
|
||||
// Outcome reports whether the operation completed (success) or
|
||||
// produced a stable failure code.
|
||||
Outcome operation.Outcome
|
||||
|
||||
// ErrorCode stores the stable error code on failure. Empty on
|
||||
// success.
|
||||
ErrorCode string
|
||||
|
||||
// ErrorMessage stores the operator-readable detail on failure.
|
||||
// Empty on success.
|
||||
ErrorMessage string
|
||||
|
||||
// RawResponse stores the engine response body. Populated on success
|
||||
// and on `engine_validation_error`. Empty on every other terminal
|
||||
// branch.
|
||||
RawResponse json.RawMessage
|
||||
}
|
||||
|
||||
// IsSuccess reports whether the result represents a successful operation.
|
||||
func (result Result) IsSuccess() bool {
|
||||
return result.Outcome == operation.OutcomeSuccess
|
||||
}
|
||||
|
||||
// Dependencies groups the collaborators required by Service.
|
||||
type Dependencies struct {
|
||||
// RuntimeRecords loads the engine endpoint and the runtime status.
|
||||
RuntimeRecords ports.RuntimeRecordStore
|
||||
|
||||
// PlayerMappings resolves `(game_id, user_id) → race_name`.
|
||||
PlayerMappings ports.PlayerMappingStore
|
||||
|
||||
// Membership authorises the caller. Hot-path services share one
|
||||
// cache instance with `commandexecute` and `reportget`.
|
||||
Membership *membership.Cache
|
||||
|
||||
// Engine forwards the reshaped payload to `/api/v1/order`.
|
||||
Engine ports.EngineClient
|
||||
|
||||
// Telemetry records the per-outcome counter and the engine-call
|
||||
// latency histogram.
|
||||
Telemetry *telemetry.Runtime
|
||||
|
||||
// Logger records structured service-level events. Defaults to
|
||||
// `slog.Default()` when nil.
|
||||
Logger *slog.Logger
|
||||
|
||||
// Clock supplies the wall-clock used for engine-call latency.
|
||||
// Defaults to `time.Now` when nil.
|
||||
Clock func() time.Time
|
||||
}
|
||||
|
||||
// Service executes the order-put hot-path operation.
|
||||
type Service struct {
|
||||
runtimeRecords ports.RuntimeRecordStore
|
||||
playerMappings ports.PlayerMappingStore
|
||||
membership *membership.Cache
|
||||
engine ports.EngineClient
|
||||
telemetry *telemetry.Runtime
|
||||
logger *slog.Logger
|
||||
clock func() time.Time
|
||||
}
|
||||
|
||||
// NewService constructs one Service from deps.
|
||||
func NewService(deps Dependencies) (*Service, error) {
|
||||
switch {
|
||||
case deps.RuntimeRecords == nil:
|
||||
return nil, errors.New("new order put service: nil runtime records")
|
||||
case deps.PlayerMappings == nil:
|
||||
return nil, errors.New("new order put service: nil player mappings")
|
||||
case deps.Membership == nil:
|
||||
return nil, errors.New("new order put service: nil membership cache")
|
||||
case deps.Engine == nil:
|
||||
return nil, errors.New("new order put service: nil engine client")
|
||||
case deps.Telemetry == nil:
|
||||
return nil, errors.New("new order put service: nil telemetry runtime")
|
||||
}
|
||||
|
||||
clock := deps.Clock
|
||||
if clock == nil {
|
||||
clock = time.Now
|
||||
}
|
||||
logger := deps.Logger
|
||||
if logger == nil {
|
||||
logger = slog.Default()
|
||||
}
|
||||
logger = logger.With("service", "gamemaster.orderput")
|
||||
|
||||
return &Service{
|
||||
runtimeRecords: deps.RuntimeRecords,
|
||||
playerMappings: deps.PlayerMappings,
|
||||
membership: deps.Membership,
|
||||
engine: deps.Engine,
|
||||
telemetry: deps.Telemetry,
|
||||
logger: logger,
|
||||
clock: clock,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Handle executes one order-put operation end-to-end. The Go-level error
|
||||
// return is reserved for non-business failures (nil context, nil
|
||||
// receiver). Every business outcome flows through Result.
|
||||
func (service *Service) Handle(ctx context.Context, input Input) (Result, error) {
|
||||
if service == nil {
|
||||
return Result{}, errors.New("order put: nil service")
|
||||
}
|
||||
if ctx == nil {
|
||||
return Result{}, errors.New("order put: nil context")
|
||||
}
|
||||
|
||||
if err := input.Validate(); err != nil {
|
||||
return service.recordFailure(ctx, input, ErrorCodeInvalidRequest, err.Error(), nil), nil
|
||||
}
|
||||
|
||||
record, result, ok := service.loadRecord(ctx, input)
|
||||
if !ok {
|
||||
return result, nil
|
||||
}
|
||||
if record.Status != runtime.StatusRunning {
|
||||
message := fmt.Sprintf("runtime status is %q, expected %q", record.Status, runtime.StatusRunning)
|
||||
return service.recordFailure(ctx, input, ErrorCodeRuntimeNotRunning, message, nil), nil
|
||||
}
|
||||
|
||||
mapping, result, ok := service.authorise(ctx, input)
|
||||
if !ok {
|
||||
return result, nil
|
||||
}
|
||||
|
||||
payload, err := rewriteOrderPayload(input.Payload, mapping.RaceName)
|
||||
if err != nil {
|
||||
return service.recordFailure(ctx, input, ErrorCodeInvalidRequest, err.Error(), nil), nil
|
||||
}
|
||||
|
||||
body, engineErr := service.callEngine(ctx, record.EngineEndpoint, payload)
|
||||
if engineErr != nil {
|
||||
errorCode := classifyEngineError(engineErr)
|
||||
message := fmt.Sprintf("engine order: %s", engineErr.Error())
|
||||
var bodyForCaller json.RawMessage
|
||||
if errorCode == ErrorCodeEngineValidationError {
|
||||
bodyForCaller = body
|
||||
}
|
||||
return service.recordFailure(ctx, input, errorCode, message, bodyForCaller), nil
|
||||
}
|
||||
|
||||
service.telemetry.RecordOrderPutOutcome(ctx,
|
||||
string(operation.OutcomeSuccess), "")
|
||||
logArgs := []any{
|
||||
"game_id", input.GameID,
|
||||
"user_id", input.UserID,
|
||||
"actor", mapping.RaceName,
|
||||
}
|
||||
logArgs = append(logArgs, logging.ContextAttrs(ctx)...)
|
||||
service.logger.InfoContext(ctx, "order put succeeded", logArgs...)
|
||||
|
||||
return Result{
|
||||
Outcome: operation.OutcomeSuccess,
|
||||
RawResponse: body,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// loadRecord reads the runtime record and maps store errors to
|
||||
// orchestrator outcomes. ok=false means the flow stops with the returned
|
||||
// Result.
|
||||
func (service *Service) loadRecord(ctx context.Context, input Input) (runtime.RuntimeRecord, Result, bool) {
|
||||
record, err := service.runtimeRecords.Get(ctx, input.GameID)
|
||||
switch {
|
||||
case err == nil:
|
||||
return record, Result{}, true
|
||||
case errors.Is(err, runtime.ErrNotFound):
|
||||
return runtime.RuntimeRecord{}, service.recordFailure(ctx, input,
|
||||
ErrorCodeRuntimeNotFound, "runtime record does not exist", nil), false
|
||||
default:
|
||||
return runtime.RuntimeRecord{}, service.recordFailure(ctx, input,
|
||||
ErrorCodeServiceUnavailable, fmt.Sprintf("get runtime record: %s", err.Error()), nil), false
|
||||
}
|
||||
}
|
||||
|
||||
// authorise resolves the membership status and the player mapping for
|
||||
// the caller. ok=false means the flow stops with the returned Result.
|
||||
func (service *Service) authorise(ctx context.Context, input Input) (playermapping.PlayerMapping, Result, bool) {
|
||||
status, err := service.membership.Resolve(ctx, input.GameID, input.UserID)
|
||||
if err != nil {
|
||||
return playermapping.PlayerMapping{}, service.recordFailure(ctx, input,
|
||||
ErrorCodeServiceUnavailable, fmt.Sprintf("resolve membership: %s", err.Error()), nil), false
|
||||
}
|
||||
if status != membershipStatusActive {
|
||||
message := fmt.Sprintf("membership status %q does not authorise orders", status)
|
||||
if status == "" {
|
||||
message = "user is not a member of the game"
|
||||
}
|
||||
return playermapping.PlayerMapping{}, service.recordFailure(ctx, input,
|
||||
ErrorCodeForbidden, message, nil), false
|
||||
}
|
||||
|
||||
mapping, err := service.playerMappings.Get(ctx, input.GameID, input.UserID)
|
||||
switch {
|
||||
case err == nil:
|
||||
return mapping, Result{}, true
|
||||
case errors.Is(err, playermapping.ErrNotFound):
|
||||
return playermapping.PlayerMapping{}, service.recordFailure(ctx, input,
|
||||
ErrorCodeForbidden, "player mapping not installed for active member", nil), false
|
||||
default:
|
||||
return playermapping.PlayerMapping{}, service.recordFailure(ctx, input,
|
||||
ErrorCodeServiceUnavailable, fmt.Sprintf("get player mapping: %s", err.Error()), nil), false
|
||||
}
|
||||
}
|
||||
|
||||
// callEngine forwards the reshaped payload to the engine and records the
|
||||
// wall-clock latency under the `order` op label.
|
||||
func (service *Service) callEngine(ctx context.Context, baseURL string, payload json.RawMessage) (json.RawMessage, error) {
|
||||
start := service.clock()
|
||||
body, err := service.engine.PutOrders(ctx, baseURL, payload)
|
||||
service.telemetry.RecordEngineCall(ctx, engineCallOp, service.clock().Sub(start))
|
||||
return body, err
|
||||
}
|
||||
|
||||
// classifyEngineError maps the engine port sentinels to the order-put
|
||||
// stable error codes.
|
||||
func classifyEngineError(err error) string {
|
||||
switch {
|
||||
case errors.Is(err, ports.ErrEngineValidation):
|
||||
return ErrorCodeEngineValidationError
|
||||
case errors.Is(err, ports.ErrEngineProtocolViolation):
|
||||
return ErrorCodeEngineProtocolViolation
|
||||
case errors.Is(err, ports.ErrEngineUnreachable):
|
||||
return ErrorCodeEngineUnreachable
|
||||
default:
|
||||
return ErrorCodeEngineUnreachable
|
||||
}
|
||||
}
|
||||
|
||||
// recordFailure emits the service-level outcome counter and a structured
|
||||
// log entry, then returns the Result the caller surfaces.
|
||||
func (service *Service) recordFailure(ctx context.Context, input Input, errorCode, errorMessage string, rawResponse json.RawMessage) Result {
|
||||
service.telemetry.RecordOrderPutOutcome(ctx,
|
||||
string(operation.OutcomeFailure), errorCode)
|
||||
logArgs := []any{
|
||||
"game_id", input.GameID,
|
||||
"user_id", input.UserID,
|
||||
"error_code", errorCode,
|
||||
"error_message", errorMessage,
|
||||
}
|
||||
logArgs = append(logArgs, logging.ContextAttrs(ctx)...)
|
||||
service.logger.WarnContext(ctx, "order put rejected", logArgs...)
|
||||
return Result{
|
||||
Outcome: operation.OutcomeFailure,
|
||||
ErrorCode: errorCode,
|
||||
ErrorMessage: errorMessage,
|
||||
RawResponse: rawResponse,
|
||||
}
|
||||
}
|
||||
|
||||
// rewriteOrderPayload reshapes the GM `PutOrdersRequest` body
|
||||
// (`{commands:[…]}`) to the engine `CommandRequest` body
|
||||
// (`{actor:<raceName>, cmd:[…]}`). Every other top-level key is
|
||||
// discarded; GM never trusts caller-supplied envelope fields per the
|
||||
// README §Hot Path rule. Returns an error when the payload is not a JSON
|
||||
// object or the `commands` field is missing or not an array.
|
||||
func rewriteOrderPayload(payload json.RawMessage, raceName string) (json.RawMessage, error) {
|
||||
var fields map[string]json.RawMessage
|
||||
if err := json.Unmarshal(payload, &fields); err != nil {
|
||||
return nil, fmt.Errorf("payload must decode as a JSON object: %w", err)
|
||||
}
|
||||
commands, ok := fields[payloadCommandsKey]
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("payload missing required %q field", payloadCommandsKey)
|
||||
}
|
||||
var commandList []json.RawMessage
|
||||
if err := json.Unmarshal(commands, &commandList); err != nil {
|
||||
return nil, fmt.Errorf("payload %q field must decode as an array: %w", payloadCommandsKey, err)
|
||||
}
|
||||
actor, err := json.Marshal(raceName)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("marshal actor: %w", err)
|
||||
}
|
||||
out := map[string]json.RawMessage{
|
||||
payloadActorKey: actor,
|
||||
payloadCmdKey: commands,
|
||||
}
|
||||
encoded, err := json.Marshal(out)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("marshal engine payload: %w", err)
|
||||
}
|
||||
_ = commandList // ensure the array shape is validated before forwarding
|
||||
return encoded, nil
|
||||
}
|
||||
@@ -0,0 +1,600 @@
|
||||
package orderput_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"galaxy/gamemaster/internal/domain/operation"
|
||||
"galaxy/gamemaster/internal/domain/playermapping"
|
||||
"galaxy/gamemaster/internal/domain/runtime"
|
||||
"galaxy/gamemaster/internal/ports"
|
||||
"galaxy/gamemaster/internal/service/membership"
|
||||
"galaxy/gamemaster/internal/service/orderput"
|
||||
"galaxy/gamemaster/internal/telemetry"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// --- fakes ------------------------------------------------------------
|
||||
|
||||
type fakeRuntimeRecords struct {
|
||||
mu sync.Mutex
|
||||
stored map[string]runtime.RuntimeRecord
|
||||
getErr error
|
||||
}
|
||||
|
||||
func newFakeRuntimeRecords() *fakeRuntimeRecords {
|
||||
return &fakeRuntimeRecords{stored: map[string]runtime.RuntimeRecord{}}
|
||||
}
|
||||
|
||||
func (s *fakeRuntimeRecords) seed(record runtime.RuntimeRecord) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
s.stored[record.GameID] = record
|
||||
}
|
||||
|
||||
func (s *fakeRuntimeRecords) Get(_ context.Context, gameID string) (runtime.RuntimeRecord, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
if s.getErr != nil {
|
||||
return runtime.RuntimeRecord{}, s.getErr
|
||||
}
|
||||
record, ok := s.stored[gameID]
|
||||
if !ok {
|
||||
return runtime.RuntimeRecord{}, runtime.ErrNotFound
|
||||
}
|
||||
return record, nil
|
||||
}
|
||||
|
||||
func (s *fakeRuntimeRecords) Insert(context.Context, runtime.RuntimeRecord) error {
|
||||
return errors.New("not used")
|
||||
}
|
||||
func (s *fakeRuntimeRecords) UpdateStatus(context.Context, ports.UpdateStatusInput) error {
|
||||
return errors.New("not used")
|
||||
}
|
||||
func (s *fakeRuntimeRecords) UpdateScheduling(context.Context, ports.UpdateSchedulingInput) error {
|
||||
return errors.New("not used")
|
||||
}
|
||||
func (s *fakeRuntimeRecords) ListDueRunning(context.Context, time.Time) ([]runtime.RuntimeRecord, error) {
|
||||
return nil, errors.New("not used")
|
||||
}
|
||||
func (s *fakeRuntimeRecords) ListByStatus(context.Context, runtime.Status) ([]runtime.RuntimeRecord, error) {
|
||||
return nil, errors.New("not used")
|
||||
}
|
||||
func (s *fakeRuntimeRecords) List(context.Context) ([]runtime.RuntimeRecord, error) {
|
||||
return nil, errors.New("not used")
|
||||
}
|
||||
func (s *fakeRuntimeRecords) UpdateImage(context.Context, ports.UpdateImageInput) error {
|
||||
return errors.New("not used")
|
||||
}
|
||||
func (s *fakeRuntimeRecords) UpdateEngineHealth(context.Context, ports.UpdateEngineHealthInput) error {
|
||||
return errors.New("not used")
|
||||
}
|
||||
func (s *fakeRuntimeRecords) Delete(context.Context, string) error {
|
||||
return errors.New("not used")
|
||||
}
|
||||
|
||||
type fakePlayerMappings struct {
|
||||
mu sync.Mutex
|
||||
stored map[string]map[string]playermapping.PlayerMapping
|
||||
getErr error
|
||||
}
|
||||
|
||||
func newFakePlayerMappings() *fakePlayerMappings {
|
||||
return &fakePlayerMappings{stored: map[string]map[string]playermapping.PlayerMapping{}}
|
||||
}
|
||||
|
||||
func (s *fakePlayerMappings) seed(record playermapping.PlayerMapping) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
if _, ok := s.stored[record.GameID]; !ok {
|
||||
s.stored[record.GameID] = map[string]playermapping.PlayerMapping{}
|
||||
}
|
||||
s.stored[record.GameID][record.UserID] = record
|
||||
}
|
||||
|
||||
func (s *fakePlayerMappings) Get(_ context.Context, gameID, userID string) (playermapping.PlayerMapping, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
if s.getErr != nil {
|
||||
return playermapping.PlayerMapping{}, s.getErr
|
||||
}
|
||||
record, ok := s.stored[gameID][userID]
|
||||
if !ok {
|
||||
return playermapping.PlayerMapping{}, playermapping.ErrNotFound
|
||||
}
|
||||
return record, nil
|
||||
}
|
||||
|
||||
func (s *fakePlayerMappings) BulkInsert(context.Context, []playermapping.PlayerMapping) error {
|
||||
return errors.New("not used")
|
||||
}
|
||||
func (s *fakePlayerMappings) GetByRace(context.Context, string, string) (playermapping.PlayerMapping, error) {
|
||||
return playermapping.PlayerMapping{}, errors.New("not used")
|
||||
}
|
||||
func (s *fakePlayerMappings) ListByGame(context.Context, string) ([]playermapping.PlayerMapping, error) {
|
||||
return nil, errors.New("not used")
|
||||
}
|
||||
func (s *fakePlayerMappings) DeleteByGame(context.Context, string) error {
|
||||
return errors.New("not used")
|
||||
}
|
||||
|
||||
type recordedCall struct {
|
||||
baseURL string
|
||||
payload json.RawMessage
|
||||
}
|
||||
|
||||
type fakeEngine struct {
|
||||
mu sync.Mutex
|
||||
body json.RawMessage
|
||||
err error
|
||||
calls []recordedCall
|
||||
}
|
||||
|
||||
func (f *fakeEngine) PutOrders(_ context.Context, baseURL string, payload json.RawMessage) (json.RawMessage, error) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
stored := append(json.RawMessage(nil), payload...)
|
||||
f.calls = append(f.calls, recordedCall{baseURL: baseURL, payload: stored})
|
||||
return f.body, f.err
|
||||
}
|
||||
|
||||
func (f *fakeEngine) Init(context.Context, string, ports.InitRequest) (ports.StateResponse, error) {
|
||||
return ports.StateResponse{}, errors.New("not used")
|
||||
}
|
||||
func (f *fakeEngine) Status(context.Context, string) (ports.StateResponse, error) {
|
||||
return ports.StateResponse{}, errors.New("not used")
|
||||
}
|
||||
func (f *fakeEngine) Turn(context.Context, string) (ports.StateResponse, error) {
|
||||
return ports.StateResponse{}, errors.New("not used")
|
||||
}
|
||||
func (f *fakeEngine) BanishRace(context.Context, string, string) error {
|
||||
return errors.New("not used")
|
||||
}
|
||||
func (f *fakeEngine) ExecuteCommands(context.Context, string, json.RawMessage) (json.RawMessage, error) {
|
||||
return nil, errors.New("not used")
|
||||
}
|
||||
func (f *fakeEngine) GetReport(context.Context, string, string, int) (json.RawMessage, error) {
|
||||
return nil, errors.New("not used")
|
||||
}
|
||||
|
||||
type fakeLobby struct {
|
||||
mu sync.Mutex
|
||||
answers map[string][]ports.Membership
|
||||
errs map[string]error
|
||||
}
|
||||
|
||||
func newFakeLobby() *fakeLobby {
|
||||
return &fakeLobby{
|
||||
answers: map[string][]ports.Membership{},
|
||||
errs: map[string]error{},
|
||||
}
|
||||
}
|
||||
|
||||
func (f *fakeLobby) seed(gameID string, members []ports.Membership) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
f.answers[gameID] = members
|
||||
}
|
||||
|
||||
func (f *fakeLobby) seedErr(gameID string, err error) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
f.errs[gameID] = err
|
||||
}
|
||||
|
||||
func (f *fakeLobby) GetMemberships(_ context.Context, gameID string) ([]ports.Membership, error) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
if err, ok := f.errs[gameID]; ok {
|
||||
return nil, err
|
||||
}
|
||||
return append([]ports.Membership(nil), f.answers[gameID]...), nil
|
||||
}
|
||||
|
||||
func (f *fakeLobby) GetGameSummary(context.Context, string) (ports.GameSummary, error) {
|
||||
return ports.GameSummary{}, errors.New("not used")
|
||||
}
|
||||
|
||||
// --- harness ----------------------------------------------------------
|
||||
|
||||
type harness struct {
|
||||
t *testing.T
|
||||
now time.Time
|
||||
runtimes *fakeRuntimeRecords
|
||||
mappings *fakePlayerMappings
|
||||
engine *fakeEngine
|
||||
lobby *fakeLobby
|
||||
cache *membership.Cache
|
||||
service *orderput.Service
|
||||
}
|
||||
|
||||
const (
|
||||
testGameID = "game-001"
|
||||
testUserID = "user-1"
|
||||
testRaceName = "Aelinari"
|
||||
testEngineEndpoint = "http://galaxy-game-game-001:8080"
|
||||
)
|
||||
|
||||
func newHarness(t *testing.T) *harness {
|
||||
t.Helper()
|
||||
tel, err := telemetry.NewWithProviders(nil, nil)
|
||||
require.NoError(t, err)
|
||||
now := time.Date(2026, 5, 1, 12, 0, 0, 0, time.UTC)
|
||||
|
||||
h := &harness{
|
||||
t: t,
|
||||
now: now,
|
||||
runtimes: newFakeRuntimeRecords(),
|
||||
mappings: newFakePlayerMappings(),
|
||||
engine: &fakeEngine{},
|
||||
lobby: newFakeLobby(),
|
||||
}
|
||||
|
||||
cache, err := membership.NewCache(membership.Dependencies{
|
||||
Lobby: h.lobby,
|
||||
Telemetry: tel,
|
||||
TTL: time.Minute,
|
||||
MaxGames: 16,
|
||||
Clock: func() time.Time { return h.now },
|
||||
})
|
||||
require.NoError(t, err)
|
||||
h.cache = cache
|
||||
|
||||
svc, err := orderput.NewService(orderput.Dependencies{
|
||||
RuntimeRecords: h.runtimes,
|
||||
PlayerMappings: h.mappings,
|
||||
Membership: h.cache,
|
||||
Engine: h.engine,
|
||||
Telemetry: tel,
|
||||
Clock: func() time.Time { return h.now },
|
||||
})
|
||||
require.NoError(t, err)
|
||||
h.service = svc
|
||||
return h
|
||||
}
|
||||
|
||||
func (h *harness) seedRunningRecord() {
|
||||
startedAt := h.now.Add(-1 * time.Hour)
|
||||
h.runtimes.seed(runtime.RuntimeRecord{
|
||||
GameID: testGameID,
|
||||
Status: runtime.StatusRunning,
|
||||
EngineEndpoint: testEngineEndpoint,
|
||||
CurrentImageRef: "ghcr.io/galaxy/game:v1.2.3",
|
||||
CurrentEngineVersion: "v1.2.3",
|
||||
TurnSchedule: "0 18 * * *",
|
||||
EngineHealth: "healthy",
|
||||
CreatedAt: h.now.Add(-2 * time.Hour),
|
||||
UpdatedAt: h.now.Add(-2 * time.Hour),
|
||||
StartedAt: &startedAt,
|
||||
})
|
||||
}
|
||||
|
||||
func (h *harness) seedActiveMembership() {
|
||||
h.lobby.seed(testGameID, []ports.Membership{{
|
||||
UserID: testUserID,
|
||||
RaceName: testRaceName,
|
||||
Status: "active",
|
||||
JoinedAt: h.now.Add(-2 * time.Hour),
|
||||
}})
|
||||
}
|
||||
|
||||
func (h *harness) seedPlayerMapping() {
|
||||
h.mappings.seed(playermapping.PlayerMapping{
|
||||
GameID: testGameID,
|
||||
UserID: testUserID,
|
||||
RaceName: testRaceName,
|
||||
EnginePlayerUUID: "uuid-1",
|
||||
CreatedAt: h.now.Add(-2 * time.Hour),
|
||||
})
|
||||
}
|
||||
|
||||
func (h *harness) inputWithCommands(payload string) orderput.Input {
|
||||
return orderput.Input{
|
||||
GameID: testGameID,
|
||||
UserID: testUserID,
|
||||
Payload: json.RawMessage(payload),
|
||||
}
|
||||
}
|
||||
|
||||
func basicOrdersPayload() string {
|
||||
return `{"commands":[{"@type":"BUILD_SHIP","cmdId":"00000000-0000-0000-0000-000000000001"}]}`
|
||||
}
|
||||
|
||||
// --- tests ------------------------------------------------------------
|
||||
|
||||
func TestNewServiceRejectsBadDependencies(t *testing.T) {
|
||||
tel, err := telemetry.NewWithProviders(nil, nil)
|
||||
require.NoError(t, err)
|
||||
cache, err := membership.NewCache(membership.Dependencies{
|
||||
Lobby: newFakeLobby(), Telemetry: tel, TTL: time.Minute, MaxGames: 1,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
cases := []struct {
|
||||
name string
|
||||
deps orderput.Dependencies
|
||||
}{
|
||||
{"nil runtime records", orderput.Dependencies{PlayerMappings: newFakePlayerMappings(), Membership: cache, Engine: &fakeEngine{}, Telemetry: tel}},
|
||||
{"nil player mappings", orderput.Dependencies{RuntimeRecords: newFakeRuntimeRecords(), Membership: cache, Engine: &fakeEngine{}, Telemetry: tel}},
|
||||
{"nil membership", orderput.Dependencies{RuntimeRecords: newFakeRuntimeRecords(), PlayerMappings: newFakePlayerMappings(), Engine: &fakeEngine{}, Telemetry: tel}},
|
||||
{"nil engine", orderput.Dependencies{RuntimeRecords: newFakeRuntimeRecords(), PlayerMappings: newFakePlayerMappings(), Membership: cache, Telemetry: tel}},
|
||||
{"nil telemetry", orderput.Dependencies{RuntimeRecords: newFakeRuntimeRecords(), PlayerMappings: newFakePlayerMappings(), Membership: cache, Engine: &fakeEngine{}}},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
svc, err := orderput.NewService(tc.deps)
|
||||
require.Error(t, err)
|
||||
assert.Nil(t, svc)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleHappyPath(t *testing.T) {
|
||||
h := newHarness(t)
|
||||
h.seedRunningRecord()
|
||||
h.seedActiveMembership()
|
||||
h.seedPlayerMapping()
|
||||
h.engine.body = json.RawMessage(`{"results":[{"cmd_id":"00000000-0000-0000-0000-000000000001","cmd_applied":true}]}`)
|
||||
|
||||
result, err := h.service.Handle(context.Background(), h.inputWithCommands(basicOrdersPayload()))
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, operation.OutcomeSuccess, result.Outcome)
|
||||
assert.JSONEq(t, string(h.engine.body), string(result.RawResponse))
|
||||
|
||||
require.Len(t, h.engine.calls, 1)
|
||||
assert.Equal(t, testEngineEndpoint, h.engine.calls[0].baseURL)
|
||||
var sentToEngine map[string]json.RawMessage
|
||||
require.NoError(t, json.Unmarshal(h.engine.calls[0].payload, &sentToEngine))
|
||||
assert.Contains(t, sentToEngine, "actor")
|
||||
assert.Contains(t, sentToEngine, "cmd")
|
||||
assert.NotContains(t, sentToEngine, "commands", "GM must rewrite the field name")
|
||||
var actor string
|
||||
require.NoError(t, json.Unmarshal(sentToEngine["actor"], &actor))
|
||||
assert.Equal(t, testRaceName, actor)
|
||||
}
|
||||
|
||||
func TestHandleHappyPathDoesNotTrustCallerActor(t *testing.T) {
|
||||
h := newHarness(t)
|
||||
h.seedRunningRecord()
|
||||
h.seedActiveMembership()
|
||||
h.seedPlayerMapping()
|
||||
h.engine.body = json.RawMessage(`{}`)
|
||||
|
||||
payload := `{"actor":"Hacker","commands":[{"@type":"BUILD_SHIP","cmdId":"00000000-0000-0000-0000-000000000001"}]}`
|
||||
result, err := h.service.Handle(context.Background(), h.inputWithCommands(payload))
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, operation.OutcomeSuccess, result.Outcome)
|
||||
|
||||
var sentToEngine map[string]json.RawMessage
|
||||
require.NoError(t, json.Unmarshal(h.engine.calls[0].payload, &sentToEngine))
|
||||
var actor string
|
||||
require.NoError(t, json.Unmarshal(sentToEngine["actor"], &actor))
|
||||
assert.Equal(t, testRaceName, actor, "GM must override caller-supplied actor")
|
||||
}
|
||||
|
||||
func TestHandleInvalidRequest(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
input orderput.Input
|
||||
message string
|
||||
}{
|
||||
{"empty game id", orderput.Input{UserID: testUserID, Payload: json.RawMessage(basicOrdersPayload())}, "game id"},
|
||||
{"empty user id", orderput.Input{GameID: testGameID, Payload: json.RawMessage(basicOrdersPayload())}, "user id"},
|
||||
{"empty payload", orderput.Input{GameID: testGameID, UserID: testUserID}, "payload"},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
h := newHarness(t)
|
||||
result, err := h.service.Handle(context.Background(), tc.input)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, operation.OutcomeFailure, result.Outcome)
|
||||
assert.Equal(t, orderput.ErrorCodeInvalidRequest, result.ErrorCode)
|
||||
assert.Contains(t, result.ErrorMessage, tc.message)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleMalformedPayload(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
payload string
|
||||
}{
|
||||
{"non-object", `[1,2,3]`},
|
||||
{"missing commands", `{"orders":[]}`},
|
||||
{"commands not array", `{"commands":"oops"}`},
|
||||
{"non-json", `not json`},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
h := newHarness(t)
|
||||
h.seedRunningRecord()
|
||||
h.seedActiveMembership()
|
||||
h.seedPlayerMapping()
|
||||
|
||||
result, err := h.service.Handle(context.Background(), h.inputWithCommands(tc.payload))
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, operation.OutcomeFailure, result.Outcome)
|
||||
assert.Equal(t, orderput.ErrorCodeInvalidRequest, result.ErrorCode)
|
||||
assert.Empty(t, h.engine.calls)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleRuntimeNotFound(t *testing.T) {
|
||||
h := newHarness(t)
|
||||
result, err := h.service.Handle(context.Background(), h.inputWithCommands(basicOrdersPayload()))
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, operation.OutcomeFailure, result.Outcome)
|
||||
assert.Equal(t, orderput.ErrorCodeRuntimeNotFound, result.ErrorCode)
|
||||
}
|
||||
|
||||
func TestHandleRuntimeStoreError(t *testing.T) {
|
||||
h := newHarness(t)
|
||||
h.runtimes.getErr = errors.New("postgres down")
|
||||
result, err := h.service.Handle(context.Background(), h.inputWithCommands(basicOrdersPayload()))
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, operation.OutcomeFailure, result.Outcome)
|
||||
assert.Equal(t, orderput.ErrorCodeServiceUnavailable, result.ErrorCode)
|
||||
}
|
||||
|
||||
func TestHandleRuntimeNotRunning(t *testing.T) {
|
||||
for _, status := range []runtime.Status{
|
||||
runtime.StatusStarting,
|
||||
runtime.StatusGenerationInProgress,
|
||||
runtime.StatusGenerationFailed,
|
||||
runtime.StatusStopped,
|
||||
runtime.StatusEngineUnreachable,
|
||||
runtime.StatusFinished,
|
||||
} {
|
||||
t.Run(string(status), func(t *testing.T) {
|
||||
h := newHarness(t)
|
||||
startedAt := h.now.Add(-1 * time.Hour)
|
||||
finishedAt := h.now
|
||||
record := runtime.RuntimeRecord{
|
||||
GameID: testGameID,
|
||||
Status: status,
|
||||
EngineEndpoint: testEngineEndpoint,
|
||||
CurrentImageRef: "ghcr.io/galaxy/game:v1.2.3",
|
||||
CurrentEngineVersion: "v1.2.3",
|
||||
TurnSchedule: "0 18 * * *",
|
||||
CreatedAt: h.now.Add(-2 * time.Hour),
|
||||
UpdatedAt: h.now.Add(-2 * time.Hour),
|
||||
}
|
||||
if status != runtime.StatusStarting {
|
||||
record.StartedAt = &startedAt
|
||||
}
|
||||
if status == runtime.StatusStopped {
|
||||
record.StoppedAt = &finishedAt
|
||||
}
|
||||
if status == runtime.StatusFinished {
|
||||
record.FinishedAt = &finishedAt
|
||||
}
|
||||
h.runtimes.seed(record)
|
||||
|
||||
result, err := h.service.Handle(context.Background(), h.inputWithCommands(basicOrdersPayload()))
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, operation.OutcomeFailure, result.Outcome)
|
||||
assert.Equal(t, orderput.ErrorCodeRuntimeNotRunning, result.ErrorCode)
|
||||
assert.Empty(t, h.engine.calls)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleForbiddenInactiveMembership(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
members []ports.Membership
|
||||
}{
|
||||
{"removed", []ports.Membership{{UserID: testUserID, RaceName: testRaceName, Status: "removed"}}},
|
||||
{"blocked", []ports.Membership{{UserID: testUserID, RaceName: testRaceName, Status: "blocked"}}},
|
||||
{"unknown user", []ports.Membership{{UserID: "ghost", RaceName: "Ghost", Status: "active"}}},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
h := newHarness(t)
|
||||
h.seedRunningRecord()
|
||||
h.seedPlayerMapping()
|
||||
h.lobby.seed(testGameID, tc.members)
|
||||
|
||||
result, err := h.service.Handle(context.Background(), h.inputWithCommands(basicOrdersPayload()))
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, operation.OutcomeFailure, result.Outcome)
|
||||
assert.Equal(t, orderput.ErrorCodeForbidden, result.ErrorCode)
|
||||
assert.Empty(t, h.engine.calls)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleForbiddenMissingPlayerMapping(t *testing.T) {
|
||||
h := newHarness(t)
|
||||
h.seedRunningRecord()
|
||||
h.seedActiveMembership()
|
||||
result, err := h.service.Handle(context.Background(), h.inputWithCommands(basicOrdersPayload()))
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, operation.OutcomeFailure, result.Outcome)
|
||||
assert.Equal(t, orderput.ErrorCodeForbidden, result.ErrorCode)
|
||||
assert.Empty(t, h.engine.calls)
|
||||
}
|
||||
|
||||
func TestHandleServiceUnavailableLobbyDown(t *testing.T) {
|
||||
h := newHarness(t)
|
||||
h.seedRunningRecord()
|
||||
h.seedPlayerMapping()
|
||||
h.lobby.seedErr(testGameID, fmt.Errorf("dial: %w", ports.ErrLobbyUnavailable))
|
||||
result, err := h.service.Handle(context.Background(), h.inputWithCommands(basicOrdersPayload()))
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, operation.OutcomeFailure, result.Outcome)
|
||||
assert.Equal(t, orderput.ErrorCodeServiceUnavailable, result.ErrorCode)
|
||||
}
|
||||
|
||||
func TestHandleServiceUnavailablePlayerMappingsError(t *testing.T) {
|
||||
h := newHarness(t)
|
||||
h.seedRunningRecord()
|
||||
h.seedActiveMembership()
|
||||
h.mappings.getErr = errors.New("postgres down")
|
||||
result, err := h.service.Handle(context.Background(), h.inputWithCommands(basicOrdersPayload()))
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, operation.OutcomeFailure, result.Outcome)
|
||||
assert.Equal(t, orderput.ErrorCodeServiceUnavailable, result.ErrorCode)
|
||||
}
|
||||
|
||||
func TestHandleEngineUnreachable(t *testing.T) {
|
||||
h := newHarness(t)
|
||||
h.seedRunningRecord()
|
||||
h.seedActiveMembership()
|
||||
h.seedPlayerMapping()
|
||||
h.engine.err = fmt.Errorf("dial: %w", ports.ErrEngineUnreachable)
|
||||
|
||||
result, err := h.service.Handle(context.Background(), h.inputWithCommands(basicOrdersPayload()))
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, operation.OutcomeFailure, result.Outcome)
|
||||
assert.Equal(t, orderput.ErrorCodeEngineUnreachable, result.ErrorCode)
|
||||
}
|
||||
|
||||
func TestHandleEngineValidationErrorForwardsBody(t *testing.T) {
|
||||
h := newHarness(t)
|
||||
h.seedRunningRecord()
|
||||
h.seedActiveMembership()
|
||||
h.seedPlayerMapping()
|
||||
h.engine.body = json.RawMessage(`{"results":[{"cmd_id":"x","cmd_error_code":"INVALID_TARGET"}]}`)
|
||||
h.engine.err = fmt.Errorf("400: %w", ports.ErrEngineValidation)
|
||||
|
||||
result, err := h.service.Handle(context.Background(), h.inputWithCommands(basicOrdersPayload()))
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, operation.OutcomeFailure, result.Outcome)
|
||||
assert.Equal(t, orderput.ErrorCodeEngineValidationError, result.ErrorCode)
|
||||
assert.JSONEq(t, string(h.engine.body), string(result.RawResponse))
|
||||
}
|
||||
|
||||
func TestHandleEngineProtocolViolation(t *testing.T) {
|
||||
h := newHarness(t)
|
||||
h.seedRunningRecord()
|
||||
h.seedActiveMembership()
|
||||
h.seedPlayerMapping()
|
||||
h.engine.err = fmt.Errorf("garbled: %w", ports.ErrEngineProtocolViolation)
|
||||
|
||||
result, err := h.service.Handle(context.Background(), h.inputWithCommands(basicOrdersPayload()))
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, operation.OutcomeFailure, result.Outcome)
|
||||
assert.Equal(t, orderput.ErrorCodeEngineProtocolViolation, result.ErrorCode)
|
||||
}
|
||||
|
||||
func TestHandleNilContext(t *testing.T) {
|
||||
h := newHarness(t)
|
||||
var nilCtx context.Context
|
||||
_, err := h.service.Handle(nilCtx, h.inputWithCommands(basicOrdersPayload()))
|
||||
require.Error(t, err)
|
||||
}
|
||||
|
||||
func TestHandleNilReceiver(t *testing.T) {
|
||||
var svc *orderput.Service
|
||||
_, err := svc.Handle(context.Background(), orderput.Input{})
|
||||
require.Error(t, err)
|
||||
}
|
||||
Reference in New Issue
Block a user