feat: game lobby service

This commit is contained in:
Ilia Denisov
2026-04-25 23:20:55 +02:00
committed by GitHub
parent 32dc29359a
commit 48b0056b49
336 changed files with 57074 additions and 1418 deletions
@@ -0,0 +1,170 @@
// 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())
}
@@ -0,0 +1,267 @@
package cancelgame_test
import (
"context"
"io"
"log/slog"
"testing"
"time"
"galaxy/lobby/internal/adapters/gamestub"
"galaxy/lobby/internal/domain/common"
"galaxy/lobby/internal/domain/game"
"galaxy/lobby/internal/ports"
"galaxy/lobby/internal/service/cancelgame"
"galaxy/lobby/internal/service/shared"
"github.com/stretchr/testify/require"
)
func silentLogger() *slog.Logger {
return slog.New(slog.NewTextHandler(io.Discard, nil))
}
func fixedClock(at time.Time) func() time.Time {
return func() time.Time { return at }
}
// seedGameWithStatus persists a fresh game and, when wanted differs from
// `draft`, overwrites the Status field directly via Save. This bypasses
// the transition gate so individual tests can exercise cancel against any
// status the surface must reject or accept.
func seedGameWithStatus(
t *testing.T,
store *gamestub.Store,
id common.GameID,
gameType game.GameType,
ownerUserID string,
status game.Status,
now time.Time,
) game.Game {
t.Helper()
record, err := game.New(game.NewGameInput{
GameID: id,
GameName: "Seed",
GameType: gameType,
OwnerUserID: ownerUserID,
MinPlayers: 2,
MaxPlayers: 4,
StartGapHours: 4,
StartGapPlayers: 1,
EnrollmentEndsAt: now.Add(24 * time.Hour),
TurnSchedule: "0 */6 * * *",
TargetEngineVersion: "1.0.0",
Now: now,
})
require.NoError(t, err)
if status != game.StatusDraft {
record.Status = status
record.UpdatedAt = now.Add(time.Minute)
if status == game.StatusRunning || status == game.StatusPaused ||
status == game.StatusFinished {
startedAt := now.Add(time.Minute)
record.StartedAt = &startedAt
}
if status == game.StatusFinished {
finishedAt := now.Add(2 * time.Minute)
record.FinishedAt = &finishedAt
}
}
require.NoError(t, store.Save(context.Background(), record))
return record
}
func newService(t *testing.T, store ports.GameStore, clock func() time.Time) *cancelgame.Service {
t.Helper()
svc, err := cancelgame.NewService(cancelgame.Dependencies{
Games: store,
Clock: clock,
Logger: silentLogger(),
})
require.NoError(t, err)
return svc
}
func TestHandleFromCancellableStatuses(t *testing.T) {
t.Parallel()
statuses := []game.Status{
game.StatusDraft,
game.StatusEnrollmentOpen,
game.StatusReadyToStart,
game.StatusStartFailed,
}
for _, status := range statuses {
t.Run(string(status), func(t *testing.T) {
t.Parallel()
now := time.Date(2026, 4, 24, 10, 0, 0, 0, time.UTC)
store := gamestub.NewStore()
record := seedGameWithStatus(t, store, "game-a", game.GameTypePublic, "", status, now)
service := newService(t, store, fixedClock(now.Add(time.Hour)))
updated, err := service.Handle(context.Background(), cancelgame.Input{
Actor: shared.NewAdminActor(),
GameID: record.GameID,
})
require.NoError(t, err)
require.Equal(t, game.StatusCancelled, updated.Status)
require.Equal(t, now.Add(time.Hour).UTC(), updated.UpdatedAt)
})
}
}
func TestHandleFromRejectedStatuses(t *testing.T) {
t.Parallel()
statuses := []game.Status{
game.StatusStarting,
game.StatusRunning,
game.StatusPaused,
}
for _, status := range statuses {
t.Run(string(status), func(t *testing.T) {
t.Parallel()
now := time.Date(2026, 4, 24, 10, 0, 0, 0, time.UTC)
store := gamestub.NewStore()
record := seedGameWithStatus(t, store, "game-b", game.GameTypePublic, "", status, now)
service := newService(t, store, fixedClock(now.Add(time.Hour)))
_, err := service.Handle(context.Background(), cancelgame.Input{
Actor: shared.NewAdminActor(),
GameID: record.GameID,
})
require.ErrorIs(t, err, game.ErrConflict)
})
}
}
func TestHandleAlreadyCancelledIsConflict(t *testing.T) {
t.Parallel()
now := time.Date(2026, 4, 24, 10, 0, 0, 0, time.UTC)
store := gamestub.NewStore()
record := seedGameWithStatus(t, store, "game-c", game.GameTypePublic, "", game.StatusCancelled, now)
service := newService(t, store, fixedClock(now.Add(time.Hour)))
_, err := service.Handle(context.Background(), cancelgame.Input{
Actor: shared.NewAdminActor(),
GameID: record.GameID,
})
require.ErrorIs(t, err, game.ErrConflict)
}
func TestHandleFinishedIsConflict(t *testing.T) {
t.Parallel()
now := time.Date(2026, 4, 24, 10, 0, 0, 0, time.UTC)
store := gamestub.NewStore()
record := seedGameWithStatus(t, store, "game-f", game.GameTypePublic, "", game.StatusFinished, now)
service := newService(t, store, fixedClock(now.Add(time.Hour)))
_, err := service.Handle(context.Background(), cancelgame.Input{
Actor: shared.NewAdminActor(),
GameID: record.GameID,
})
require.ErrorIs(t, err, game.ErrConflict)
}
func TestHandleOwnerCancelsPrivate(t *testing.T) {
t.Parallel()
now := time.Date(2026, 4, 24, 10, 0, 0, 0, time.UTC)
store := gamestub.NewStore()
record := seedGameWithStatus(t, store, "game-priv", game.GameTypePrivate, "user-1", game.StatusEnrollmentOpen, now)
service := newService(t, store, fixedClock(now.Add(time.Hour)))
updated, err := service.Handle(context.Background(), cancelgame.Input{
Actor: shared.NewUserActor("user-1"),
GameID: record.GameID,
})
require.NoError(t, err)
require.Equal(t, game.StatusCancelled, updated.Status)
}
func TestHandleNonOwnerForbidden(t *testing.T) {
t.Parallel()
now := time.Date(2026, 4, 24, 10, 0, 0, 0, time.UTC)
store := gamestub.NewStore()
record := seedGameWithStatus(t, store, "game-priv", game.GameTypePrivate, "user-1", game.StatusEnrollmentOpen, now)
service := newService(t, store, fixedClock(now.Add(time.Hour)))
_, err := service.Handle(context.Background(), cancelgame.Input{
Actor: shared.NewUserActor("user-2"),
GameID: record.GameID,
})
require.ErrorIs(t, err, shared.ErrForbidden)
}
func TestHandleUserCannotCancelPublic(t *testing.T) {
t.Parallel()
now := time.Date(2026, 4, 24, 10, 0, 0, 0, time.UTC)
store := gamestub.NewStore()
record := seedGameWithStatus(t, store, "game-pub", game.GameTypePublic, "", game.StatusEnrollmentOpen, now)
service := newService(t, store, fixedClock(now.Add(time.Hour)))
_, err := service.Handle(context.Background(), cancelgame.Input{
Actor: shared.NewUserActor("user-1"),
GameID: record.GameID,
})
require.ErrorIs(t, err, shared.ErrForbidden)
}
func TestHandleNotFound(t *testing.T) {
t.Parallel()
store := gamestub.NewStore()
service := newService(t, store, fixedClock(time.Date(2026, 4, 24, 10, 0, 0, 0, time.UTC)))
_, err := service.Handle(context.Background(), cancelgame.Input{
Actor: shared.NewAdminActor(),
GameID: "game-missing",
})
require.ErrorIs(t, err, game.ErrNotFound)
}
func TestHandleInvalidActor(t *testing.T) {
t.Parallel()
store := gamestub.NewStore()
service := newService(t, store, fixedClock(time.Date(2026, 4, 24, 10, 0, 0, 0, time.UTC)))
_, err := service.Handle(context.Background(), cancelgame.Input{
Actor: shared.Actor{Kind: shared.ActorKindUser},
GameID: "game-x",
})
require.Error(t, err)
require.Contains(t, err.Error(), "actor")
}
func TestHandleInvalidGameID(t *testing.T) {
t.Parallel()
store := gamestub.NewStore()
service := newService(t, store, fixedClock(time.Date(2026, 4, 24, 10, 0, 0, 0, time.UTC)))
_, err := service.Handle(context.Background(), cancelgame.Input{
Actor: shared.NewAdminActor(),
GameID: "bad",
})
require.Error(t, err)
}