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,279 @@
// Package submitapplication implements the `lobby.application.submit`
// message type. It validates the request against the public-game
// enrollment rules, calls UserService for eligibility, checks race name
// availability through the Race Name Directory, persists the new
// submitted application via ApplicationStore, and publishes the
// `lobby.application.submitted` notification intent.
package submitapplication
import (
"context"
"errors"
"fmt"
"log/slog"
"time"
"galaxy/lobby/internal/domain/application"
"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"
"galaxy/notificationintent"
)
// Service executes the public-game application submission use case.
type Service struct {
games ports.GameStore
memberships ports.MembershipStore
applications ports.ApplicationStore
users ports.UserService
directory ports.RaceNameDirectory
intents ports.IntentPublisher
ids ports.IDGenerator
clock func() time.Time
logger *slog.Logger
telemetry *telemetry.Runtime
}
// Dependencies groups the collaborators used by Service.
type Dependencies struct {
// Games loads the target game record for enrollment validation.
Games ports.GameStore
// Memberships is consulted for the active-member roster count used
// to enforce the max_players + start_gap_players capacity guard.
Memberships ports.MembershipStore
// Applications persists the new submitted record.
Applications ports.ApplicationStore
// Users resolves the synchronous eligibility snapshot.
Users ports.UserService
// Directory checks race name availability.
Directory ports.RaceNameDirectory
// Intents publishes the lobby.application.submitted intent.
Intents ports.IntentPublisher
// IDs mints the new opaque application identifier.
IDs ports.IDGenerator
// Clock supplies the wall-clock used for CreatedAt and the
// notification's OccurredAt. 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.application.outcomes` counter on each
// successful submission. 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 submit application service: nil game store")
case deps.Memberships == nil:
return nil, errors.New("new submit application service: nil membership store")
case deps.Applications == nil:
return nil, errors.New("new submit application service: nil application store")
case deps.Users == nil:
return nil, errors.New("new submit application service: nil user service")
case deps.Directory == nil:
return nil, errors.New("new submit application service: nil race name directory")
case deps.Intents == nil:
return nil, errors.New("new submit application service: nil intent publisher")
case deps.IDs == nil:
return nil, errors.New("new submit application service: nil id generator")
}
clock := deps.Clock
if clock == nil {
clock = time.Now
}
logger := deps.Logger
if logger == nil {
logger = slog.Default()
}
return &Service{
games: deps.Games,
memberships: deps.Memberships,
applications: deps.Applications,
users: deps.Users,
directory: deps.Directory,
intents: deps.Intents,
ids: deps.IDs,
clock: clock,
logger: logger.With("service", "lobby.submitapplication"),
telemetry: deps.Telemetry,
}, nil
}
// Input stores the arguments required to submit one application.
type Input struct {
// Actor identifies the caller. Must be ActorKindUser.
Actor shared.Actor
// GameID identifies the target game.
GameID common.GameID
// RaceName stores the desired in-game name in original casing.
RaceName string
}
// Handle validates input, authorizes the actor, verifies eligibility and
// race name availability, persists the new submitted application, and
// publishes the lobby.application.submitted intent on success.
func (service *Service) Handle(ctx context.Context, input Input) (application.Application, error) {
if service == nil {
return application.Application{}, errors.New("submit application: nil service")
}
if ctx == nil {
return application.Application{}, errors.New("submit application: nil context")
}
if err := input.Actor.Validate(); err != nil {
return application.Application{}, fmt.Errorf("submit application: actor: %w", err)
}
if !input.Actor.IsUser() {
return application.Application{}, fmt.Errorf(
"%w: only authenticated users may submit applications",
shared.ErrForbidden,
)
}
if err := input.GameID.Validate(); err != nil {
return application.Application{}, fmt.Errorf("submit application: %w", err)
}
gameRecord, err := service.games.Get(ctx, input.GameID)
if err != nil {
return application.Application{}, fmt.Errorf("submit application: %w", err)
}
if gameRecord.GameType != game.GameTypePublic {
return application.Application{}, fmt.Errorf(
"submit application: game %q is not public: %w",
gameRecord.GameID, game.ErrConflict,
)
}
if gameRecord.Status != game.StatusEnrollmentOpen {
return application.Application{}, fmt.Errorf(
"submit application: game %q is not in enrollment_open: %w",
gameRecord.GameID, game.ErrConflict,
)
}
eligibility, err := service.users.GetEligibility(ctx, input.Actor.UserID)
if err != nil {
return application.Application{}, fmt.Errorf(
"submit application: %w: %w",
shared.ErrServiceUnavailable, err,
)
}
if !eligibility.Exists || !eligibility.CanJoinGame {
return application.Application{}, fmt.Errorf(
"%w: user is not eligible to join games",
shared.ErrEligibilityDenied,
)
}
if err := service.checkRosterCapacity(ctx, gameRecord); err != nil {
return application.Application{}, err
}
availability, err := service.directory.Check(ctx, input.RaceName, input.Actor.UserID)
if err != nil {
return application.Application{}, fmt.Errorf("submit application: %w", err)
}
if availability.Taken {
return application.Application{}, fmt.Errorf(
"submit application: race name held by another user: %w",
ports.ErrNameTaken,
)
}
applicationID, err := service.ids.NewApplicationID()
if err != nil {
return application.Application{}, fmt.Errorf("submit application: %w", err)
}
now := service.clock().UTC()
record, err := application.New(application.NewApplicationInput{
ApplicationID: applicationID,
GameID: input.GameID,
ApplicantUserID: input.Actor.UserID,
RaceName: input.RaceName,
Now: now,
})
if err != nil {
return application.Application{}, fmt.Errorf("submit application: %w", err)
}
if err := service.applications.Save(ctx, record); err != nil {
return application.Application{}, fmt.Errorf("submit application: %w", err)
}
intent, err := notificationintent.NewPublicLobbyApplicationSubmittedIntent(
notificationintent.Metadata{
IdempotencyKey: "lobby.application.submitted:" + record.ApplicationID.String(),
OccurredAt: now,
},
notificationintent.LobbyApplicationSubmittedPayload{
GameID: gameRecord.GameID.String(),
GameName: gameRecord.GameName,
ApplicantUserID: record.ApplicantUserID,
ApplicantName: record.RaceName,
},
)
if err != nil {
// Building the intent failed: this is a programmer error
// (mismatched payload contract), not a transport failure.
// Log and proceed — the application is already committed.
service.logger.ErrorContext(ctx, "build application submitted intent",
"application_id", record.ApplicationID.String(),
"err", err.Error(),
)
} else if _, publishErr := service.intents.Publish(ctx, intent); publishErr != nil {
// Notification degradation per README §Notification Contracts:
// do not roll back business state.
service.logger.WarnContext(ctx, "publish application submitted intent",
"application_id", record.ApplicationID.String(),
"err", publishErr.Error(),
)
}
service.telemetry.RecordApplicationOutcome(ctx, "submitted")
logArgs := []any{
"game_id", record.GameID.String(),
"game_type", string(gameRecord.GameType),
"game_status", string(gameRecord.Status),
"application_id", record.ApplicationID.String(),
"user_id", record.ApplicantUserID,
"race_name", record.RaceName,
}
logArgs = append(logArgs, logging.ContextAttrs(ctx)...)
service.logger.InfoContext(ctx, "application submitted", logArgs...)
return record, nil
}
// checkRosterCapacity counts active memberships for gameRecord and
// returns game.ErrConflict when the roster has reached the gap-window
// upper bound (max_players + start_gap_players).
func (service *Service) checkRosterCapacity(ctx context.Context, gameRecord game.Game) error {
cap := gameRecord.MaxPlayers + gameRecord.StartGapPlayers
count, err := shared.CountActiveMemberships(ctx, service.memberships, gameRecord.GameID)
if err != nil {
return fmt.Errorf("submit application: %w", err)
}
if count >= cap {
return fmt.Errorf(
"submit application: roster full (%d active >= %d cap): %w",
count, cap, game.ErrConflict,
)
}
return nil
}
@@ -0,0 +1,335 @@
package submitapplication_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/membershipstub"
"galaxy/lobby/internal/adapters/racenamestub"
"galaxy/lobby/internal/adapters/userservicestub"
"galaxy/lobby/internal/domain/application"
"galaxy/lobby/internal/domain/common"
"galaxy/lobby/internal/domain/game"
"galaxy/lobby/internal/domain/membership"
"galaxy/lobby/internal/ports"
"galaxy/lobby/internal/service/shared"
"galaxy/lobby/internal/service/submitapplication"
"galaxy/notificationintent"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
const (
defaultRaceName = "SolarPilot"
otherRaceName = "VoidRunner"
)
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 fixedIDs struct {
applicationID common.ApplicationID
membershipID common.MembershipID
}
func (f fixedIDs) NewGameID() (common.GameID, error) { return "", errors.New("not used") }
func (f fixedIDs) NewApplicationID() (common.ApplicationID, error) {
return f.applicationID, nil
}
func (f fixedIDs) NewInviteID() (common.InviteID, error) {
return "", errors.New("not used")
}
func (f fixedIDs) NewMembershipID() (common.MembershipID, error) {
return f.membershipID, nil
}
type fixture struct {
now time.Time
games *gamestub.Store
memberships *membershipstub.Store
applications *applicationstub.Store
directory *racenamestub.Directory
users *userservicestub.Service
intents *intentpubstub.Publisher
ids fixedIDs
openPublicGameID common.GameID
defaultUserID string
}
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)
users := userservicestub.NewService()
users.SetEligibility("user-1", ports.Eligibility{Exists: true, CanLogin: true, CanJoinGame: true})
games := gamestub.NewStore()
memberships := membershipstub.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,
memberships: memberships,
applications: applications,
directory: dir,
users: users,
intents: intentpubstub.NewPublisher(),
ids: fixedIDs{applicationID: "application-fixed", membershipID: "membership-fixed"},
openPublicGameID: gameRecord.GameID,
defaultUserID: "user-1",
}
}
func newService(t *testing.T, f *fixture) *submitapplication.Service {
t.Helper()
svc, err := submitapplication.NewService(submitapplication.Dependencies{
Games: f.games,
Memberships: f.memberships,
Applications: f.applications,
Users: f.users,
Directory: f.directory,
Intents: f.intents,
IDs: f.ids,
Clock: fixedClock(f.now),
Logger: silentLogger(),
})
require.NoError(t, err)
return svc
}
func defaultInput(f *fixture) submitapplication.Input {
return submitapplication.Input{
Actor: shared.NewUserActor(f.defaultUserID),
GameID: f.openPublicGameID,
RaceName: defaultRaceName,
}
}
func TestHandleHappyPath(t *testing.T) {
t.Parallel()
f := newFixture(t)
svc := newService(t, f)
got, err := svc.Handle(context.Background(), defaultInput(f))
require.NoError(t, err)
assert.Equal(t, application.StatusSubmitted, got.Status)
assert.Equal(t, common.ApplicationID("application-fixed"), got.ApplicationID)
assert.Equal(t, defaultRaceName, got.RaceName)
intents := f.intents.Published()
require.Len(t, intents, 1)
assert.Equal(t, notificationintent.NotificationTypeLobbyApplicationSubmitted, intents[0].NotificationType)
assert.Equal(t, notificationintent.AudienceKindAdminEmail, intents[0].AudienceKind)
}
func TestHandleAdminActorForbidden(t *testing.T) {
t.Parallel()
f := newFixture(t)
svc := newService(t, f)
input := defaultInput(f)
input.Actor = shared.NewAdminActor()
_, err := svc.Handle(context.Background(), input)
require.ErrorIs(t, err, shared.ErrForbidden)
}
func TestHandleGameNotFound(t *testing.T) {
t.Parallel()
f := newFixture(t)
svc := newService(t, f)
input := defaultInput(f)
input.GameID = "game-missing"
_, err := svc.Handle(context.Background(), input)
require.ErrorIs(t, err, game.ErrNotFound)
}
func TestHandleNonPublicGameConflict(t *testing.T) {
t.Parallel()
f := newFixture(t)
now := f.now
private, err := game.New(game.NewGameInput{
GameID: "game-private",
GameName: "Private Match",
GameType: game.GameTypePrivate,
OwnerUserID: "user-9",
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)
private.Status = game.StatusEnrollmentOpen
require.NoError(t, f.games.Save(context.Background(), private))
svc := newService(t, f)
input := defaultInput(f)
input.GameID = private.GameID
_, err = svc.Handle(context.Background(), input)
require.ErrorIs(t, err, game.ErrConflict)
}
func TestHandleWrongStatusConflict(t *testing.T) {
t.Parallel()
f := newFixture(t)
// Force status back to draft.
rec, err := f.games.Get(context.Background(), f.openPublicGameID)
require.NoError(t, err)
rec.Status = game.StatusDraft
require.NoError(t, f.games.Save(context.Background(), rec))
svc := newService(t, f)
_, err = svc.Handle(context.Background(), defaultInput(f))
require.ErrorIs(t, err, game.ErrConflict)
}
func TestHandleUserMissingEligibilityDenied(t *testing.T) {
t.Parallel()
f := newFixture(t)
// Default-missing returns Exists=false.
svc := newService(t, f)
input := defaultInput(f)
input.Actor = shared.NewUserActor("user-unknown")
_, err := svc.Handle(context.Background(), input)
require.ErrorIs(t, err, shared.ErrEligibilityDenied)
}
func TestHandleCanJoinGameFalseEligibilityDenied(t *testing.T) {
t.Parallel()
f := newFixture(t)
f.users.SetEligibility("user-blocked", ports.Eligibility{Exists: true, CanLogin: true, CanJoinGame: false})
svc := newService(t, f)
input := defaultInput(f)
input.Actor = shared.NewUserActor("user-blocked")
_, err := svc.Handle(context.Background(), input)
require.ErrorIs(t, err, shared.ErrEligibilityDenied)
}
func TestHandleUserServiceUnavailable(t *testing.T) {
t.Parallel()
f := newFixture(t)
f.users.SetFailure(f.defaultUserID, ports.ErrUserServiceUnavailable)
svc := newService(t, f)
_, err := svc.Handle(context.Background(), defaultInput(f))
require.ErrorIs(t, err, shared.ErrServiceUnavailable)
require.ErrorIs(t, err, ports.ErrUserServiceUnavailable)
}
func TestHandleRosterFullConflict(t *testing.T) {
t.Parallel()
f := newFixture(t)
// Capacity = max_players(4) + start_gap_players(1) = 5; seed 5 active members.
for i := range 5 {
member, err := membership.New(membership.NewMembershipInput{
MembershipID: common.MembershipID("membership-seed-" + string(rune('a'+i))),
GameID: f.openPublicGameID,
UserID: "seed-user-" + string(rune('a'+i)),
RaceName: "Seed " + string(rune('A'+i)),
CanonicalKey: "seed" + string(rune('a'+i)),
Now: f.now,
})
require.NoError(t, err)
require.NoError(t, f.memberships.Save(context.Background(), member))
}
svc := newService(t, f)
_, err := svc.Handle(context.Background(), defaultInput(f))
require.ErrorIs(t, err, game.ErrConflict)
}
func TestHandleRaceNameTakenByOtherUser(t *testing.T) {
t.Parallel()
f := newFixture(t)
require.NoError(t, f.directory.Reserve(context.Background(), "game-other", "user-2", defaultRaceName))
svc := newService(t, f)
_, err := svc.Handle(context.Background(), defaultInput(f))
require.ErrorIs(t, err, ports.ErrNameTaken)
}
func TestHandleInvalidRaceName(t *testing.T) {
t.Parallel()
f := newFixture(t)
svc := newService(t, f)
input := defaultInput(f)
input.RaceName = " " // empty after trim — ports.ErrInvalidName
_, err := svc.Handle(context.Background(), input)
require.Error(t, err)
require.True(t, errors.Is(err, ports.ErrInvalidName))
}
func TestHandleDuplicateActiveApplicationConflict(t *testing.T) {
t.Parallel()
f := newFixture(t)
// Pre-existing submitted application by the same user for the same game.
existing, err := application.New(application.NewApplicationInput{
ApplicationID: "application-existing",
GameID: f.openPublicGameID,
ApplicantUserID: f.defaultUserID,
RaceName: otherRaceName,
Now: f.now,
})
require.NoError(t, err)
require.NoError(t, f.applications.Save(context.Background(), existing))
svc := newService(t, f)
_, err = svc.Handle(context.Background(), defaultInput(f))
require.ErrorIs(t, err, application.ErrConflict)
}
func TestHandlePublishFailureDoesNotRollback(t *testing.T) {
t.Parallel()
f := newFixture(t)
f.intents.SetError(errors.New("publish failed"))
svc := newService(t, f)
got, err := svc.Handle(context.Background(), defaultInput(f))
require.NoError(t, err)
assert.Equal(t, application.StatusSubmitted, got.Status)
stored, err := f.applications.Get(context.Background(), got.ApplicationID)
require.NoError(t, err)
assert.Equal(t, application.StatusSubmitted, stored.Status)
}