// 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 }