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,167 @@
// Package revokeinvite implements the `lobby.invite.revoke` message type. It
// transitions the invite from created to revoked when the actor is the
// private-game owner. Per `lobby/README.md` §Invite Lifecycle, no
// notification is published in v1.
package revokeinvite
import (
"context"
"errors"
"fmt"
"log/slog"
"time"
"galaxy/lobby/internal/domain/common"
"galaxy/lobby/internal/domain/invite"
"galaxy/lobby/internal/logging"
"galaxy/lobby/internal/ports"
"galaxy/lobby/internal/service/shared"
"galaxy/lobby/internal/telemetry"
)
// Service executes the private-game invite revoke use case.
type Service struct {
games ports.GameStore
invites ports.InviteStore
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 for the owner-authorization check.
Games ports.GameStore
// Invites loads the target invite and applies the
// created → revoked transition.
Invites ports.InviteStore
// Clock supplies the wall-clock used for DecidedAt.
Clock func() time.Time
// Logger records structured service-level events.
Logger *slog.Logger
// Telemetry records the `lobby.invite.outcomes` counter on each
// successful revoke. 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 revoke invite service: nil game store")
case deps.Invites == nil:
return nil, errors.New("new revoke invite service: nil invite store")
}
clock := deps.Clock
if clock == nil {
clock = time.Now
}
logger := deps.Logger
if logger == nil {
logger = slog.Default()
}
return &Service{
games: deps.Games,
invites: deps.Invites,
clock: clock,
logger: logger.With("service", "lobby.revokeinvite"),
telemetry: deps.Telemetry,
}, nil
}
// Input stores the arguments required to revoke one invite.
type Input struct {
// Actor identifies the caller. Must be the private-game owner.
Actor shared.Actor
// GameID identifies the game referenced by the request path; it must
// match the loaded invite's GameID.
GameID common.GameID
// InviteID identifies the target invite.
InviteID common.InviteID
}
// Handle authorizes the owner, validates the invite state, transitions the
// invite to revoked, and returns the updated record.
func (service *Service) Handle(ctx context.Context, input Input) (invite.Invite, error) {
if service == nil {
return invite.Invite{}, errors.New("revoke invite: nil service")
}
if ctx == nil {
return invite.Invite{}, errors.New("revoke invite: nil context")
}
if err := input.Actor.Validate(); err != nil {
return invite.Invite{}, fmt.Errorf("revoke invite: actor: %w", err)
}
if !input.Actor.IsUser() {
return invite.Invite{}, fmt.Errorf(
"%w: only the private-game owner may revoke an invite",
shared.ErrForbidden,
)
}
if err := input.GameID.Validate(); err != nil {
return invite.Invite{}, fmt.Errorf("revoke invite: %w", err)
}
if err := input.InviteID.Validate(); err != nil {
return invite.Invite{}, fmt.Errorf("revoke invite: %w", err)
}
inv, err := service.invites.Get(ctx, input.InviteID)
if err != nil {
return invite.Invite{}, fmt.Errorf("revoke invite: %w", err)
}
if inv.GameID != input.GameID {
return invite.Invite{}, fmt.Errorf(
"revoke invite: invite %q does not belong to game %q: %w",
inv.InviteID, input.GameID, invite.ErrNotFound,
)
}
if inv.Status != invite.StatusCreated {
return invite.Invite{}, fmt.Errorf(
"revoke invite: status %q is not %q: %w",
inv.Status, invite.StatusCreated, invite.ErrConflict,
)
}
gameRecord, err := service.games.Get(ctx, input.GameID)
if err != nil {
return invite.Invite{}, fmt.Errorf("revoke invite: %w", err)
}
if gameRecord.OwnerUserID != input.Actor.UserID {
return invite.Invite{}, fmt.Errorf(
"%w: actor is not the owner of game %q",
shared.ErrForbidden, gameRecord.GameID,
)
}
now := service.clock().UTC()
if err := service.invites.UpdateStatus(ctx, ports.UpdateInviteStatusInput{
InviteID: inv.InviteID,
ExpectedFrom: invite.StatusCreated,
To: invite.StatusRevoked,
At: now,
}); err != nil {
return invite.Invite{}, fmt.Errorf("revoke invite: %w", err)
}
revoked, err := service.invites.Get(ctx, inv.InviteID)
if err != nil {
return invite.Invite{}, fmt.Errorf("revoke invite: %w", err)
}
service.telemetry.RecordInviteOutcome(ctx, "revoked")
logArgs := []any{
"game_id", revoked.GameID.String(),
"invite_id", revoked.InviteID.String(),
"invitee_user_id", revoked.InviteeUserID,
}
logArgs = append(logArgs, logging.ContextAttrs(ctx)...)
service.logger.InfoContext(ctx, "invite revoked", logArgs...)
return revoked, nil
}
@@ -0,0 +1,212 @@
package revokeinvite_test
import (
"context"
"io"
"log/slog"
"testing"
"time"
"galaxy/lobby/internal/adapters/gamestub"
"galaxy/lobby/internal/adapters/invitestub"
"galaxy/lobby/internal/domain/common"
"galaxy/lobby/internal/domain/game"
"galaxy/lobby/internal/domain/invite"
"galaxy/lobby/internal/ports"
"galaxy/lobby/internal/service/revokeinvite"
"galaxy/lobby/internal/service/shared"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
const (
ownerUserID = "user-owner"
inviteeUserID = "user-invitee"
)
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
invites *invitestub.Store
game game.Game
}
func newFixture(t *testing.T) *fixture {
t.Helper()
now := time.Date(2026, 4, 25, 10, 0, 0, 0, time.UTC)
games := gamestub.NewStore()
invites := invitestub.NewStore()
gameRecord, err := game.New(game.NewGameInput{
GameID: "game-private",
GameName: "Friends Only",
GameType: game.GameTypePrivate,
OwnerUserID: ownerUserID,
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,
invites: invites,
game: gameRecord,
}
}
func newService(t *testing.T, f *fixture) *revokeinvite.Service {
t.Helper()
svc, err := revokeinvite.NewService(revokeinvite.Dependencies{
Games: f.games,
Invites: f.invites,
Clock: fixedClock(f.now),
Logger: silentLogger(),
})
require.NoError(t, err)
return svc
}
func seedCreatedInvite(t *testing.T, f *fixture, inviteID common.InviteID, invitee string) invite.Invite {
t.Helper()
inv, err := invite.New(invite.NewInviteInput{
InviteID: inviteID,
GameID: f.game.GameID,
InviterUserID: ownerUserID,
InviteeUserID: invitee,
Now: f.now,
ExpiresAt: f.game.EnrollmentEndsAt,
})
require.NoError(t, err)
require.NoError(t, f.invites.Save(context.Background(), inv))
return inv
}
func TestRevokeHappyPath(t *testing.T) {
t.Parallel()
f := newFixture(t)
inv := seedCreatedInvite(t, f, "invite-1", inviteeUserID)
svc := newService(t, f)
got, err := svc.Handle(context.Background(), revokeinvite.Input{
Actor: shared.NewUserActor(ownerUserID),
GameID: f.game.GameID,
InviteID: inv.InviteID,
})
require.NoError(t, err)
assert.Equal(t, invite.StatusRevoked, got.Status)
require.NotNil(t, got.DecidedAt)
assert.Equal(t, f.now, *got.DecidedAt)
}
func TestRevokeAdminActorForbidden(t *testing.T) {
t.Parallel()
f := newFixture(t)
inv := seedCreatedInvite(t, f, "invite-1", inviteeUserID)
svc := newService(t, f)
_, err := svc.Handle(context.Background(), revokeinvite.Input{
Actor: shared.NewAdminActor(),
GameID: f.game.GameID,
InviteID: inv.InviteID,
})
require.ErrorIs(t, err, shared.ErrForbidden)
}
func TestRevokeNonOwnerForbidden(t *testing.T) {
t.Parallel()
f := newFixture(t)
inv := seedCreatedInvite(t, f, "invite-1", inviteeUserID)
svc := newService(t, f)
_, err := svc.Handle(context.Background(), revokeinvite.Input{
Actor: shared.NewUserActor("user-impostor"),
GameID: f.game.GameID,
InviteID: inv.InviteID,
})
require.ErrorIs(t, err, shared.ErrForbidden)
}
func TestRevokeInviteNotFound(t *testing.T) {
t.Parallel()
f := newFixture(t)
svc := newService(t, f)
_, err := svc.Handle(context.Background(), revokeinvite.Input{
Actor: shared.NewUserActor(ownerUserID),
GameID: f.game.GameID,
InviteID: "invite-missing",
})
require.ErrorIs(t, err, invite.ErrNotFound)
}
func TestRevokeCrossGameNotFound(t *testing.T) {
t.Parallel()
f := newFixture(t)
inv := seedCreatedInvite(t, f, "invite-1", inviteeUserID)
svc := newService(t, f)
_, err := svc.Handle(context.Background(), revokeinvite.Input{
Actor: shared.NewUserActor(ownerUserID),
GameID: "game-other",
InviteID: inv.InviteID,
})
require.ErrorIs(t, err, invite.ErrNotFound)
}
func TestRevokeWrongStatusConflict(t *testing.T) {
t.Parallel()
f := newFixture(t)
inv := seedCreatedInvite(t, f, "invite-1", inviteeUserID)
require.NoError(t, f.invites.UpdateStatus(context.Background(), ports.UpdateInviteStatusInput{
InviteID: inv.InviteID,
ExpectedFrom: invite.StatusCreated,
To: invite.StatusDeclined,
At: f.now,
}))
svc := newService(t, f)
_, err := svc.Handle(context.Background(), revokeinvite.Input{
Actor: shared.NewUserActor(ownerUserID),
GameID: f.game.GameID,
InviteID: inv.InviteID,
})
require.ErrorIs(t, err, invite.ErrConflict)
}
func TestRevokeGameNotFound(t *testing.T) {
t.Parallel()
f := newFixture(t)
inv := seedCreatedInvite(t, f, "invite-1", inviteeUserID)
// Re-wire the service against a fresh empty games store so the
// owner-check load fails. The invite remains addressable; the missing
// game path is a defensive guard, but the surfaced error must be
// subject_not_found rather than forbidden.
svc, err := revokeinvite.NewService(revokeinvite.Dependencies{
Games: gamestub.NewStore(),
Invites: f.invites,
Clock: fixedClock(f.now),
Logger: silentLogger(),
})
require.NoError(t, err)
_, err = svc.Handle(context.Background(), revokeinvite.Input{
Actor: shared.NewUserActor(ownerUserID),
GameID: f.game.GameID,
InviteID: inv.InviteID,
})
require.ErrorIs(t, err, game.ErrNotFound)
}