feat: game lobby service
This commit is contained in:
@@ -0,0 +1,175 @@
|
||||
// Package resumegame implements the `lobby.game.resume` message type.
|
||||
// It transitions a `paused` game back to `running` after enforcing
|
||||
// admin-or-owner authorization and a synchronous Game Master liveness
|
||||
// probe. When Game Master is unreachable the game stays `paused` and
|
||||
// the caller receives `service_unavailable`.
|
||||
package resumegame
|
||||
|
||||
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"
|
||||
)
|
||||
|
||||
// Service executes the resume-game use case.
|
||||
type Service struct {
|
||||
games ports.GameStore
|
||||
gm ports.GMClient
|
||||
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
|
||||
|
||||
// GM is the synchronous Game Master client used for the liveness
|
||||
// probe issued before the status transition.
|
||||
GM ports.GMClient
|
||||
|
||||
// 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 resume. Optional; nil disables metric emission.
|
||||
Telemetry *telemetry.Runtime
|
||||
}
|
||||
|
||||
// NewService constructs one Service with deps.
|
||||
func NewService(deps Dependencies) (*Service, error) {
|
||||
switch {
|
||||
case deps.Games == nil:
|
||||
return nil, errors.New("new resume game service: nil game store")
|
||||
case deps.GM == nil:
|
||||
return nil, errors.New("new resume game service: nil gm client")
|
||||
}
|
||||
|
||||
clock := deps.Clock
|
||||
if clock == nil {
|
||||
clock = time.Now
|
||||
}
|
||||
logger := deps.Logger
|
||||
if logger == nil {
|
||||
logger = slog.Default()
|
||||
}
|
||||
|
||||
return &Service{
|
||||
games: deps.Games,
|
||||
gm: deps.GM,
|
||||
clock: clock,
|
||||
logger: logger.With("service", "lobby.resumegame"),
|
||||
telemetry: deps.Telemetry,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Input stores the arguments required to resume 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, asserts the source status is `paused`,
|
||||
// pings Game Master, and on a healthy probe transitions the record to
|
||||
// `running`. A failed probe returns shared.ErrServiceUnavailable
|
||||
// without mutating the record so the game stays `paused`.
|
||||
func (service *Service) Handle(ctx context.Context, input Input) (game.Game, error) {
|
||||
if service == nil {
|
||||
return game.Game{}, errors.New("resume game: nil service")
|
||||
}
|
||||
if ctx == nil {
|
||||
return game.Game{}, errors.New("resume game: nil context")
|
||||
}
|
||||
if err := input.Actor.Validate(); err != nil {
|
||||
return game.Game{}, fmt.Errorf("resume game: actor: %w", err)
|
||||
}
|
||||
if err := input.GameID.Validate(); err != nil {
|
||||
return game.Game{}, fmt.Errorf("resume game: %w", err)
|
||||
}
|
||||
|
||||
record, err := service.games.Get(ctx, input.GameID)
|
||||
if err != nil {
|
||||
return game.Game{}, fmt.Errorf("resume game: %w", err)
|
||||
}
|
||||
if err := authorize(input.Actor, record); err != nil {
|
||||
return game.Game{}, err
|
||||
}
|
||||
if record.Status != game.StatusPaused {
|
||||
return game.Game{}, fmt.Errorf(
|
||||
"resume game: status %q is not %q: %w",
|
||||
record.Status, game.StatusPaused, game.ErrConflict,
|
||||
)
|
||||
}
|
||||
|
||||
if err := service.gm.Ping(ctx); err != nil {
|
||||
service.logger.WarnContext(ctx, "resume game: game master unavailable",
|
||||
"game_id", input.GameID.String(),
|
||||
"err", err.Error(),
|
||||
)
|
||||
return game.Game{}, fmt.Errorf("resume game: %w",
|
||||
errors.Join(shared.ErrServiceUnavailable, err))
|
||||
}
|
||||
|
||||
at := service.clock().UTC()
|
||||
if err := service.games.UpdateStatus(ctx, ports.UpdateStatusInput{
|
||||
GameID: input.GameID,
|
||||
ExpectedFrom: game.StatusPaused,
|
||||
To: game.StatusRunning,
|
||||
Trigger: game.TriggerCommand,
|
||||
At: at,
|
||||
}); err != nil {
|
||||
return game.Game{}, fmt.Errorf("resume game: %w", err)
|
||||
}
|
||||
|
||||
service.telemetry.RecordGameTransition(ctx,
|
||||
string(game.StatusPaused),
|
||||
string(game.StatusRunning),
|
||||
string(game.TriggerCommand),
|
||||
)
|
||||
|
||||
updated, err := service.games.Get(ctx, input.GameID)
|
||||
if err != nil {
|
||||
return game.Game{}, fmt.Errorf("resume game: %w", err)
|
||||
}
|
||||
|
||||
logArgs := []any{
|
||||
"game_id", updated.GameID.String(),
|
||||
"from_status", string(game.StatusPaused),
|
||||
"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 resumed", 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 resume game %q",
|
||||
shared.ErrForbidden, record.GameID.String())
|
||||
}
|
||||
@@ -0,0 +1,284 @@
|
||||
package resumegame_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"log/slog"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"galaxy/lobby/internal/adapters/gamestub"
|
||||
"galaxy/lobby/internal/adapters/gmclientstub"
|
||||
"galaxy/lobby/internal/domain/common"
|
||||
"galaxy/lobby/internal/domain/game"
|
||||
"galaxy/lobby/internal/ports"
|
||||
"galaxy/lobby/internal/service/resumegame"
|
||||
"galaxy/lobby/internal/service/shared"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"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 overrides Status to the
|
||||
// requested value so individual tests can exercise resume against any
|
||||
// source status.
|
||||
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: "test resume game",
|
||||
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,
|
||||
gm ports.GMClient,
|
||||
clock func() time.Time,
|
||||
) *resumegame.Service {
|
||||
t.Helper()
|
||||
|
||||
svc, err := resumegame.NewService(resumegame.Dependencies{
|
||||
Games: store,
|
||||
GM: gm,
|
||||
Clock: clock,
|
||||
Logger: silentLogger(),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
return svc
|
||||
}
|
||||
|
||||
func TestNewServiceRejectsMissingDeps(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
_, err := resumegame.NewService(resumegame.Dependencies{})
|
||||
require.Error(t, err)
|
||||
|
||||
_, err = resumegame.NewService(resumegame.Dependencies{Games: gamestub.NewStore()})
|
||||
require.Error(t, err)
|
||||
}
|
||||
|
||||
func TestResumeGameAdminHappyPath(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
now := time.Date(2026, 4, 25, 12, 0, 0, 0, time.UTC)
|
||||
store := gamestub.NewStore()
|
||||
record := seedGameWithStatus(t, store, "game-pub", game.GameTypePublic, "", game.StatusPaused, now)
|
||||
|
||||
gm := gmclientstub.NewClient()
|
||||
service := newService(t, store, gm, fixedClock(now.Add(time.Hour)))
|
||||
|
||||
updated, err := service.Handle(context.Background(), resumegame.Input{
|
||||
Actor: shared.NewAdminActor(),
|
||||
GameID: record.GameID,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, game.StatusRunning, updated.Status)
|
||||
assert.Equal(t, 1, gm.PingCalls())
|
||||
}
|
||||
|
||||
func TestResumeGamePrivateOwnerHappyPath(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
now := time.Date(2026, 4, 25, 12, 0, 0, 0, time.UTC)
|
||||
store := gamestub.NewStore()
|
||||
record := seedGameWithStatus(t, store, "game-priv", game.GameTypePrivate, "user-owner", game.StatusPaused, now)
|
||||
|
||||
gm := gmclientstub.NewClient()
|
||||
service := newService(t, store, gm, fixedClock(now.Add(time.Hour)))
|
||||
|
||||
updated, err := service.Handle(context.Background(), resumegame.Input{
|
||||
Actor: shared.NewUserActor("user-owner"),
|
||||
GameID: record.GameID,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, game.StatusRunning, updated.Status)
|
||||
assert.Equal(t, 1, gm.PingCalls())
|
||||
}
|
||||
|
||||
func TestResumeGameRejectsNonOwnerUser(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
now := time.Date(2026, 4, 25, 12, 0, 0, 0, time.UTC)
|
||||
store := gamestub.NewStore()
|
||||
record := seedGameWithStatus(t, store, "game-priv", game.GameTypePrivate, "user-owner", game.StatusPaused, now)
|
||||
|
||||
gm := gmclientstub.NewClient()
|
||||
service := newService(t, store, gm, fixedClock(now.Add(time.Hour)))
|
||||
|
||||
_, err := service.Handle(context.Background(), resumegame.Input{
|
||||
Actor: shared.NewUserActor("user-other"),
|
||||
GameID: record.GameID,
|
||||
})
|
||||
require.ErrorIs(t, err, shared.ErrForbidden)
|
||||
assert.Equal(t, 0, gm.PingCalls(), "ping must not run before authorization passes")
|
||||
}
|
||||
|
||||
func TestResumeGameRejectsUserActorOnPublicGame(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
now := time.Date(2026, 4, 25, 12, 0, 0, 0, time.UTC)
|
||||
store := gamestub.NewStore()
|
||||
record := seedGameWithStatus(t, store, "game-pub", game.GameTypePublic, "", game.StatusPaused, now)
|
||||
|
||||
gm := gmclientstub.NewClient()
|
||||
service := newService(t, store, gm, fixedClock(now.Add(time.Hour)))
|
||||
|
||||
_, err := service.Handle(context.Background(), resumegame.Input{
|
||||
Actor: shared.NewUserActor("user-x"),
|
||||
GameID: record.GameID,
|
||||
})
|
||||
require.ErrorIs(t, err, shared.ErrForbidden)
|
||||
assert.Equal(t, 0, gm.PingCalls())
|
||||
}
|
||||
|
||||
func TestResumeGameRejectsWrongStatuses(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
statuses := []game.Status{
|
||||
game.StatusDraft,
|
||||
game.StatusEnrollmentOpen,
|
||||
game.StatusReadyToStart,
|
||||
game.StatusStarting,
|
||||
game.StatusStartFailed,
|
||||
game.StatusRunning,
|
||||
game.StatusFinished,
|
||||
game.StatusCancelled,
|
||||
}
|
||||
|
||||
for _, status := range statuses {
|
||||
t.Run(string(status), func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
now := time.Date(2026, 4, 25, 12, 0, 0, 0, time.UTC)
|
||||
store := gamestub.NewStore()
|
||||
record := seedGameWithStatus(t, store, "game-x", game.GameTypePublic, "", status, now)
|
||||
|
||||
gm := gmclientstub.NewClient()
|
||||
service := newService(t, store, gm, fixedClock(now.Add(time.Hour)))
|
||||
|
||||
_, err := service.Handle(context.Background(), resumegame.Input{
|
||||
Actor: shared.NewAdminActor(),
|
||||
GameID: record.GameID,
|
||||
})
|
||||
require.ErrorIs(t, err, game.ErrConflict)
|
||||
assert.Equal(t, 0, gm.PingCalls(), "ping must not run before status check passes")
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestResumeGameGMUnavailableKeepsPaused(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
now := time.Date(2026, 4, 25, 12, 0, 0, 0, time.UTC)
|
||||
store := gamestub.NewStore()
|
||||
record := seedGameWithStatus(t, store, "game-pub", game.GameTypePublic, "", game.StatusPaused, now)
|
||||
|
||||
gm := gmclientstub.NewClient()
|
||||
gm.SetPingError(errors.Join(ports.ErrGMUnavailable, errors.New("dial tcp: connection refused")))
|
||||
service := newService(t, store, gm, fixedClock(now.Add(time.Hour)))
|
||||
|
||||
_, err := service.Handle(context.Background(), resumegame.Input{
|
||||
Actor: shared.NewAdminActor(),
|
||||
GameID: record.GameID,
|
||||
})
|
||||
require.Error(t, err)
|
||||
assert.ErrorIs(t, err, shared.ErrServiceUnavailable)
|
||||
assert.ErrorIs(t, err, ports.ErrGMUnavailable)
|
||||
assert.Equal(t, 1, gm.PingCalls())
|
||||
|
||||
persisted, err := store.Get(context.Background(), record.GameID)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, game.StatusPaused, persisted.Status,
|
||||
"game must remain paused when GM is unavailable")
|
||||
}
|
||||
|
||||
func TestResumeGameRejectsMissingRecord(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
gm := gmclientstub.NewClient()
|
||||
store := gamestub.NewStore()
|
||||
service := newService(t, store, gm, fixedClock(time.Date(2026, 4, 25, 12, 0, 0, 0, time.UTC)))
|
||||
|
||||
_, err := service.Handle(context.Background(), resumegame.Input{
|
||||
Actor: shared.NewAdminActor(),
|
||||
GameID: common.GameID("game-missing"),
|
||||
})
|
||||
require.ErrorIs(t, err, game.ErrNotFound)
|
||||
assert.Equal(t, 0, gm.PingCalls())
|
||||
}
|
||||
|
||||
func TestResumeGameInvalidActor(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
gm := gmclientstub.NewClient()
|
||||
store := gamestub.NewStore()
|
||||
service := newService(t, store, gm, fixedClock(time.Date(2026, 4, 25, 12, 0, 0, 0, time.UTC)))
|
||||
|
||||
_, err := service.Handle(context.Background(), resumegame.Input{
|
||||
Actor: shared.Actor{Kind: shared.ActorKindUser},
|
||||
GameID: "game-x",
|
||||
})
|
||||
require.Error(t, err)
|
||||
require.Contains(t, err.Error(), "actor")
|
||||
}
|
||||
|
||||
func TestResumeGameInvalidGameID(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
gm := gmclientstub.NewClient()
|
||||
store := gamestub.NewStore()
|
||||
service := newService(t, store, gm, fixedClock(time.Date(2026, 4, 25, 12, 0, 0, 0, time.UTC)))
|
||||
|
||||
_, err := service.Handle(context.Background(), resumegame.Input{
|
||||
Actor: shared.NewAdminActor(),
|
||||
GameID: "bad",
|
||||
})
|
||||
require.Error(t, err)
|
||||
}
|
||||
Reference in New Issue
Block a user