// Package cancelgame implements the `lobby.game.cancel` message type. It // transitions a game record to `cancelled` from one of the allowed source // statuses (`draft`, `enrollment_open`, `ready_to_start`, `start_failed`) // after enforcing admin-or-owner authorization. Any other source status is // rejected with game.ErrConflict. package cancelgame import ( "context" "errors" "fmt" "log/slog" "time" "galaxy/lobby/internal/domain/common" "galaxy/lobby/internal/domain/game" "galaxy/lobby/internal/logging" "galaxy/lobby/internal/ports" "galaxy/lobby/internal/service/shared" "galaxy/lobby/internal/telemetry" ) // cancellableStatuses enumerates the source statuses from which a game may // transition directly to `cancelled`. The set mirrors the allowed // transitions defined in `internal/domain/game/status.go` and the // PLAN.md exit criteria. var cancellableStatuses = map[game.Status]struct{}{ game.StatusDraft: {}, game.StatusEnrollmentOpen: {}, game.StatusReadyToStart: {}, game.StatusStartFailed: {}, } // Service executes the cancel-game use case. type Service struct { games ports.GameStore clock func() time.Time logger *slog.Logger telemetry *telemetry.Runtime } // Dependencies groups the collaborators used by Service. type Dependencies struct { // Games mediates the CAS status transition and the result read. Games ports.GameStore // Clock supplies the wall-clock used for UpdatedAt. Defaults to // time.Now when nil. Clock func() time.Time // Logger records structured service-level events. Defaults to // slog.Default when nil. Logger *slog.Logger // Telemetry records the `lobby.game.transitions` counter on each // successful cancellation. Optional; nil disables metric emission. Telemetry *telemetry.Runtime } // NewService constructs one Service with deps. func NewService(deps Dependencies) (*Service, error) { if deps.Games == nil { return nil, errors.New("new cancel game service: nil game store") } clock := deps.Clock if clock == nil { clock = time.Now } logger := deps.Logger if logger == nil { logger = slog.Default() } return &Service{ games: deps.Games, clock: clock, logger: logger.With("service", "lobby.cancelgame"), telemetry: deps.Telemetry, }, nil } // Input stores the arguments required to cancel one game. type Input struct { // Actor identifies the caller. Actor shared.Actor // GameID identifies the target game record. GameID common.GameID } // Handle authorizes the actor, checks the source status, transitions the // record to `cancelled`, and returns the post-transition snapshot. func (service *Service) Handle(ctx context.Context, input Input) (game.Game, error) { if service == nil { return game.Game{}, errors.New("cancel game: nil service") } if ctx == nil { return game.Game{}, errors.New("cancel game: nil context") } if err := input.Actor.Validate(); err != nil { return game.Game{}, fmt.Errorf("cancel game: actor: %w", err) } if err := input.GameID.Validate(); err != nil { return game.Game{}, fmt.Errorf("cancel game: %w", err) } record, err := service.games.Get(ctx, input.GameID) if err != nil { return game.Game{}, fmt.Errorf("cancel game: %w", err) } if err := authorize(input.Actor, record); err != nil { return game.Game{}, err } if _, ok := cancellableStatuses[record.Status]; !ok { return game.Game{}, fmt.Errorf( "cancel game: status %q cannot be cancelled: %w", record.Status, game.ErrConflict, ) } at := service.clock().UTC() err = service.games.UpdateStatus(ctx, ports.UpdateStatusInput{ GameID: input.GameID, ExpectedFrom: record.Status, To: game.StatusCancelled, Trigger: game.TriggerCommand, At: at, }) if err != nil { return game.Game{}, fmt.Errorf("cancel game: %w", err) } service.telemetry.RecordGameTransition(ctx, string(record.Status), string(game.StatusCancelled), string(game.TriggerCommand), ) updated, err := service.games.Get(ctx, input.GameID) if err != nil { return game.Game{}, fmt.Errorf("cancel game: %w", err) } logArgs := []any{ "game_id", updated.GameID.String(), "from_status", string(record.Status), "to_status", string(updated.Status), "trigger", string(game.TriggerCommand), "actor_kind", string(input.Actor.Kind), } logArgs = append(logArgs, logging.ContextAttrs(ctx)...) service.logger.InfoContext(ctx, "game cancelled", logArgs...) return updated, nil } // authorize enforces admin OR private-owner access to the record. func authorize(actor shared.Actor, record game.Game) error { if actor.IsAdmin() { return nil } if record.GameType == game.GameTypePrivate && actor.UserID == record.OwnerUserID { return nil } return fmt.Errorf("%w: actor is not authorized to cancel game %q", shared.ErrForbidden, record.GameID.String()) }