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,216 @@
// Package rejectapplication implements the `lobby.application.reject`
// message type. It transitions the application from submitted to
// rejected, defensively releases any race name reservation held for
// the applicant in the game, and publishes the
// `lobby.membership.rejected` notification intent.
package rejectapplication
import (
"context"
"errors"
"fmt"
"log/slog"
"time"
"galaxy/lobby/internal/domain/application"
"galaxy/lobby/internal/domain/common"
"galaxy/lobby/internal/logging"
"galaxy/lobby/internal/ports"
"galaxy/lobby/internal/service/shared"
"galaxy/lobby/internal/telemetry"
"galaxy/notificationintent"
)
// Service executes the public-game application rejection use case.
type Service struct {
games ports.GameStore
applications ports.ApplicationStore
directory ports.RaceNameDirectory
intents ports.IntentPublisher
clock func() time.Time
logger *slog.Logger
telemetry *telemetry.Runtime
}
// Dependencies groups the collaborators used by Service.
type Dependencies struct {
// Games loads the game record so the rejection intent can carry
// the human-readable game_name for display.
Games ports.GameStore
// Applications applies the submitted → rejected transition.
Applications ports.ApplicationStore
// Directory releases any reservation held for the applicant in
// the game (no-op when none exists).
Directory ports.RaceNameDirectory
// Intents publishes the lobby.membership.rejected intent.
Intents ports.IntentPublisher
// Clock supplies the wall-clock used for DecidedAt and the
// notification's OccurredAt.
Clock func() time.Time
// Logger records structured service-level events.
Logger *slog.Logger
// Telemetry records the `lobby.application.outcomes` counter on
// each rejection. 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 reject application service: nil game store")
case deps.Applications == nil:
return nil, errors.New("new reject application service: nil application store")
case deps.Directory == nil:
return nil, errors.New("new reject application service: nil race name directory")
case deps.Intents == nil:
return nil, errors.New("new reject application service: nil intent publisher")
}
clock := deps.Clock
if clock == nil {
clock = time.Now
}
logger := deps.Logger
if logger == nil {
logger = slog.Default()
}
return &Service{
games: deps.Games,
applications: deps.Applications,
directory: deps.Directory,
intents: deps.Intents,
clock: clock,
logger: logger.With("service", "lobby.rejectapplication"),
telemetry: deps.Telemetry,
}, nil
}
// Input stores the arguments required to reject one application.
type Input struct {
// Actor identifies the caller. Must be ActorKindAdmin.
Actor shared.Actor
// GameID identifies the game referenced by the request path; it
// must match the loaded application's GameID.
GameID common.GameID
// ApplicationID identifies the target application.
ApplicationID common.ApplicationID
}
// Handle authorizes the actor, validates the application state,
// transitions the application to rejected, releases any held
// reservation, and publishes the lobby.membership.rejected intent on
// success.
func (service *Service) Handle(ctx context.Context, input Input) (application.Application, error) {
if service == nil {
return application.Application{}, errors.New("reject application: nil service")
}
if ctx == nil {
return application.Application{}, errors.New("reject application: nil context")
}
if err := input.Actor.Validate(); err != nil {
return application.Application{}, fmt.Errorf("reject application: actor: %w", err)
}
if !input.Actor.IsAdmin() {
return application.Application{}, fmt.Errorf(
"%w: only admin callers may reject applications",
shared.ErrForbidden,
)
}
if err := input.GameID.Validate(); err != nil {
return application.Application{}, fmt.Errorf("reject application: %w", err)
}
if err := input.ApplicationID.Validate(); err != nil {
return application.Application{}, fmt.Errorf("reject application: %w", err)
}
app, err := service.applications.Get(ctx, input.ApplicationID)
if err != nil {
return application.Application{}, fmt.Errorf("reject application: %w", err)
}
if app.GameID != input.GameID {
return application.Application{}, fmt.Errorf(
"reject application: application %q does not belong to game %q: %w",
app.ApplicationID, input.GameID, application.ErrNotFound,
)
}
if app.Status != application.StatusSubmitted {
return application.Application{}, fmt.Errorf(
"reject application: status %q is not %q: %w",
app.Status, application.StatusSubmitted, application.ErrConflict,
)
}
gameRecord, err := service.games.Get(ctx, input.GameID)
if err != nil {
return application.Application{}, fmt.Errorf("reject application: %w", err)
}
now := service.clock().UTC()
if err := service.applications.UpdateStatus(ctx, ports.UpdateApplicationStatusInput{
ApplicationID: app.ApplicationID,
ExpectedFrom: application.StatusSubmitted,
To: application.StatusRejected,
At: now,
}); err != nil {
return application.Application{}, fmt.Errorf("reject application: %w", err)
}
if err := service.directory.ReleaseReservation(ctx, gameRecord.GameID.String(), app.ApplicantUserID, app.RaceName); err != nil {
// The directory contract states ReleaseReservation is a no-op
// for missing / mismatched / invalid records, so a non-nil
// error here is unexpected. Log and proceed — the
// application is already rejected.
service.logger.WarnContext(ctx, "release reservation on reject",
"application_id", app.ApplicationID.String(),
"err", err.Error(),
)
}
intent, err := notificationintent.NewLobbyMembershipRejectedIntent(
notificationintent.Metadata{
IdempotencyKey: "lobby.membership.rejected:" + app.ApplicationID.String(),
OccurredAt: now,
},
app.ApplicantUserID,
notificationintent.LobbyMembershipRejectedPayload{
GameID: gameRecord.GameID.String(),
GameName: gameRecord.GameName,
},
)
if err != nil {
service.logger.ErrorContext(ctx, "build membership rejected intent",
"application_id", app.ApplicationID.String(),
"err", err.Error(),
)
} else if _, publishErr := service.intents.Publish(ctx, intent); publishErr != nil {
service.logger.WarnContext(ctx, "publish membership rejected intent",
"application_id", app.ApplicationID.String(),
"err", publishErr.Error(),
)
}
rejected, err := service.applications.Get(ctx, app.ApplicationID)
if err != nil {
return application.Application{}, fmt.Errorf("reject application: %w", err)
}
service.telemetry.RecordApplicationOutcome(ctx, "rejected")
logArgs := []any{
"game_id", gameRecord.GameID.String(),
"game_status", string(gameRecord.Status),
"application_id", app.ApplicationID.String(),
"user_id", app.ApplicantUserID,
}
logArgs = append(logArgs, logging.ContextAttrs(ctx)...)
service.logger.InfoContext(ctx, "application rejected", logArgs...)
return rejected, nil
}
@@ -0,0 +1,225 @@
package rejectapplication_test
import (
"context"
"errors"
"io"
"log/slog"
"testing"
"time"
"galaxy/lobby/internal/adapters/applicationstub"
"galaxy/lobby/internal/adapters/gamestub"
"galaxy/lobby/internal/adapters/intentpubstub"
"galaxy/lobby/internal/adapters/racenamestub"
"galaxy/lobby/internal/domain/application"
"galaxy/lobby/internal/domain/common"
"galaxy/lobby/internal/domain/game"
"galaxy/lobby/internal/ports"
"galaxy/lobby/internal/service/rejectapplication"
"galaxy/lobby/internal/service/shared"
"galaxy/notificationintent"
"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 } }
type fixture struct {
now time.Time
games *gamestub.Store
applications *applicationstub.Store
directory *racenamestub.Directory
intents *intentpubstub.Publisher
openPublicGameID common.GameID
}
func newFixture(t *testing.T) *fixture {
t.Helper()
now := time.Date(2026, 4, 25, 10, 0, 0, 0, time.UTC)
dir, err := racenamestub.NewDirectory(racenamestub.WithClock(fixedClock(now)))
require.NoError(t, err)
games := gamestub.NewStore()
applications := applicationstub.NewStore()
gameRecord, err := game.New(game.NewGameInput{
GameID: "game-public",
GameName: "Galactic Open",
GameType: game.GameTypePublic,
MinPlayers: 2,
MaxPlayers: 4,
StartGapHours: 2,
StartGapPlayers: 1,
EnrollmentEndsAt: now.Add(24 * time.Hour),
TurnSchedule: "0 */6 * * *",
TargetEngineVersion: "1.0.0",
Now: now,
})
require.NoError(t, err)
gameRecord.Status = game.StatusEnrollmentOpen
require.NoError(t, games.Save(context.Background(), gameRecord))
return &fixture{
now: now,
games: games,
applications: applications,
directory: dir,
intents: intentpubstub.NewPublisher(),
openPublicGameID: gameRecord.GameID,
}
}
func newService(t *testing.T, f *fixture) *rejectapplication.Service {
t.Helper()
svc, err := rejectapplication.NewService(rejectapplication.Dependencies{
Games: f.games,
Applications: f.applications,
Directory: f.directory,
Intents: f.intents,
Clock: fixedClock(f.now),
Logger: silentLogger(),
})
require.NoError(t, err)
return svc
}
func seedSubmittedApplication(t *testing.T, f *fixture, applicationID common.ApplicationID, userID, raceName string) application.Application {
t.Helper()
app, err := application.New(application.NewApplicationInput{
ApplicationID: applicationID,
GameID: f.openPublicGameID,
ApplicantUserID: userID,
RaceName: raceName,
Now: f.now,
})
require.NoError(t, err)
require.NoError(t, f.applications.Save(context.Background(), app))
return app
}
func TestRejectHappyPath(t *testing.T) {
t.Parallel()
f := newFixture(t)
app := seedSubmittedApplication(t, f, "application-1", "user-1", "SolarPilot")
svc := newService(t, f)
got, err := svc.Handle(context.Background(), rejectapplication.Input{
Actor: shared.NewAdminActor(),
GameID: f.openPublicGameID,
ApplicationID: app.ApplicationID,
})
require.NoError(t, err)
assert.Equal(t, application.StatusRejected, got.Status)
require.NotNil(t, got.DecidedAt)
assert.Equal(t, f.now, got.DecidedAt.UTC())
intents := f.intents.Published()
require.Len(t, intents, 1)
assert.Equal(t, notificationintent.NotificationTypeLobbyMembershipRejected, intents[0].NotificationType)
assert.Equal(t, []string{"user-1"}, intents[0].RecipientUserIDs)
}
func TestRejectReleasesPriorReservation(t *testing.T) {
t.Parallel()
f := newFixture(t)
app := seedSubmittedApplication(t, f, "application-1", "user-1", "SolarPilot")
require.NoError(t, f.directory.Reserve(context.Background(), f.openPublicGameID.String(), "user-1", "SolarPilot"))
svc := newService(t, f)
_, err := svc.Handle(context.Background(), rejectapplication.Input{
Actor: shared.NewAdminActor(),
GameID: f.openPublicGameID,
ApplicationID: app.ApplicationID,
})
require.NoError(t, err)
availability, err := f.directory.Check(context.Background(), "SolarPilot", "user-other")
require.NoError(t, err)
assert.False(t, availability.Taken)
assert.Empty(t, availability.HolderUserID)
}
func TestRejectUserActorForbidden(t *testing.T) {
t.Parallel()
f := newFixture(t)
app := seedSubmittedApplication(t, f, "application-1", "user-1", "SolarPilot")
svc := newService(t, f)
_, err := svc.Handle(context.Background(), rejectapplication.Input{
Actor: shared.NewUserActor("user-1"),
GameID: f.openPublicGameID,
ApplicationID: app.ApplicationID,
})
require.ErrorIs(t, err, shared.ErrForbidden)
}
func TestRejectNotFound(t *testing.T) {
t.Parallel()
f := newFixture(t)
svc := newService(t, f)
_, err := svc.Handle(context.Background(), rejectapplication.Input{
Actor: shared.NewAdminActor(),
GameID: f.openPublicGameID,
ApplicationID: "application-missing",
})
require.ErrorIs(t, err, application.ErrNotFound)
}
func TestRejectCrossGameNotFound(t *testing.T) {
t.Parallel()
f := newFixture(t)
app := seedSubmittedApplication(t, f, "application-1", "user-1", "SolarPilot")
svc := newService(t, f)
_, err := svc.Handle(context.Background(), rejectapplication.Input{
Actor: shared.NewAdminActor(),
GameID: "game-other",
ApplicationID: app.ApplicationID,
})
require.ErrorIs(t, err, application.ErrNotFound)
}
func TestRejectAlreadyDecidedConflict(t *testing.T) {
t.Parallel()
f := newFixture(t)
app := seedSubmittedApplication(t, f, "application-1", "user-1", "SolarPilot")
require.NoError(t, f.applications.UpdateStatus(context.Background(), ports.UpdateApplicationStatusInput{
ApplicationID: app.ApplicationID,
ExpectedFrom: application.StatusSubmitted,
To: application.StatusApproved,
At: f.now,
}))
svc := newService(t, f)
_, err := svc.Handle(context.Background(), rejectapplication.Input{
Actor: shared.NewAdminActor(),
GameID: f.openPublicGameID,
ApplicationID: app.ApplicationID,
})
require.ErrorIs(t, err, application.ErrConflict)
}
func TestRejectPublishFailureDoesNotRollback(t *testing.T) {
t.Parallel()
f := newFixture(t)
app := seedSubmittedApplication(t, f, "application-1", "user-1", "SolarPilot")
f.intents.SetError(errors.New("publish failed"))
svc := newService(t, f)
got, err := svc.Handle(context.Background(), rejectapplication.Input{
Actor: shared.NewAdminActor(),
GameID: f.openPublicGameID,
ApplicationID: app.ApplicationID,
})
require.NoError(t, err)
assert.Equal(t, application.StatusRejected, got.Status)
stored, err := f.applications.Get(context.Background(), app.ApplicationID)
require.NoError(t, err)
assert.Equal(t, application.StatusRejected, stored.Status)
}