feat: gamemaster
This commit is contained in:
@@ -0,0 +1,42 @@
|
||||
package adminbanish
|
||||
|
||||
// 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`. Service-layer callers (Stage
|
||||
// 19 handlers) import 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 GameID or RaceName).
|
||||
ErrorCodeInvalidRequest = "invalid_request"
|
||||
|
||||
// ErrorCodeRuntimeNotFound reports that no runtime_records row
|
||||
// exists for the requested game id.
|
||||
ErrorCodeRuntimeNotFound = "runtime_not_found"
|
||||
|
||||
// ErrorCodeForbidden reports that the requested race is not in the
|
||||
// game's roster (`player_mappings.GetByRace` returned not-found).
|
||||
ErrorCodeForbidden = "forbidden"
|
||||
|
||||
// ErrorCodeEngineUnreachable reports that the engine
|
||||
// `/admin/race/banish` call returned a 5xx, timed out, or could
|
||||
// not be dispatched.
|
||||
ErrorCodeEngineUnreachable = "engine_unreachable"
|
||||
|
||||
// ErrorCodeEngineValidationError reports that the engine
|
||||
// `/admin/race/banish` call returned a 4xx response (e.g. invalid
|
||||
// race name).
|
||||
ErrorCodeEngineValidationError = "engine_validation_error"
|
||||
|
||||
// ErrorCodeEngineProtocolViolation reports that the engine
|
||||
// response did not match the expected protocol shape.
|
||||
ErrorCodeEngineProtocolViolation = "engine_protocol_violation"
|
||||
|
||||
// ErrorCodeServiceUnavailable reports that a steady-state
|
||||
// dependency (PostgreSQL) 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,317 @@
|
||||
// Package adminbanish implements the admin banish service-layer
|
||||
// orchestrator owned by Game Master. It is driven by Game Lobby (and,
|
||||
// in a later iteration, Admin Service) through
|
||||
// `POST /api/v1/internal/games/{game_id}/race/{race_name}/banish` after
|
||||
// a permanent membership removal at the platform level. The flow
|
||||
// resolves the race against the installed roster, calls the engine
|
||||
// `/admin/race/banish` endpoint, and writes one operation_log row.
|
||||
//
|
||||
// Lifecycle and failure-mode semantics follow `gamemaster/README.md
|
||||
// §Lifecycles → Banish`. Design rationale (no runtime status check,
|
||||
// missing race surfaces as `forbidden`) is captured in
|
||||
// `gamemaster/docs/stage17-admin-operations.md`.
|
||||
package adminbanish
|
||||
|
||||
import (
|
||||
"context"
|
||||
"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/telemetry"
|
||||
)
|
||||
|
||||
// Input stores the per-call arguments for one admin banish operation.
|
||||
type Input struct {
|
||||
// GameID identifies the runtime the race belongs to.
|
||||
GameID string
|
||||
|
||||
// RaceName stores the platform race name to banish.
|
||||
RaceName string
|
||||
|
||||
// OpSource classifies how the request entered Game Master. Used to
|
||||
// stamp `operation_log.op_source`. Defaults to `lobby_internal`
|
||||
// when missing or unrecognised — Lobby is the only v1 caller.
|
||||
OpSource operation.OpSource
|
||||
|
||||
// SourceRef stores the optional opaque per-source reference (REST
|
||||
// request id). Empty when the caller does not provide one.
|
||||
SourceRef string
|
||||
}
|
||||
|
||||
// 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.RaceName) == "" {
|
||||
return fmt.Errorf("race name must not be empty")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Result stores the deterministic outcome of one Handle call. Business
|
||||
// outcomes flow through Result; the Go-level error return is reserved
|
||||
// for non-business failures (nil context, nil receiver).
|
||||
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
|
||||
}
|
||||
|
||||
// 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 supplies the engine endpoint used for the engine
|
||||
// call.
|
||||
RuntimeRecords ports.RuntimeRecordStore
|
||||
|
||||
// PlayerMappings resolves the race against the installed roster.
|
||||
PlayerMappings ports.PlayerMappingStore
|
||||
|
||||
// OperationLogs records the audit entry.
|
||||
OperationLogs ports.OperationLogStore
|
||||
|
||||
// Engine drives the `/admin/race/banish` call.
|
||||
Engine ports.EngineClient
|
||||
|
||||
// Telemetry is required: every banish call ends with a
|
||||
// `gamemaster.banish.outcomes` counter sample.
|
||||
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 operation timestamps.
|
||||
// Defaults to `time.Now` when nil.
|
||||
Clock func() time.Time
|
||||
}
|
||||
|
||||
// Service executes the admin banish lifecycle operation.
|
||||
type Service struct {
|
||||
runtimeRecords ports.RuntimeRecordStore
|
||||
playerMappings ports.PlayerMappingStore
|
||||
operationLogs ports.OperationLogStore
|
||||
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 admin banish service: nil runtime records")
|
||||
case deps.PlayerMappings == nil:
|
||||
return nil, errors.New("new admin banish service: nil player mappings")
|
||||
case deps.OperationLogs == nil:
|
||||
return nil, errors.New("new admin banish service: nil operation logs")
|
||||
case deps.Engine == nil:
|
||||
return nil, errors.New("new admin banish service: nil engine client")
|
||||
case deps.Telemetry == nil:
|
||||
return nil, errors.New("new admin banish 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.adminbanish")
|
||||
|
||||
return &Service{
|
||||
runtimeRecords: deps.RuntimeRecords,
|
||||
playerMappings: deps.PlayerMappings,
|
||||
operationLogs: deps.OperationLogs,
|
||||
engine: deps.Engine,
|
||||
telemetry: deps.Telemetry,
|
||||
logger: logger,
|
||||
clock: clock,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Handle executes one admin banish 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("admin banish: nil service")
|
||||
}
|
||||
if ctx == nil {
|
||||
return Result{}, errors.New("admin banish: nil context")
|
||||
}
|
||||
|
||||
opStartedAt := service.clock().UTC()
|
||||
|
||||
if err := input.Validate(); err != nil {
|
||||
return service.recordFailure(ctx, opStartedAt, input,
|
||||
ErrorCodeInvalidRequest, err.Error()), nil
|
||||
}
|
||||
|
||||
record, err := service.runtimeRecords.Get(ctx, input.GameID)
|
||||
switch {
|
||||
case errors.Is(err, runtime.ErrNotFound):
|
||||
return service.recordFailure(ctx, opStartedAt, input,
|
||||
ErrorCodeRuntimeNotFound, "runtime record does not exist"), nil
|
||||
case err != nil:
|
||||
return service.recordFailure(ctx, opStartedAt, input,
|
||||
ErrorCodeServiceUnavailable, fmt.Sprintf("get runtime record: %s", err.Error())), nil
|
||||
}
|
||||
|
||||
if _, err := service.playerMappings.GetByRace(ctx, input.GameID, input.RaceName); err != nil {
|
||||
switch {
|
||||
case errors.Is(err, playermapping.ErrNotFound):
|
||||
return service.recordFailure(ctx, opStartedAt, input,
|
||||
ErrorCodeForbidden, fmt.Sprintf("race %q not in roster", input.RaceName)), nil
|
||||
default:
|
||||
return service.recordFailure(ctx, opStartedAt, input,
|
||||
ErrorCodeServiceUnavailable, fmt.Sprintf("get player mapping by race: %s", err.Error())), nil
|
||||
}
|
||||
}
|
||||
|
||||
if err := service.engine.BanishRace(ctx, record.EngineEndpoint, input.RaceName); err != nil {
|
||||
errorCode := classifyEngineError(err)
|
||||
return service.recordFailure(ctx, opStartedAt, input,
|
||||
errorCode, fmt.Sprintf("engine banish: %s", err.Error())), nil
|
||||
}
|
||||
|
||||
service.appendSuccessLog(ctx, opStartedAt, input)
|
||||
service.telemetry.RecordBanishOutcome(ctx, string(operation.OutcomeSuccess), "")
|
||||
|
||||
logArgs := []any{
|
||||
"game_id", input.GameID,
|
||||
"race_name", input.RaceName,
|
||||
"op_source", string(fallbackOpSource(input.OpSource)),
|
||||
}
|
||||
logArgs = append(logArgs, logging.ContextAttrs(ctx)...)
|
||||
service.logger.InfoContext(ctx, "race banished", logArgs...)
|
||||
|
||||
return Result{Outcome: operation.OutcomeSuccess}, nil
|
||||
}
|
||||
|
||||
// recordFailure assembles the failure Result, appends the
|
||||
// operation_log failure entry, emits telemetry, and returns the
|
||||
// structured outcome.
|
||||
func (service *Service) recordFailure(ctx context.Context, opStartedAt time.Time, input Input, errorCode string, errorMessage string) Result {
|
||||
service.appendFailureLog(ctx, opStartedAt, input, errorCode, errorMessage)
|
||||
service.telemetry.RecordBanishOutcome(ctx, string(operation.OutcomeFailure), errorCode)
|
||||
|
||||
logArgs := []any{
|
||||
"game_id", input.GameID,
|
||||
"race_name", input.RaceName,
|
||||
"op_source", string(input.OpSource),
|
||||
"error_code", errorCode,
|
||||
"error_message", errorMessage,
|
||||
}
|
||||
logArgs = append(logArgs, logging.ContextAttrs(ctx)...)
|
||||
service.logger.WarnContext(ctx, "admin banish rejected", logArgs...)
|
||||
|
||||
return Result{
|
||||
Outcome: operation.OutcomeFailure,
|
||||
ErrorCode: errorCode,
|
||||
ErrorMessage: errorMessage,
|
||||
}
|
||||
}
|
||||
|
||||
// classifyEngineError maps the engine port sentinels to the
|
||||
// admin-banish 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
|
||||
}
|
||||
}
|
||||
|
||||
// appendSuccessLog records the success operation_log entry.
|
||||
func (service *Service) appendSuccessLog(ctx context.Context, opStartedAt time.Time, input Input) {
|
||||
finishedAt := service.clock().UTC()
|
||||
service.bestEffortAppend(ctx, operation.OperationEntry{
|
||||
GameID: input.GameID,
|
||||
OpKind: operation.OpKindBanish,
|
||||
OpSource: fallbackOpSource(input.OpSource),
|
||||
SourceRef: input.SourceRef,
|
||||
Outcome: operation.OutcomeSuccess,
|
||||
StartedAt: opStartedAt,
|
||||
FinishedAt: &finishedAt,
|
||||
})
|
||||
}
|
||||
|
||||
// appendFailureLog records the failure operation_log entry. Skipped
|
||||
// when the input game id is empty so the entry validator does not
|
||||
// reject an audit row that adds no value.
|
||||
func (service *Service) appendFailureLog(ctx context.Context, opStartedAt time.Time, input Input, errorCode string, errorMessage string) {
|
||||
if strings.TrimSpace(input.GameID) == "" {
|
||||
return
|
||||
}
|
||||
finishedAt := service.clock().UTC()
|
||||
service.bestEffortAppend(ctx, operation.OperationEntry{
|
||||
GameID: input.GameID,
|
||||
OpKind: operation.OpKindBanish,
|
||||
OpSource: fallbackOpSource(input.OpSource),
|
||||
SourceRef: input.SourceRef,
|
||||
Outcome: operation.OutcomeFailure,
|
||||
ErrorCode: errorCode,
|
||||
ErrorMessage: errorMessage,
|
||||
StartedAt: opStartedAt,
|
||||
FinishedAt: &finishedAt,
|
||||
})
|
||||
}
|
||||
|
||||
// bestEffortAppend writes one operation_log entry. A failure is logged
|
||||
// and discarded; the engine state and runtime row are the source of
|
||||
// truth.
|
||||
func (service *Service) bestEffortAppend(ctx context.Context, entry operation.OperationEntry) {
|
||||
if _, err := service.operationLogs.Append(ctx, entry); err != nil {
|
||||
service.logger.ErrorContext(ctx, "append operation log",
|
||||
"game_id", entry.GameID,
|
||||
"op_kind", string(entry.OpKind),
|
||||
"outcome", string(entry.Outcome),
|
||||
"error_code", entry.ErrorCode,
|
||||
"err", err.Error(),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// fallbackOpSource defaults to `lobby_internal` when the caller did
|
||||
// not supply a known op source. Lobby is the only v1 banish caller; an
|
||||
// `admin_rest` source is preserved when explicitly set so future Admin
|
||||
// Service traffic is identifiable.
|
||||
func fallbackOpSource(source operation.OpSource) operation.OpSource {
|
||||
if source.IsKnown() {
|
||||
return source
|
||||
}
|
||||
return operation.OpSourceLobbyInternal
|
||||
}
|
||||
@@ -0,0 +1,415 @@
|
||||
package adminbanish_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"galaxy/gamemaster/internal/adapters/mocks"
|
||||
"galaxy/gamemaster/internal/domain/operation"
|
||||
"galaxy/gamemaster/internal/domain/playermapping"
|
||||
"galaxy/gamemaster/internal/domain/runtime"
|
||||
"galaxy/gamemaster/internal/ports"
|
||||
"galaxy/gamemaster/internal/service/adminbanish"
|
||||
"galaxy/gamemaster/internal/telemetry"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
"go.uber.org/mock/gomock"
|
||||
)
|
||||
|
||||
// --- test doubles -----------------------------------------------------
|
||||
|
||||
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) 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")
|
||||
}
|
||||
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")
|
||||
}
|
||||
|
||||
type fakePlayerMappings struct {
|
||||
mu sync.Mutex
|
||||
races map[string]map[string]playermapping.PlayerMapping
|
||||
getErr error
|
||||
}
|
||||
|
||||
func newFakePlayerMappings() *fakePlayerMappings {
|
||||
return &fakePlayerMappings{races: map[string]map[string]playermapping.PlayerMapping{}}
|
||||
}
|
||||
|
||||
func (s *fakePlayerMappings) seedRace(gameID, raceName, userID, uuid string) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
if _, ok := s.races[gameID]; !ok {
|
||||
s.races[gameID] = map[string]playermapping.PlayerMapping{}
|
||||
}
|
||||
s.races[gameID][raceName] = playermapping.PlayerMapping{
|
||||
GameID: gameID, UserID: userID, RaceName: raceName, EnginePlayerUUID: uuid,
|
||||
CreatedAt: time.Now(),
|
||||
}
|
||||
}
|
||||
|
||||
func (s *fakePlayerMappings) BulkInsert(context.Context, []playermapping.PlayerMapping) error {
|
||||
return errors.New("not used")
|
||||
}
|
||||
func (s *fakePlayerMappings) Get(context.Context, string, string) (playermapping.PlayerMapping, error) {
|
||||
return playermapping.PlayerMapping{}, errors.New("not used")
|
||||
}
|
||||
func (s *fakePlayerMappings) GetByRace(_ context.Context, gameID, raceName string) (playermapping.PlayerMapping, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
if s.getErr != nil {
|
||||
return playermapping.PlayerMapping{}, s.getErr
|
||||
}
|
||||
gameRaces, ok := s.races[gameID]
|
||||
if !ok {
|
||||
return playermapping.PlayerMapping{}, playermapping.ErrNotFound
|
||||
}
|
||||
rec, ok := gameRaces[raceName]
|
||||
if !ok {
|
||||
return playermapping.PlayerMapping{}, playermapping.ErrNotFound
|
||||
}
|
||||
return rec, nil
|
||||
}
|
||||
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 fakeOperationLogs struct {
|
||||
mu sync.Mutex
|
||||
entries []operation.OperationEntry
|
||||
}
|
||||
|
||||
func (s *fakeOperationLogs) Append(_ context.Context, entry operation.OperationEntry) (int64, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
if err := entry.Validate(); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
s.entries = append(s.entries, entry)
|
||||
return int64(len(s.entries)), nil
|
||||
}
|
||||
func (s *fakeOperationLogs) ListByGame(context.Context, string, int) ([]operation.OperationEntry, error) {
|
||||
return nil, errors.New("not used")
|
||||
}
|
||||
func (s *fakeOperationLogs) lastEntry() (operation.OperationEntry, bool) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
if len(s.entries) == 0 {
|
||||
return operation.OperationEntry{}, false
|
||||
}
|
||||
return s.entries[len(s.entries)-1], true
|
||||
}
|
||||
|
||||
// --- harness ----------------------------------------------------------
|
||||
|
||||
type harness struct {
|
||||
t *testing.T
|
||||
ctrl *gomock.Controller
|
||||
runtime *fakeRuntimeRecords
|
||||
mappings *fakePlayerMappings
|
||||
logs *fakeOperationLogs
|
||||
engine *mocks.MockEngineClient
|
||||
telemetry *telemetry.Runtime
|
||||
now time.Time
|
||||
service *adminbanish.Service
|
||||
}
|
||||
|
||||
func newHarness(t *testing.T) *harness {
|
||||
t.Helper()
|
||||
ctrl := gomock.NewController(t)
|
||||
telemetryRuntime, err := telemetry.NewWithProviders(nil, nil)
|
||||
require.NoError(t, err)
|
||||
h := &harness{
|
||||
t: t,
|
||||
ctrl: ctrl,
|
||||
runtime: newFakeRuntimeRecords(),
|
||||
mappings: newFakePlayerMappings(),
|
||||
logs: &fakeOperationLogs{},
|
||||
engine: mocks.NewMockEngineClient(ctrl),
|
||||
telemetry: telemetryRuntime,
|
||||
now: time.Date(2026, time.May, 1, 12, 0, 0, 0, time.UTC),
|
||||
}
|
||||
service, err := adminbanish.NewService(adminbanish.Dependencies{
|
||||
RuntimeRecords: h.runtime,
|
||||
PlayerMappings: h.mappings,
|
||||
OperationLogs: h.logs,
|
||||
Engine: h.engine,
|
||||
Telemetry: h.telemetry,
|
||||
Clock: func() time.Time { return h.now },
|
||||
})
|
||||
require.NoError(t, err)
|
||||
h.service = service
|
||||
return h
|
||||
}
|
||||
|
||||
const (
|
||||
testGameID = "game-001"
|
||||
testRaceName = "Aelinari"
|
||||
testEndpoint = "http://galaxy-game-game-001:8080"
|
||||
)
|
||||
|
||||
func (h *harness) seedRuntime(status runtime.Status) {
|
||||
created := h.now.Add(-time.Hour)
|
||||
started := h.now.Add(-30 * time.Minute)
|
||||
record := runtime.RuntimeRecord{
|
||||
GameID: testGameID,
|
||||
Status: status,
|
||||
EngineEndpoint: testEndpoint,
|
||||
CurrentImageRef: "ghcr.io/galaxy/game:v1.2.3",
|
||||
CurrentEngineVersion: "v1.2.3",
|
||||
TurnSchedule: "0 18 * * *",
|
||||
CurrentTurn: 7,
|
||||
CreatedAt: created,
|
||||
UpdatedAt: started,
|
||||
StartedAt: &started,
|
||||
}
|
||||
h.runtime.seed(record)
|
||||
}
|
||||
|
||||
func baseInput() adminbanish.Input {
|
||||
return adminbanish.Input{
|
||||
GameID: testGameID,
|
||||
RaceName: testRaceName,
|
||||
OpSource: operation.OpSourceLobbyInternal,
|
||||
SourceRef: "req-banish-001",
|
||||
}
|
||||
}
|
||||
|
||||
// --- tests ------------------------------------------------------------
|
||||
|
||||
func TestNewServiceRejectsMissingDeps(t *testing.T) {
|
||||
telemetryRuntime, err := telemetry.NewWithProviders(nil, nil)
|
||||
require.NoError(t, err)
|
||||
cases := []struct {
|
||||
name string
|
||||
mut func(*adminbanish.Dependencies)
|
||||
}{
|
||||
{"runtime records", func(d *adminbanish.Dependencies) { d.RuntimeRecords = nil }},
|
||||
{"player mappings", func(d *adminbanish.Dependencies) { d.PlayerMappings = nil }},
|
||||
{"operation logs", func(d *adminbanish.Dependencies) { d.OperationLogs = nil }},
|
||||
{"engine", func(d *adminbanish.Dependencies) { d.Engine = nil }},
|
||||
{"telemetry", func(d *adminbanish.Dependencies) { d.Telemetry = nil }},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
ctrl := gomock.NewController(t)
|
||||
deps := adminbanish.Dependencies{
|
||||
RuntimeRecords: newFakeRuntimeRecords(),
|
||||
PlayerMappings: newFakePlayerMappings(),
|
||||
OperationLogs: &fakeOperationLogs{},
|
||||
Engine: mocks.NewMockEngineClient(ctrl),
|
||||
Telemetry: telemetryRuntime,
|
||||
}
|
||||
tc.mut(&deps)
|
||||
service, err := adminbanish.NewService(deps)
|
||||
require.Error(t, err)
|
||||
require.Nil(t, service)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleHappyPath(t *testing.T) {
|
||||
h := newHarness(t)
|
||||
h.seedRuntime(runtime.StatusRunning)
|
||||
h.mappings.seedRace(testGameID, testRaceName, "user-1", "uuid-1")
|
||||
|
||||
h.engine.EXPECT().BanishRace(gomock.Any(), testEndpoint, testRaceName).Return(nil)
|
||||
|
||||
result, err := h.service.Handle(context.Background(), baseInput())
|
||||
require.NoError(t, err)
|
||||
require.True(t, result.IsSuccess(), "want success, got %+v", result)
|
||||
|
||||
entry, ok := h.logs.lastEntry()
|
||||
require.True(t, ok)
|
||||
assert.Equal(t, operation.OpKindBanish, entry.OpKind)
|
||||
assert.Equal(t, operation.OpSourceLobbyInternal, entry.OpSource)
|
||||
assert.Equal(t, operation.OutcomeSuccess, entry.Outcome)
|
||||
}
|
||||
|
||||
func TestHandleHappyPathOnStoppedRuntime(t *testing.T) {
|
||||
// README §Banish does not check status; the engine call may fail
|
||||
// later with engine_unreachable, but the service runs the call.
|
||||
h := newHarness(t)
|
||||
h.seedRuntime(runtime.StatusStopped)
|
||||
h.mappings.seedRace(testGameID, testRaceName, "user-1", "uuid-1")
|
||||
h.engine.EXPECT().BanishRace(gomock.Any(), testEndpoint, testRaceName).Return(nil)
|
||||
|
||||
result, err := h.service.Handle(context.Background(), baseInput())
|
||||
require.NoError(t, err)
|
||||
require.True(t, result.IsSuccess())
|
||||
}
|
||||
|
||||
func TestHandleRuntimeNotFound(t *testing.T) {
|
||||
h := newHarness(t)
|
||||
h.mappings.seedRace(testGameID, testRaceName, "user-1", "uuid-1")
|
||||
|
||||
result, err := h.service.Handle(context.Background(), baseInput())
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, adminbanish.ErrorCodeRuntimeNotFound, result.ErrorCode)
|
||||
}
|
||||
|
||||
func TestHandleForbiddenWhenRaceMissing(t *testing.T) {
|
||||
h := newHarness(t)
|
||||
h.seedRuntime(runtime.StatusRunning)
|
||||
|
||||
result, err := h.service.Handle(context.Background(), baseInput())
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, adminbanish.ErrorCodeForbidden, result.ErrorCode)
|
||||
|
||||
entry, ok := h.logs.lastEntry()
|
||||
require.True(t, ok)
|
||||
assert.Equal(t, operation.OutcomeFailure, entry.Outcome)
|
||||
assert.Equal(t, adminbanish.ErrorCodeForbidden, entry.ErrorCode)
|
||||
}
|
||||
|
||||
func TestHandleEngineUnreachable(t *testing.T) {
|
||||
h := newHarness(t)
|
||||
h.seedRuntime(runtime.StatusRunning)
|
||||
h.mappings.seedRace(testGameID, testRaceName, "user-1", "uuid-1")
|
||||
h.engine.EXPECT().BanishRace(gomock.Any(), testEndpoint, testRaceName).
|
||||
Return(ports.ErrEngineUnreachable)
|
||||
|
||||
result, err := h.service.Handle(context.Background(), baseInput())
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, adminbanish.ErrorCodeEngineUnreachable, result.ErrorCode)
|
||||
}
|
||||
|
||||
func TestHandleEngineValidation(t *testing.T) {
|
||||
h := newHarness(t)
|
||||
h.seedRuntime(runtime.StatusRunning)
|
||||
h.mappings.seedRace(testGameID, testRaceName, "user-1", "uuid-1")
|
||||
h.engine.EXPECT().BanishRace(gomock.Any(), testEndpoint, testRaceName).
|
||||
Return(ports.ErrEngineValidation)
|
||||
|
||||
result, err := h.service.Handle(context.Background(), baseInput())
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, adminbanish.ErrorCodeEngineValidationError, result.ErrorCode)
|
||||
}
|
||||
|
||||
func TestHandleEngineProtocolViolation(t *testing.T) {
|
||||
h := newHarness(t)
|
||||
h.seedRuntime(runtime.StatusRunning)
|
||||
h.mappings.seedRace(testGameID, testRaceName, "user-1", "uuid-1")
|
||||
h.engine.EXPECT().BanishRace(gomock.Any(), testEndpoint, testRaceName).
|
||||
Return(ports.ErrEngineProtocolViolation)
|
||||
|
||||
result, err := h.service.Handle(context.Background(), baseInput())
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, adminbanish.ErrorCodeEngineProtocolViolation, result.ErrorCode)
|
||||
}
|
||||
|
||||
func TestHandleStoreReadFailure(t *testing.T) {
|
||||
h := newHarness(t)
|
||||
h.runtime.getErr = errors.New("connection refused")
|
||||
|
||||
result, err := h.service.Handle(context.Background(), baseInput())
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, adminbanish.ErrorCodeServiceUnavailable, result.ErrorCode)
|
||||
}
|
||||
|
||||
func TestHandleMappingStoreFailure(t *testing.T) {
|
||||
h := newHarness(t)
|
||||
h.seedRuntime(runtime.StatusRunning)
|
||||
h.mappings.getErr = errors.New("connection refused")
|
||||
|
||||
result, err := h.service.Handle(context.Background(), baseInput())
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, adminbanish.ErrorCodeServiceUnavailable, result.ErrorCode)
|
||||
}
|
||||
|
||||
func TestHandleInvalidRequest(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
input adminbanish.Input
|
||||
}{
|
||||
{"empty game id", adminbanish.Input{GameID: "", RaceName: "X", OpSource: operation.OpSourceLobbyInternal}},
|
||||
{"empty race", adminbanish.Input{GameID: testGameID, RaceName: "", OpSource: operation.OpSourceLobbyInternal}},
|
||||
}
|
||||
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, adminbanish.ErrorCodeInvalidRequest, result.ErrorCode)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleNilContextReturnsError(t *testing.T) {
|
||||
h := newHarness(t)
|
||||
_, err := h.service.Handle(nil, baseInput()) //nolint:staticcheck // guard test
|
||||
require.Error(t, err)
|
||||
}
|
||||
|
||||
func TestHandleDefaultsOpSourceToLobbyInternal(t *testing.T) {
|
||||
h := newHarness(t)
|
||||
h.seedRuntime(runtime.StatusRunning)
|
||||
h.mappings.seedRace(testGameID, testRaceName, "user-1", "uuid-1")
|
||||
h.engine.EXPECT().BanishRace(gomock.Any(), testEndpoint, testRaceName).Return(nil)
|
||||
|
||||
input := baseInput()
|
||||
input.OpSource = ""
|
||||
result, err := h.service.Handle(context.Background(), input)
|
||||
require.NoError(t, err)
|
||||
require.True(t, result.IsSuccess())
|
||||
|
||||
entry, ok := h.logs.lastEntry()
|
||||
require.True(t, ok)
|
||||
assert.Equal(t, operation.OpSourceLobbyInternal, entry.OpSource)
|
||||
}
|
||||
Reference in New Issue
Block a user