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,45 @@
package adminpatch
// 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/Version, malformed semver).
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 is not in
// `running`. Patch is supported only for runtimes RTM can recreate
// in place.
ErrorCodeRuntimeNotRunning = "runtime_not_running"
// ErrorCodeEngineVersionNotFound reports that the requested target
// version is missing from the engine_versions registry, or that it
// is present but `status=deprecated`.
ErrorCodeEngineVersionNotFound = "engine_version_not_found"
// ErrorCodeSemverPatchOnly reports that the requested target
// version differs in major or minor from the current one. Patch
// upgrades are constrained to same-major.minor.
ErrorCodeSemverPatchOnly = "semver_patch_only"
// ErrorCodeConflict reports that the runtime's status changed
// concurrently between the lookup and the post-RTM image rotation
// CAS.
ErrorCodeConflict = "conflict"
// ErrorCodeServiceUnavailable reports that a steady-state
// dependency (PostgreSQL, Runtime Manager) 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,375 @@
// Package adminpatch implements the admin patch service-layer
// orchestrator owned by Game Master. It is driven by Admin Service or
// system administrators through
// `POST /api/v1/internal/runtimes/{game_id}/patch` and tells Runtime
// Manager to recreate the engine container with a new image, then
// rotates `runtime_records.current_image_ref` and
// `runtime_records.current_engine_version` while keeping the runtime in
// `running`.
//
// Lifecycle and failure-mode semantics follow `gamemaster/README.md
// §Lifecycles → Patch`. Design rationale (the dedicated UpdateImage
// port, rejection of deprecated targets, `service_unavailable` mapping
// for RTM failures) is captured in
// `gamemaster/docs/stage17-admin-operations.md`.
package adminpatch
import (
"context"
"errors"
"fmt"
"log/slog"
"strings"
"time"
"galaxy/gamemaster/internal/domain/engineversion"
"galaxy/gamemaster/internal/domain/operation"
"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 patch operation.
type Input struct {
// GameID identifies the runtime to patch.
GameID string
// Version stores the target engine version (semver). Must be
// present in `engine_versions` with `status=active` and a same
// major.minor as the runtime's current version.
Version string
// OpSource classifies how the request entered Game Master. Used to
// stamp `operation_log.op_source`. Defaults to `admin_rest` when
// missing or unrecognised.
OpSource operation.OpSource
// SourceRef stores the optional opaque per-source reference (REST
// request id, admin user 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 _, err := engineversion.ParseSemver(input.Version); err != nil {
return fmt.Errorf("version: %w", err)
}
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 {
// Record carries the post-rotation runtime record. Populated on
// success; zero on early-rejection failures.
Record runtime.RuntimeRecord
// 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 drives the row read plus the post-RTM image
// rotation under a CAS guard.
RuntimeRecords ports.RuntimeRecordStore
// EngineVersions resolves the target version's image ref and
// status.
EngineVersions ports.EngineVersionStore
// OperationLogs records the audit entry.
OperationLogs ports.OperationLogStore
// RTM drives the Runtime Manager patch call.
RTM ports.RTMClient
// Telemetry is required by the audit/log path. The Stage 17
// service does not introduce a dedicated counter; outcome metrics
// land under the future Admin Service surface.
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 patch lifecycle operation.
type Service struct {
runtimeRecords ports.RuntimeRecordStore
engineVersions ports.EngineVersionStore
operationLogs ports.OperationLogStore
rtm ports.RTMClient
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 patch service: nil runtime records")
case deps.EngineVersions == nil:
return nil, errors.New("new admin patch service: nil engine versions")
case deps.OperationLogs == nil:
return nil, errors.New("new admin patch service: nil operation logs")
case deps.RTM == nil:
return nil, errors.New("new admin patch service: nil rtm client")
case deps.Telemetry == nil:
return nil, errors.New("new admin patch 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.adminpatch")
return &Service{
runtimeRecords: deps.RuntimeRecords,
engineVersions: deps.EngineVersions,
operationLogs: deps.OperationLogs,
rtm: deps.RTM,
telemetry: deps.Telemetry,
logger: logger,
clock: clock,
}, nil
}
// Handle executes one admin patch 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 patch: nil service")
}
if ctx == nil {
return Result{}, errors.New("admin patch: 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 record.Status != runtime.StatusRunning {
return service.recordFailure(ctx, opStartedAt, input,
ErrorCodeRuntimeNotRunning,
fmt.Sprintf("runtime status is %q, expected %q",
record.Status, runtime.StatusRunning)), nil
}
target, err := service.engineVersions.Get(ctx, input.Version)
switch {
case errors.Is(err, engineversion.ErrNotFound):
return service.recordFailure(ctx, opStartedAt, input,
ErrorCodeEngineVersionNotFound,
fmt.Sprintf("engine version %q not found", input.Version)), nil
case err != nil:
return service.recordFailure(ctx, opStartedAt, input,
ErrorCodeServiceUnavailable, fmt.Sprintf("get engine version: %s", err.Error())), nil
}
if target.Status != engineversion.StatusActive {
return service.recordFailure(ctx, opStartedAt, input,
ErrorCodeEngineVersionNotFound,
fmt.Sprintf("engine version %q is %q, expected %q",
input.Version, target.Status, engineversion.StatusActive)), nil
}
patchOK, semErr := engineversion.IsPatchUpgrade(record.CurrentEngineVersion, input.Version)
if semErr != nil {
return service.recordFailure(ctx, opStartedAt, input,
ErrorCodeInvalidRequest, fmt.Sprintf("compare semver: %s", semErr.Error())), nil
}
if !patchOK {
return service.recordFailure(ctx, opStartedAt, input,
ErrorCodeSemverPatchOnly,
fmt.Sprintf("target %q is not a same-major.minor patch of %q",
input.Version, record.CurrentEngineVersion)), nil
}
if err := service.rtm.Patch(ctx, input.GameID, target.ImageRef); err != nil {
return service.recordFailure(ctx, opStartedAt, input,
ErrorCodeServiceUnavailable, fmt.Sprintf("rtm patch: %s", err.Error())), nil
}
rotatedAt := service.clock().UTC()
updateErr := service.runtimeRecords.UpdateImage(ctx, ports.UpdateImageInput{
GameID: input.GameID,
ExpectedStatus: runtime.StatusRunning,
CurrentImageRef: target.ImageRef,
CurrentEngineVersion: input.Version,
Now: rotatedAt,
})
switch {
case updateErr == nil:
case errors.Is(updateErr, runtime.ErrConflict):
return service.recordFailure(ctx, opStartedAt, input,
ErrorCodeConflict,
fmt.Sprintf("runtime status changed during patch: %s", updateErr.Error())), nil
case errors.Is(updateErr, runtime.ErrNotFound):
return service.recordFailure(ctx, opStartedAt, input,
ErrorCodeRuntimeNotFound,
fmt.Sprintf("runtime record disappeared during patch: %s", updateErr.Error())), nil
default:
return service.recordFailure(ctx, opStartedAt, input,
ErrorCodeServiceUnavailable,
fmt.Sprintf("update runtime image: %s", updateErr.Error())), nil
}
persisted, reloadErr := service.runtimeRecords.Get(ctx, input.GameID)
if reloadErr != nil {
// The image rotation already committed; surface the success
// outcome with the in-memory projection so the caller still
// sees the new image_ref / engine_version.
service.logger.WarnContext(ctx, "reload runtime record after patch",
"game_id", input.GameID,
"err", reloadErr.Error(),
)
persisted = record
persisted.CurrentImageRef = target.ImageRef
persisted.CurrentEngineVersion = input.Version
persisted.UpdatedAt = rotatedAt
}
service.appendSuccessLog(ctx, opStartedAt, input)
logArgs := []any{
"game_id", input.GameID,
"new_image_ref", target.ImageRef,
"new_engine_version", input.Version,
"previous_engine_version", record.CurrentEngineVersion,
"op_source", string(fallbackOpSource(input.OpSource)),
}
logArgs = append(logArgs, logging.ContextAttrs(ctx)...)
service.logger.InfoContext(ctx, "runtime patched", logArgs...)
return Result{
Record: persisted,
Outcome: operation.OutcomeSuccess,
}, nil
}
// recordFailure assembles the failure Result, appends the
// operation_log failure entry, 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)
logArgs := []any{
"game_id", input.GameID,
"target_version", input.Version,
"op_source", string(input.OpSource),
"error_code", errorCode,
"error_message", errorMessage,
}
logArgs = append(logArgs, logging.ContextAttrs(ctx)...)
service.logger.WarnContext(ctx, "admin patch rejected", logArgs...)
return Result{
Outcome: operation.OutcomeFailure,
ErrorCode: errorCode,
ErrorMessage: errorMessage,
}
}
// 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.OpKindPatch,
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.OpKindPatch,
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 runtime row is 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 `admin_rest` when the caller did not
// supply a known op source. Mirrors `gamemaster/README.md §Trusted
// Surfaces`.
func fallbackOpSource(source operation.OpSource) operation.OpSource {
if source.IsKnown() {
return source
}
return operation.OpSourceAdminRest
}
@@ -0,0 +1,448 @@
package adminpatch_test
import (
"context"
"errors"
"sync"
"testing"
"time"
"galaxy/gamemaster/internal/adapters/mocks"
"galaxy/gamemaster/internal/domain/engineversion"
"galaxy/gamemaster/internal/domain/operation"
"galaxy/gamemaster/internal/domain/runtime"
"galaxy/gamemaster/internal/ports"
"galaxy/gamemaster/internal/service/adminpatch"
"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
imgErr error
images []ports.UpdateImageInput
}
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, input ports.UpdateImageInput) error {
s.mu.Lock()
defer s.mu.Unlock()
if s.imgErr != nil {
s.images = append(s.images, input)
return s.imgErr
}
record, ok := s.stored[input.GameID]
if !ok {
s.images = append(s.images, input)
return runtime.ErrNotFound
}
if record.Status != input.ExpectedStatus {
s.images = append(s.images, input)
return runtime.ErrConflict
}
record.CurrentImageRef = input.CurrentImageRef
record.CurrentEngineVersion = input.CurrentEngineVersion
record.UpdatedAt = input.Now
s.stored[input.GameID] = record
s.images = append(s.images, input)
return nil
}
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 fakeEngineVersions struct {
mu sync.Mutex
versions map[string]engineversion.EngineVersion
getErr error
}
func newFakeEngineVersions() *fakeEngineVersions {
return &fakeEngineVersions{versions: map[string]engineversion.EngineVersion{}}
}
func (s *fakeEngineVersions) seed(record engineversion.EngineVersion) {
s.mu.Lock()
defer s.mu.Unlock()
s.versions[record.Version] = record
}
func (s *fakeEngineVersions) Get(_ context.Context, version string) (engineversion.EngineVersion, error) {
s.mu.Lock()
defer s.mu.Unlock()
if s.getErr != nil {
return engineversion.EngineVersion{}, s.getErr
}
rec, ok := s.versions[version]
if !ok {
return engineversion.EngineVersion{}, engineversion.ErrNotFound
}
return rec, nil
}
func (s *fakeEngineVersions) List(context.Context, *engineversion.Status) ([]engineversion.EngineVersion, error) {
return nil, errors.New("not used")
}
func (s *fakeEngineVersions) Insert(context.Context, engineversion.EngineVersion) error {
return errors.New("not used")
}
func (s *fakeEngineVersions) Update(context.Context, ports.UpdateEngineVersionInput) error {
return errors.New("not used")
}
func (s *fakeEngineVersions) Deprecate(context.Context, string, time.Time) error {
return errors.New("not used")
}
func (s *fakeEngineVersions) Delete(context.Context, string) error {
return errors.New("not used")
}
func (s *fakeEngineVersions) IsReferencedByActiveRuntime(context.Context, string) (bool, error) {
return false, 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
}
func (s *fakeOperationLogs) snapshot() []operation.OperationEntry {
s.mu.Lock()
defer s.mu.Unlock()
out := make([]operation.OperationEntry, len(s.entries))
copy(out, s.entries)
return out
}
// --- harness ----------------------------------------------------------
type harness struct {
t *testing.T
ctrl *gomock.Controller
runtime *fakeRuntimeRecords
versions *fakeEngineVersions
logs *fakeOperationLogs
rtm *mocks.MockRTMClient
telemetry *telemetry.Runtime
now time.Time
service *adminpatch.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(),
versions: newFakeEngineVersions(),
logs: &fakeOperationLogs{},
rtm: mocks.NewMockRTMClient(ctrl),
telemetry: telemetryRuntime,
now: time.Date(2026, time.May, 1, 12, 0, 0, 0, time.UTC),
}
service, err := adminpatch.NewService(adminpatch.Dependencies{
RuntimeRecords: h.runtime,
EngineVersions: h.versions,
OperationLogs: h.logs,
RTM: h.rtm,
Telemetry: h.telemetry,
Clock: func() time.Time { return h.now },
})
require.NoError(t, err)
h.service = service
return h
}
func (h *harness) seedRunningOnVersion(version, image string) runtime.RuntimeRecord {
created := h.now.Add(-time.Hour)
started := h.now.Add(-30 * time.Minute)
next := h.now.Add(30 * time.Minute)
record := runtime.RuntimeRecord{
GameID: "game-001",
Status: runtime.StatusRunning,
EngineEndpoint: "http://galaxy-game-game-001:8080",
CurrentImageRef: image,
CurrentEngineVersion: version,
TurnSchedule: "0 18 * * *",
CurrentTurn: 7,
NextGenerationAt: &next,
EngineHealth: "healthy",
CreatedAt: created,
UpdatedAt: started,
StartedAt: &started,
}
h.runtime.seed(record)
return record
}
func (h *harness) seedTarget(version, image string, status engineversion.Status) {
h.versions.seed(engineversion.EngineVersion{
Version: version,
ImageRef: image,
Status: status,
CreatedAt: h.now.Add(-24 * time.Hour),
UpdatedAt: h.now.Add(-24 * time.Hour),
})
}
func baseInput(version string) adminpatch.Input {
return adminpatch.Input{
GameID: "game-001",
Version: version,
OpSource: operation.OpSourceAdminRest,
SourceRef: "req-patch-001",
}
}
// --- tests ------------------------------------------------------------
func TestNewServiceRejectsMissingDeps(t *testing.T) {
telemetryRuntime, err := telemetry.NewWithProviders(nil, nil)
require.NoError(t, err)
cases := []struct {
name string
mut func(*adminpatch.Dependencies)
}{
{"runtime records", func(d *adminpatch.Dependencies) { d.RuntimeRecords = nil }},
{"engine versions", func(d *adminpatch.Dependencies) { d.EngineVersions = nil }},
{"operation logs", func(d *adminpatch.Dependencies) { d.OperationLogs = nil }},
{"rtm", func(d *adminpatch.Dependencies) { d.RTM = nil }},
{"telemetry", func(d *adminpatch.Dependencies) { d.Telemetry = nil }},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
ctrl := gomock.NewController(t)
deps := adminpatch.Dependencies{
RuntimeRecords: newFakeRuntimeRecords(),
EngineVersions: newFakeEngineVersions(),
OperationLogs: &fakeOperationLogs{},
RTM: mocks.NewMockRTMClient(ctrl),
Telemetry: telemetryRuntime,
}
tc.mut(&deps)
service, err := adminpatch.NewService(deps)
require.Error(t, err)
require.Nil(t, service)
})
}
}
func TestHandleHappyPathRotatesImage(t *testing.T) {
h := newHarness(t)
h.seedRunningOnVersion("v1.2.3", "ghcr.io/galaxy/game:v1.2.3")
h.seedTarget("v1.2.4", "ghcr.io/galaxy/game:v1.2.4", engineversion.StatusActive)
h.rtm.EXPECT().Patch(gomock.Any(), "game-001", "ghcr.io/galaxy/game:v1.2.4").Return(nil)
result, err := h.service.Handle(context.Background(), baseInput("v1.2.4"))
require.NoError(t, err)
require.True(t, result.IsSuccess(), "want success, got %+v", result)
assert.Equal(t, "ghcr.io/galaxy/game:v1.2.4", result.Record.CurrentImageRef)
assert.Equal(t, "v1.2.4", result.Record.CurrentEngineVersion)
assert.Equal(t, runtime.StatusRunning, result.Record.Status)
require.Len(t, h.runtime.images, 1)
assert.Equal(t, runtime.StatusRunning, h.runtime.images[0].ExpectedStatus)
assert.Equal(t, "ghcr.io/galaxy/game:v1.2.4", h.runtime.images[0].CurrentImageRef)
assert.Equal(t, "v1.2.4", h.runtime.images[0].CurrentEngineVersion)
entry, ok := h.logs.lastEntry()
require.True(t, ok)
assert.Equal(t, operation.OpKindPatch, entry.OpKind)
assert.Equal(t, operation.OutcomeSuccess, entry.Outcome)
}
func TestHandleRuntimeNotFound(t *testing.T) {
h := newHarness(t)
h.seedTarget("v1.2.4", "ghcr.io/galaxy/game:v1.2.4", engineversion.StatusActive)
result, err := h.service.Handle(context.Background(), baseInput("v1.2.4"))
require.NoError(t, err)
assert.Equal(t, adminpatch.ErrorCodeRuntimeNotFound, result.ErrorCode)
}
func TestHandleRuntimeNotRunning(t *testing.T) {
h := newHarness(t)
rec := h.seedRunningOnVersion("v1.2.3", "ghcr.io/galaxy/game:v1.2.3")
rec.Status = runtime.StatusStopped
h.runtime.seed(rec)
h.seedTarget("v1.2.4", "ghcr.io/galaxy/game:v1.2.4", engineversion.StatusActive)
result, err := h.service.Handle(context.Background(), baseInput("v1.2.4"))
require.NoError(t, err)
assert.Equal(t, adminpatch.ErrorCodeRuntimeNotRunning, result.ErrorCode)
assert.Empty(t, h.runtime.images, "no UpdateImage when status precondition fails")
}
func TestHandleEngineVersionMissing(t *testing.T) {
h := newHarness(t)
h.seedRunningOnVersion("v1.2.3", "ghcr.io/galaxy/game:v1.2.3")
result, err := h.service.Handle(context.Background(), baseInput("v1.2.4"))
require.NoError(t, err)
assert.Equal(t, adminpatch.ErrorCodeEngineVersionNotFound, result.ErrorCode)
}
func TestHandleEngineVersionDeprecated(t *testing.T) {
h := newHarness(t)
h.seedRunningOnVersion("v1.2.3", "ghcr.io/galaxy/game:v1.2.3")
h.seedTarget("v1.2.4", "ghcr.io/galaxy/game:v1.2.4", engineversion.StatusDeprecated)
result, err := h.service.Handle(context.Background(), baseInput("v1.2.4"))
require.NoError(t, err)
assert.Equal(t, adminpatch.ErrorCodeEngineVersionNotFound, result.ErrorCode)
assert.Contains(t, result.ErrorMessage, "deprecated")
}
func TestHandleSemverPatchOnlyMajor(t *testing.T) {
h := newHarness(t)
h.seedRunningOnVersion("v1.2.3", "ghcr.io/galaxy/game:v1.2.3")
h.seedTarget("v2.0.0", "ghcr.io/galaxy/game:v2.0.0", engineversion.StatusActive)
result, err := h.service.Handle(context.Background(), baseInput("v2.0.0"))
require.NoError(t, err)
assert.Equal(t, adminpatch.ErrorCodeSemverPatchOnly, result.ErrorCode)
assert.Empty(t, h.runtime.images)
}
func TestHandleSemverPatchOnlyMinor(t *testing.T) {
h := newHarness(t)
h.seedRunningOnVersion("v1.2.3", "ghcr.io/galaxy/game:v1.2.3")
h.seedTarget("v1.3.0", "ghcr.io/galaxy/game:v1.3.0", engineversion.StatusActive)
result, err := h.service.Handle(context.Background(), baseInput("v1.3.0"))
require.NoError(t, err)
assert.Equal(t, adminpatch.ErrorCodeSemverPatchOnly, result.ErrorCode)
}
func TestHandleRTMUnavailable(t *testing.T) {
h := newHarness(t)
h.seedRunningOnVersion("v1.2.3", "ghcr.io/galaxy/game:v1.2.3")
h.seedTarget("v1.2.4", "ghcr.io/galaxy/game:v1.2.4", engineversion.StatusActive)
h.rtm.EXPECT().Patch(gomock.Any(), "game-001", "ghcr.io/galaxy/game:v1.2.4").
Return(ports.ErrRTMUnavailable)
result, err := h.service.Handle(context.Background(), baseInput("v1.2.4"))
require.NoError(t, err)
assert.Equal(t, adminpatch.ErrorCodeServiceUnavailable, result.ErrorCode)
assert.Empty(t, h.runtime.images, "no UpdateImage when RTM fails")
}
func TestHandleCASLostAfterRTM(t *testing.T) {
h := newHarness(t)
h.seedRunningOnVersion("v1.2.3", "ghcr.io/galaxy/game:v1.2.3")
h.seedTarget("v1.2.4", "ghcr.io/galaxy/game:v1.2.4", engineversion.StatusActive)
h.rtm.EXPECT().Patch(gomock.Any(), "game-001", "ghcr.io/galaxy/game:v1.2.4").Return(nil)
h.runtime.imgErr = runtime.ErrConflict
result, err := h.service.Handle(context.Background(), baseInput("v1.2.4"))
require.NoError(t, err)
assert.Equal(t, adminpatch.ErrorCodeConflict, result.ErrorCode)
require.Len(t, h.runtime.images, 1)
}
func TestHandleInvalidRequest(t *testing.T) {
cases := []struct {
name string
input adminpatch.Input
}{
{"empty game id", adminpatch.Input{GameID: "", Version: "v1.2.4", OpSource: operation.OpSourceAdminRest}},
{"malformed version", adminpatch.Input{GameID: "game-001", Version: "not-a-semver", OpSource: operation.OpSourceAdminRest}},
}
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, adminpatch.ErrorCodeInvalidRequest, result.ErrorCode)
})
}
}
func TestHandleNilContextReturnsError(t *testing.T) {
h := newHarness(t)
_, err := h.service.Handle(nil, baseInput("v1.2.4")) //nolint:staticcheck // guard test
require.Error(t, err)
}
func TestHandleStoreReadFailure(t *testing.T) {
h := newHarness(t)
h.runtime.getErr = errors.New("connection refused")
result, err := h.service.Handle(context.Background(), baseInput("v1.2.4"))
require.NoError(t, err)
assert.Equal(t, adminpatch.ErrorCodeServiceUnavailable, result.ErrorCode)
}