feat: gamemaster

This commit is contained in:
Ilia Denisov
2026-05-03 07:59:03 +02:00
committed by GitHub
parent a7cee15115
commit 3e2622757e
229 changed files with 41521 additions and 1098 deletions
@@ -0,0 +1,48 @@
package reportget
// 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.
//
// Note: the report-get operation does **not** require the runtime to be
// in `running` state. Reports may be served against any runtime that
// exists in `runtime_records`; an unreachable engine surfaces naturally
// through `engine_unreachable`. Therefore `runtime_not_running` is not
// part of this vocabulary.
const (
// ErrorCodeInvalidRequest reports that the request envelope failed
// structural validation (empty required field, negative turn).
ErrorCodeInvalidRequest = "invalid_request"
// ErrorCodeRuntimeNotFound reports that no `runtime_records` row
// exists for the requested game id.
ErrorCodeRuntimeNotFound = "runtime_not_found"
// 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/report
// call returned a 5xx status, timed out, or could not be dispatched.
ErrorCodeEngineUnreachable = "engine_unreachable"
// ErrorCodeEngineValidationError reports that the engine returned
// 4xx. The body is forwarded verbatim through `Result.RawResponse`.
ErrorCodeEngineValidationError = "engine_validation_error"
// ErrorCodeEngineProtocolViolation reports that the engine response
// did not match the expected schema (empty body, malformed JSON).
// 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,314 @@
// Package reportget implements the per-player turn-report hot-path
// service owned by Game Master. It accepts a verified `(game_id, user_id,
// turn)` envelope from Edge Gateway, authorises the caller against the
// membership cache, resolves `race_name` from `player_mappings`, and
// forwards `GET /api/v1/report?player={race_name}&turn={turn}` to the
// engine.
//
// Lifecycle and error semantics follow `gamemaster/README.md §Hot Path →
// Reports`. Unlike commandexecute and orderput, the report service does
// not require `runtime_records.status = running`: reports may be served
// against any runtime that exists in the table, allowing post-finish
// inspection. Design rationale (decision D1) is captured in
// `gamemaster/docs/stage16-membership-cache-and-invalidation.md`.
package reportget
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 = "report"
membershipStatusActive = "active"
)
// Input stores the per-call arguments for one report-get operation.
type Input struct {
// GameID identifies the platform game whose report is being read.
GameID string
// UserID identifies the platform user submitting the request. The
// service derives `race_name` from this value via `player_mappings`
// before calling the engine.
UserID string
// Turn identifies the turn number to read. Must be non-negative;
// zero requests the initial state report.
Turn int
}
// 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 input.Turn < 0 {
return fmt.Errorf("turn must not be negative, got %d", input.Turn)
}
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.
RuntimeRecords ports.RuntimeRecordStore
// PlayerMappings resolves `(game_id, user_id) → race_name`.
PlayerMappings ports.PlayerMappingStore
// Membership authorises the caller.
Membership *membership.Cache
// Engine forwards `GET /api/v1/report` calls.
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 report-get 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 report get service: nil runtime records")
case deps.PlayerMappings == nil:
return nil, errors.New("new report get service: nil player mappings")
case deps.Membership == nil:
return nil, errors.New("new report get service: nil membership cache")
case deps.Engine == nil:
return nil, errors.New("new report get service: nil engine client")
case deps.Telemetry == nil:
return nil, errors.New("new report get 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.reportget")
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 report-get 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("report get: nil service")
}
if ctx == nil {
return Result{}, errors.New("report get: 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
}
mapping, result, ok := service.authorise(ctx, input)
if !ok {
return result, nil
}
body, engineErr := service.callEngine(ctx, record.EngineEndpoint, mapping.RaceName, input.Turn)
if engineErr != nil {
errorCode := classifyEngineError(engineErr)
message := fmt.Sprintf("engine report: %s", engineErr.Error())
var bodyForCaller json.RawMessage
if errorCode == ErrorCodeEngineValidationError {
bodyForCaller = body
}
return service.recordFailure(ctx, input, errorCode, message, bodyForCaller), nil
}
service.telemetry.RecordReportGetOutcome(ctx,
string(operation.OutcomeSuccess), "")
logArgs := []any{
"game_id", input.GameID,
"user_id", input.UserID,
"actor", mapping.RaceName,
"turn", input.Turn,
}
logArgs = append(logArgs, logging.ContextAttrs(ctx)...)
service.logger.InfoContext(ctx, "report get 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. Reports tolerate any non-deleted runtime status; the running
// guard from commandexecute / orderput is intentionally absent.
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 reports", 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 read to the engine and records the wall-clock
// latency under the `report` op label.
func (service *Service) callEngine(ctx context.Context, baseURL, raceName string, turn int) (json.RawMessage, error) {
start := service.clock()
body, err := service.engine.GetReport(ctx, baseURL, raceName, turn)
service.telemetry.RecordEngineCall(ctx, engineCallOp, service.clock().Sub(start))
return body, err
}
// classifyEngineError maps the engine port sentinels to the report-get
// 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.RecordReportGetOutcome(ctx,
string(operation.OutcomeFailure), errorCode)
logArgs := []any{
"game_id", input.GameID,
"user_id", input.UserID,
"turn", input.Turn,
"error_code", errorCode,
"error_message", errorMessage,
}
logArgs = append(logArgs, logging.ContextAttrs(ctx)...)
service.logger.WarnContext(ctx, "report get rejected", logArgs...)
return Result{
Outcome: operation.OutcomeFailure,
ErrorCode: errorCode,
ErrorMessage: errorMessage,
RawResponse: rawResponse,
}
}
@@ -0,0 +1,533 @@
package reportget_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/reportget"
"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 recordedReport struct {
baseURL string
raceName string
turn int
}
type fakeEngine struct {
mu sync.Mutex
body json.RawMessage
err error
calls []recordedReport
}
func (f *fakeEngine) GetReport(_ context.Context, baseURL, raceName string, turn int) (json.RawMessage, error) {
f.mu.Lock()
defer f.mu.Unlock()
f.calls = append(f.calls, recordedReport{baseURL: baseURL, raceName: raceName, turn: turn})
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) PutOrders(context.Context, string, json.RawMessage) (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 *reportget.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 := reportget.NewService(reportget.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) seedRecordWithStatus(status runtime.Status) {
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 * * *",
EngineHealth: "healthy",
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)
}
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) input(turn int) reportget.Input {
return reportget.Input{GameID: testGameID, UserID: testUserID, Turn: turn}
}
// --- 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 reportget.Dependencies
}{
{"nil runtime records", reportget.Dependencies{PlayerMappings: newFakePlayerMappings(), Membership: cache, Engine: &fakeEngine{}, Telemetry: tel}},
{"nil player mappings", reportget.Dependencies{RuntimeRecords: newFakeRuntimeRecords(), Membership: cache, Engine: &fakeEngine{}, Telemetry: tel}},
{"nil membership", reportget.Dependencies{RuntimeRecords: newFakeRuntimeRecords(), PlayerMappings: newFakePlayerMappings(), Engine: &fakeEngine{}, Telemetry: tel}},
{"nil engine", reportget.Dependencies{RuntimeRecords: newFakeRuntimeRecords(), PlayerMappings: newFakePlayerMappings(), Membership: cache, Telemetry: tel}},
{"nil telemetry", reportget.Dependencies{RuntimeRecords: newFakeRuntimeRecords(), PlayerMappings: newFakePlayerMappings(), Membership: cache, Engine: &fakeEngine{}}},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
svc, err := reportget.NewService(tc.deps)
require.Error(t, err)
assert.Nil(t, svc)
})
}
}
func TestHandleHappyPath(t *testing.T) {
h := newHarness(t)
h.seedRecordWithStatus(runtime.StatusRunning)
h.seedActiveMembership()
h.seedPlayerMapping()
h.engine.body = json.RawMessage(`{"version":1,"turn":3,"player":[]}`)
result, err := h.service.Handle(context.Background(), h.input(3))
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)
assert.Equal(t, testRaceName, h.engine.calls[0].raceName)
assert.Equal(t, 3, h.engine.calls[0].turn)
}
func TestHandleAcceptsAnyNonNotFoundStatus(t *testing.T) {
for _, status := range []runtime.Status{
runtime.StatusStarting,
runtime.StatusRunning,
runtime.StatusGenerationInProgress,
runtime.StatusGenerationFailed,
runtime.StatusStopped,
runtime.StatusEngineUnreachable,
runtime.StatusFinished,
} {
t.Run(string(status), func(t *testing.T) {
h := newHarness(t)
h.seedRecordWithStatus(status)
h.seedActiveMembership()
h.seedPlayerMapping()
h.engine.body = json.RawMessage(`{"version":1,"turn":0,"player":[]}`)
result, err := h.service.Handle(context.Background(), h.input(0))
require.NoError(t, err)
assert.Equal(t, operation.OutcomeSuccess, result.Outcome,
"reports must be served regardless of status; got %s", result.ErrorCode)
})
}
}
func TestHandleInvalidRequest(t *testing.T) {
cases := []struct {
name string
input reportget.Input
message string
}{
{"empty game id", reportget.Input{UserID: testUserID, Turn: 0}, "game id"},
{"empty user id", reportget.Input{GameID: testGameID, Turn: 0}, "user id"},
{"negative turn", reportget.Input{GameID: testGameID, UserID: testUserID, Turn: -1}, "turn"},
}
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, reportget.ErrorCodeInvalidRequest, result.ErrorCode)
assert.Contains(t, result.ErrorMessage, tc.message)
})
}
}
func TestHandleRuntimeNotFound(t *testing.T) {
h := newHarness(t)
result, err := h.service.Handle(context.Background(), h.input(0))
require.NoError(t, err)
assert.Equal(t, operation.OutcomeFailure, result.Outcome)
assert.Equal(t, reportget.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.input(0))
require.NoError(t, err)
assert.Equal(t, operation.OutcomeFailure, result.Outcome)
assert.Equal(t, reportget.ErrorCodeServiceUnavailable, result.ErrorCode)
}
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.seedRecordWithStatus(runtime.StatusRunning)
h.seedPlayerMapping()
h.lobby.seed(testGameID, tc.members)
result, err := h.service.Handle(context.Background(), h.input(0))
require.NoError(t, err)
assert.Equal(t, operation.OutcomeFailure, result.Outcome)
assert.Equal(t, reportget.ErrorCodeForbidden, result.ErrorCode)
assert.Empty(t, h.engine.calls)
})
}
}
func TestHandleForbiddenMissingPlayerMapping(t *testing.T) {
h := newHarness(t)
h.seedRecordWithStatus(runtime.StatusRunning)
h.seedActiveMembership()
result, err := h.service.Handle(context.Background(), h.input(0))
require.NoError(t, err)
assert.Equal(t, operation.OutcomeFailure, result.Outcome)
assert.Equal(t, reportget.ErrorCodeForbidden, result.ErrorCode)
assert.Empty(t, h.engine.calls)
}
func TestHandleServiceUnavailableLobbyDown(t *testing.T) {
h := newHarness(t)
h.seedRecordWithStatus(runtime.StatusRunning)
h.seedPlayerMapping()
h.lobby.seedErr(testGameID, fmt.Errorf("dial: %w", ports.ErrLobbyUnavailable))
result, err := h.service.Handle(context.Background(), h.input(0))
require.NoError(t, err)
assert.Equal(t, operation.OutcomeFailure, result.Outcome)
assert.Equal(t, reportget.ErrorCodeServiceUnavailable, result.ErrorCode)
}
func TestHandleServiceUnavailablePlayerMappingsError(t *testing.T) {
h := newHarness(t)
h.seedRecordWithStatus(runtime.StatusRunning)
h.seedActiveMembership()
h.mappings.getErr = errors.New("postgres down")
result, err := h.service.Handle(context.Background(), h.input(0))
require.NoError(t, err)
assert.Equal(t, operation.OutcomeFailure, result.Outcome)
assert.Equal(t, reportget.ErrorCodeServiceUnavailable, result.ErrorCode)
}
func TestHandleEngineUnreachable(t *testing.T) {
h := newHarness(t)
h.seedRecordWithStatus(runtime.StatusRunning)
h.seedActiveMembership()
h.seedPlayerMapping()
h.engine.err = fmt.Errorf("dial: %w", ports.ErrEngineUnreachable)
result, err := h.service.Handle(context.Background(), h.input(0))
require.NoError(t, err)
assert.Equal(t, operation.OutcomeFailure, result.Outcome)
assert.Equal(t, reportget.ErrorCodeEngineUnreachable, result.ErrorCode)
}
func TestHandleEngineValidationErrorForwardsBody(t *testing.T) {
h := newHarness(t)
h.seedRecordWithStatus(runtime.StatusRunning)
h.seedActiveMembership()
h.seedPlayerMapping()
h.engine.body = json.RawMessage(`{"error":"unknown turn"}`)
h.engine.err = fmt.Errorf("400: %w", ports.ErrEngineValidation)
result, err := h.service.Handle(context.Background(), h.input(99))
require.NoError(t, err)
assert.Equal(t, operation.OutcomeFailure, result.Outcome)
assert.Equal(t, reportget.ErrorCodeEngineValidationError, result.ErrorCode)
assert.JSONEq(t, string(h.engine.body), string(result.RawResponse))
}
func TestHandleEngineProtocolViolation(t *testing.T) {
h := newHarness(t)
h.seedRecordWithStatus(runtime.StatusRunning)
h.seedActiveMembership()
h.seedPlayerMapping()
h.engine.err = fmt.Errorf("garbled: %w", ports.ErrEngineProtocolViolation)
result, err := h.service.Handle(context.Background(), h.input(0))
require.NoError(t, err)
assert.Equal(t, operation.OutcomeFailure, result.Outcome)
assert.Equal(t, reportget.ErrorCodeEngineProtocolViolation, result.ErrorCode)
}
func TestHandleNilContext(t *testing.T) {
h := newHarness(t)
var nilCtx context.Context
_, err := h.service.Handle(nilCtx, h.input(0))
require.Error(t, err)
}
func TestHandleNilReceiver(t *testing.T) {
var svc *reportget.Service
_, err := svc.Handle(context.Background(), reportget.Input{})
require.Error(t, err)
}