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,19 @@
package livenessreply
// Stable error codes returned by Handle as Go-level errors. Liveness
// reply itself never produces a 4xx/5xx response — the endpoint always
// answers 200 — but the service surfaces structural validation
// failures to the handler so it can return the standard error envelope.
const (
// ErrorCodeInvalidRequest reports that the request envelope failed
// structural validation (empty GameID).
ErrorCodeInvalidRequest = "invalid_request"
// 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,114 @@
// Package livenessreply implements the Lobby-facing liveness service-
// layer answer owned by Game Master. It is driven by Game Lobby
// resuming a paused game through
// `GET /api/v1/internal/games/{game_id}/liveness` and reflects GM's
// own view of the runtime without ever calling the engine.
//
// Lifecycle and failure-mode semantics follow `gamemaster/README.md
// §Liveness reply`. The 200 / status="" response on
// `runtime_not_found` is the Stage 17 D5 decision recorded in
// `gamemaster/docs/stage17-admin-operations.md`.
package livenessreply
import (
"context"
"errors"
"fmt"
"log/slog"
"strings"
"galaxy/gamemaster/internal/domain/runtime"
"galaxy/gamemaster/internal/ports"
)
// Input stores the per-call arguments for one liveness reply.
type Input struct {
// GameID identifies the runtime to inspect.
GameID 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")
}
return nil
}
// Result stores the deterministic outcome of one Handle call. The
// endpoint always answers 200; the result fields populate the JSON
// body. ErrorCode / ErrorMessage are reserved for handler-side error
// envelopes and are never set by Handle on a successful read.
type Result struct {
// Ready is true when the runtime exists and is in `running`.
Ready bool
// Status carries the observed runtime status. Empty when the
// runtime record does not exist (Stage 17 D5).
Status runtime.Status
}
// Dependencies groups the collaborators required by Service.
type Dependencies struct {
// RuntimeRecords supplies the runtime status read.
RuntimeRecords ports.RuntimeRecordStore
// Logger records structured service-level events. Defaults to
// `slog.Default()` when nil.
Logger *slog.Logger
}
// Service executes the liveness reply lookup.
type Service struct {
runtimeRecords ports.RuntimeRecordStore
logger *slog.Logger
}
// NewService constructs one Service from deps.
func NewService(deps Dependencies) (*Service, error) {
if deps.RuntimeRecords == nil {
return nil, errors.New("new liveness reply service: nil runtime records")
}
logger := deps.Logger
if logger == nil {
logger = slog.Default()
}
logger = logger.With("service", "gamemaster.livenessreply")
return &Service{
runtimeRecords: deps.RuntimeRecords,
logger: logger,
}, nil
}
// Handle executes one liveness reply lookup. The Go-level error return
// is reserved for non-business failures: nil context, nil receiver,
// invalid input (so the handler can answer `invalid_request`), or a
// store read failure (so the handler can answer `service_unavailable`).
// `runtime.ErrNotFound` is intentionally absorbed into Result with
// `Ready=false` and an empty status.
func (service *Service) Handle(ctx context.Context, input Input) (Result, error) {
if service == nil {
return Result{}, errors.New("liveness reply: nil service")
}
if ctx == nil {
return Result{}, errors.New("liveness reply: nil context")
}
if err := input.Validate(); err != nil {
return Result{}, fmt.Errorf("%s: %w", ErrorCodeInvalidRequest, err)
}
record, err := service.runtimeRecords.Get(ctx, input.GameID)
switch {
case err == nil:
return Result{
Ready: record.Status == runtime.StatusRunning,
Status: record.Status,
}, nil
case errors.Is(err, runtime.ErrNotFound):
return Result{Ready: false, Status: ""}, nil
default:
return Result{}, fmt.Errorf("%s: get runtime record: %w", ErrorCodeServiceUnavailable, err)
}
}
@@ -0,0 +1,175 @@
package livenessreply_test
import (
"context"
"errors"
"sync"
"testing"
"time"
"galaxy/gamemaster/internal/domain/runtime"
"galaxy/gamemaster/internal/ports"
"galaxy/gamemaster/internal/service/livenessreply"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
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")
}
func newService(t *testing.T, store *fakeRuntimeRecords) *livenessreply.Service {
t.Helper()
service, err := livenessreply.NewService(livenessreply.Dependencies{
RuntimeRecords: store,
})
require.NoError(t, err)
return service
}
func runningRecord(gameID string) runtime.RuntimeRecord {
now := time.Date(2026, time.May, 1, 12, 0, 0, 0, time.UTC)
return runtime.RuntimeRecord{
GameID: gameID,
Status: runtime.StatusRunning,
EngineEndpoint: "http://galaxy-game-" + gameID + ":8080",
CurrentImageRef: "ghcr.io/galaxy/game:v1.2.3",
CurrentEngineVersion: "v1.2.3",
TurnSchedule: "0 18 * * *",
CurrentTurn: 5,
CreatedAt: now,
UpdatedAt: now,
}
}
func TestNewServiceRejectsNilRuntimeRecords(t *testing.T) {
_, err := livenessreply.NewService(livenessreply.Dependencies{})
require.Error(t, err)
}
func TestHandleRunningReturnsReadyTrue(t *testing.T) {
store := newFakeRuntimeRecords()
store.seed(runningRecord("game-001"))
service := newService(t, store)
result, err := service.Handle(context.Background(), livenessreply.Input{GameID: "game-001"})
require.NoError(t, err)
assert.True(t, result.Ready)
assert.Equal(t, runtime.StatusRunning, result.Status)
}
func TestHandleNonRunningReturnsReadyFalseWithStatus(t *testing.T) {
cases := []runtime.Status{
runtime.StatusStarting,
runtime.StatusGenerationInProgress,
runtime.StatusGenerationFailed,
runtime.StatusEngineUnreachable,
runtime.StatusStopped,
runtime.StatusFinished,
}
for _, status := range cases {
t.Run(string(status), func(t *testing.T) {
store := newFakeRuntimeRecords()
rec := runningRecord("game-001")
rec.Status = status
store.seed(rec)
service := newService(t, store)
result, err := service.Handle(context.Background(), livenessreply.Input{GameID: "game-001"})
require.NoError(t, err)
assert.False(t, result.Ready)
assert.Equal(t, status, result.Status)
})
}
}
func TestHandleRuntimeNotFoundReturnsEmptyStatus(t *testing.T) {
store := newFakeRuntimeRecords()
service := newService(t, store)
result, err := service.Handle(context.Background(), livenessreply.Input{GameID: "missing"})
require.NoError(t, err, "runtime_not_found is absorbed into 200 response per Stage 17 D5")
assert.False(t, result.Ready)
assert.Equal(t, runtime.Status(""), result.Status)
}
func TestHandleStoreReadFailureReturnsServiceUnavailable(t *testing.T) {
store := newFakeRuntimeRecords()
store.getErr = errors.New("connection refused")
service := newService(t, store)
_, err := service.Handle(context.Background(), livenessreply.Input{GameID: "game-001"})
require.Error(t, err)
assert.Contains(t, err.Error(), livenessreply.ErrorCodeServiceUnavailable)
}
func TestHandleEmptyGameIDReturnsInvalidRequest(t *testing.T) {
store := newFakeRuntimeRecords()
service := newService(t, store)
_, err := service.Handle(context.Background(), livenessreply.Input{GameID: ""})
require.Error(t, err)
assert.Contains(t, err.Error(), livenessreply.ErrorCodeInvalidRequest)
}
func TestHandleNilContextReturnsError(t *testing.T) {
store := newFakeRuntimeRecords()
service := newService(t, store)
_, err := service.Handle(nil, livenessreply.Input{GameID: "game-001"}) //nolint:staticcheck // guard test
require.Error(t, err)
}