feat: game lobby service
This commit is contained in:
@@ -0,0 +1,183 @@
|
||||
// Package listmyapplications implements the `lobby.my_applications.list`
|
||||
// message type. It returns the acting user's submitted applications
|
||||
// joined with the corresponding game's `game_name` and `game_type`,
|
||||
// matching `lobby/README.md` §«My pending applications».
|
||||
//
|
||||
// The service is exclusively self-service: admin actors are rejected
|
||||
// with `shared.ErrForbidden`. Cross-user reads are not exposed by this
|
||||
// route in v1.
|
||||
package listmyapplications
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"sort"
|
||||
|
||||
"galaxy/lobby/internal/domain/application"
|
||||
"galaxy/lobby/internal/domain/common"
|
||||
"galaxy/lobby/internal/domain/game"
|
||||
"galaxy/lobby/internal/ports"
|
||||
"galaxy/lobby/internal/service/shared"
|
||||
)
|
||||
|
||||
// Service executes the list-my-applications use case.
|
||||
type Service struct {
|
||||
games ports.GameStore
|
||||
applications ports.ApplicationStore
|
||||
logger *slog.Logger
|
||||
}
|
||||
|
||||
// Dependencies groups the collaborators used by Service.
|
||||
type Dependencies struct {
|
||||
// Games is loaded per submitted application to enrich the response
|
||||
// with game name and type for client display.
|
||||
Games ports.GameStore
|
||||
|
||||
// Applications supplies the per-applicant index.
|
||||
Applications ports.ApplicationStore
|
||||
|
||||
// Logger records structured diagnostics. Defaults to slog.Default
|
||||
// when nil.
|
||||
Logger *slog.Logger
|
||||
}
|
||||
|
||||
// NewService constructs one Service with deps.
|
||||
func NewService(deps Dependencies) (*Service, error) {
|
||||
switch {
|
||||
case deps.Games == nil:
|
||||
return nil, errors.New("new list my applications service: nil game store")
|
||||
case deps.Applications == nil:
|
||||
return nil, errors.New("new list my applications service: nil application store")
|
||||
}
|
||||
logger := deps.Logger
|
||||
if logger == nil {
|
||||
logger = slog.Default()
|
||||
}
|
||||
return &Service{
|
||||
games: deps.Games,
|
||||
applications: deps.Applications,
|
||||
logger: logger.With("service", "lobby.listmyapplications"),
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Input stores the arguments required to compute the acting user's
|
||||
// submitted-applications view.
|
||||
type Input struct {
|
||||
// Actor identifies the caller. Must be ActorKindUser.
|
||||
Actor shared.Actor
|
||||
|
||||
// Page stores the pagination request.
|
||||
Page shared.Page
|
||||
}
|
||||
|
||||
// Item enriches one submitted application with the host game's name
|
||||
// and type, mirroring the OpenAPI `MyApplicationItem` schema.
|
||||
type Item struct {
|
||||
Application application.Application
|
||||
GameName string
|
||||
GameType game.GameType
|
||||
}
|
||||
|
||||
// Output stores the page returned by Handle.
|
||||
type Output struct {
|
||||
// Items stores the enriched application records included in the
|
||||
// current page.
|
||||
Items []Item
|
||||
|
||||
// NextPageToken stores the opaque continuation token; empty when
|
||||
// the current page is the last one.
|
||||
NextPageToken string
|
||||
}
|
||||
|
||||
// Handle authorizes the actor as a user, fetches their applications,
|
||||
// filters to `submitted`, joins with the game store, sorts, and
|
||||
// returns the requested page.
|
||||
func (service *Service) Handle(ctx context.Context, input Input) (Output, error) {
|
||||
if service == nil {
|
||||
return Output{}, errors.New("list my applications: nil service")
|
||||
}
|
||||
if ctx == nil {
|
||||
return Output{}, errors.New("list my applications: nil context")
|
||||
}
|
||||
if err := input.Actor.Validate(); err != nil {
|
||||
return Output{}, fmt.Errorf("list my applications: actor: %w", err)
|
||||
}
|
||||
if !input.Actor.IsUser() {
|
||||
return Output{}, fmt.Errorf(
|
||||
"%w: only authenticated user actors may list their applications",
|
||||
shared.ErrForbidden,
|
||||
)
|
||||
}
|
||||
|
||||
records, err := service.applications.GetByUser(ctx, input.Actor.UserID)
|
||||
if err != nil {
|
||||
return Output{}, fmt.Errorf("list my applications: %w", err)
|
||||
}
|
||||
|
||||
candidates := make([]Item, 0, len(records))
|
||||
for _, record := range records {
|
||||
if record.Status != application.StatusSubmitted {
|
||||
continue
|
||||
}
|
||||
gameName, gameType, ok := service.lookupGame(ctx, record.GameID, record.ApplicationID)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
candidates = append(candidates, Item{
|
||||
Application: record,
|
||||
GameName: gameName,
|
||||
GameType: gameType,
|
||||
})
|
||||
}
|
||||
|
||||
sortItems(candidates)
|
||||
|
||||
start, end, nextOffset, hasMore := shared.Window(len(candidates), input.Page)
|
||||
out := Output{Items: append([]Item(nil), candidates[start:end]...)}
|
||||
if hasMore {
|
||||
out.NextPageToken = shared.EncodeToken(nextOffset)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// lookupGame returns the host game's name and type. A missing game
|
||||
// record is logged at warn and the application is silently dropped from
|
||||
// the list — surfacing a 500 to the user for a dangling reference would
|
||||
// be a worse experience and the operator alert is more useful.
|
||||
func (service *Service) lookupGame(
|
||||
ctx context.Context,
|
||||
gameID common.GameID,
|
||||
applicationID common.ApplicationID,
|
||||
) (name string, gameType game.GameType, ok bool) {
|
||||
record, err := service.games.Get(ctx, gameID)
|
||||
if err == nil {
|
||||
return record.GameName, record.GameType, true
|
||||
}
|
||||
if errors.Is(err, game.ErrNotFound) {
|
||||
service.logger.WarnContext(ctx, "application references missing game",
|
||||
"application_id", applicationID.String(),
|
||||
"game_id", gameID.String(),
|
||||
)
|
||||
return "", "", false
|
||||
}
|
||||
service.logger.ErrorContext(ctx, "load application game",
|
||||
"application_id", applicationID.String(),
|
||||
"game_id", gameID.String(),
|
||||
"err", err.Error(),
|
||||
)
|
||||
return "", "", false
|
||||
}
|
||||
|
||||
// sortItems orders applications by CreatedAt descending so the most
|
||||
// recent appears first; ApplicationID breaks ties for stable output.
|
||||
func sortItems(items []Item) {
|
||||
sort.Slice(items, func(i, j int) bool {
|
||||
ci, cj := items[i].Application.CreatedAt, items[j].Application.CreatedAt
|
||||
if !ci.Equal(cj) {
|
||||
return ci.After(cj)
|
||||
}
|
||||
return items[i].Application.ApplicationID < items[j].Application.ApplicationID
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,193 @@
|
||||
package listmyapplications_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"log/slog"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"galaxy/lobby/internal/adapters/applicationstub"
|
||||
"galaxy/lobby/internal/adapters/gamestub"
|
||||
"galaxy/lobby/internal/domain/application"
|
||||
"galaxy/lobby/internal/domain/common"
|
||||
"galaxy/lobby/internal/domain/game"
|
||||
"galaxy/lobby/internal/ports"
|
||||
"galaxy/lobby/internal/service/listmyapplications"
|
||||
"galaxy/lobby/internal/service/shared"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func silentLogger() *slog.Logger {
|
||||
return slog.New(slog.NewTextHandler(io.Discard, nil))
|
||||
}
|
||||
|
||||
type fixture struct {
|
||||
games *gamestub.Store
|
||||
applications *applicationstub.Store
|
||||
svc *listmyapplications.Service
|
||||
}
|
||||
|
||||
func newFixture(t *testing.T) *fixture {
|
||||
t.Helper()
|
||||
games := gamestub.NewStore()
|
||||
apps := applicationstub.NewStore()
|
||||
svc, err := listmyapplications.NewService(listmyapplications.Dependencies{
|
||||
Games: games,
|
||||
Applications: apps,
|
||||
Logger: silentLogger(),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
return &fixture{games: games, applications: apps, svc: svc}
|
||||
}
|
||||
|
||||
func seedGame(
|
||||
t *testing.T,
|
||||
store *gamestub.Store,
|
||||
id common.GameID,
|
||||
gameType game.GameType,
|
||||
name string,
|
||||
now time.Time,
|
||||
) {
|
||||
t.Helper()
|
||||
owner := ""
|
||||
if gameType == game.GameTypePrivate {
|
||||
owner = "user-owner"
|
||||
}
|
||||
record, err := game.New(game.NewGameInput{
|
||||
GameID: id,
|
||||
GameName: name,
|
||||
GameType: gameType,
|
||||
OwnerUserID: owner,
|
||||
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)
|
||||
require.NoError(t, store.Save(context.Background(), record))
|
||||
}
|
||||
|
||||
func seedApplication(
|
||||
t *testing.T,
|
||||
store *applicationstub.Store,
|
||||
id common.ApplicationID,
|
||||
gameID common.GameID,
|
||||
userID string,
|
||||
status application.Status,
|
||||
createdAt time.Time,
|
||||
) {
|
||||
t.Helper()
|
||||
record, err := application.New(application.NewApplicationInput{
|
||||
ApplicationID: id,
|
||||
GameID: gameID,
|
||||
ApplicantUserID: userID,
|
||||
RaceName: "Race-" + userID,
|
||||
Now: createdAt,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, store.Save(context.Background(), record))
|
||||
if status != application.StatusSubmitted {
|
||||
require.NoError(t, store.UpdateStatus(context.Background(), ports.UpdateApplicationStatusInput{
|
||||
ApplicationID: id,
|
||||
ExpectedFrom: application.StatusSubmitted,
|
||||
To: status,
|
||||
At: createdAt.Add(time.Minute),
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleReturnsSubmittedOnly(t *testing.T) {
|
||||
t.Parallel()
|
||||
fix := newFixture(t)
|
||||
now := time.Date(2025, 6, 1, 12, 0, 0, 0, time.UTC)
|
||||
|
||||
seedGame(t, fix.games, "game-1", game.GameTypePublic, "Hyperion", now)
|
||||
seedGame(t, fix.games, "game-2", game.GameTypePublic, "Endymion", now)
|
||||
seedApplication(t, fix.applications, "application-submitted", "game-1", "user-1", application.StatusSubmitted, now)
|
||||
seedApplication(t, fix.applications, "application-rejected", "game-2", "user-1", application.StatusRejected, now)
|
||||
|
||||
out, err := fix.svc.Handle(context.Background(), listmyapplications.Input{
|
||||
Actor: shared.NewUserActor("user-1"),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.Len(t, out.Items, 1)
|
||||
require.Equal(t, common.ApplicationID("application-submitted"), out.Items[0].Application.ApplicationID)
|
||||
require.Equal(t, "Hyperion", out.Items[0].GameName)
|
||||
require.Equal(t, game.GameTypePublic, out.Items[0].GameType)
|
||||
}
|
||||
|
||||
func TestHandleAdminForbidden(t *testing.T) {
|
||||
t.Parallel()
|
||||
fix := newFixture(t)
|
||||
_, err := fix.svc.Handle(context.Background(), listmyapplications.Input{
|
||||
Actor: shared.NewAdminActor(),
|
||||
})
|
||||
require.ErrorIs(t, err, shared.ErrForbidden)
|
||||
}
|
||||
|
||||
func TestHandleSkipsApplicationsWithMissingGame(t *testing.T) {
|
||||
t.Parallel()
|
||||
fix := newFixture(t)
|
||||
now := time.Date(2025, 6, 1, 12, 0, 0, 0, time.UTC)
|
||||
// Note: seed only application-1's game; application-2 will reference a missing game.
|
||||
seedGame(t, fix.games, "game-1", game.GameTypePublic, "G1", now)
|
||||
seedApplication(t, fix.applications, "application-1", "game-1", "user-1", application.StatusSubmitted, now)
|
||||
seedApplication(t, fix.applications, "application-2", "game-missing", "user-1", application.StatusSubmitted, now)
|
||||
|
||||
out, err := fix.svc.Handle(context.Background(), listmyapplications.Input{
|
||||
Actor: shared.NewUserActor("user-1"),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.Len(t, out.Items, 1)
|
||||
require.Equal(t, common.ApplicationID("application-1"), out.Items[0].Application.ApplicationID)
|
||||
}
|
||||
|
||||
func TestHandlePagination(t *testing.T) {
|
||||
t.Parallel()
|
||||
fix := newFixture(t)
|
||||
now := time.Date(2025, 6, 1, 12, 0, 0, 0, time.UTC)
|
||||
for i := range 4 {
|
||||
gid := common.GameID("game-page-" + string(rune('a'+i)))
|
||||
seedGame(t, fix.games, gid, game.GameTypePublic, "G", now)
|
||||
seedApplication(t, fix.applications,
|
||||
common.ApplicationID("application-page-"+string(rune('a'+i))),
|
||||
gid, "user-1", application.StatusSubmitted,
|
||||
now.Add(time.Duration(i)*time.Minute),
|
||||
)
|
||||
}
|
||||
|
||||
first, err := fix.svc.Handle(context.Background(), listmyapplications.Input{
|
||||
Actor: shared.NewUserActor("user-1"),
|
||||
Page: shared.Page{Size: 2},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.Len(t, first.Items, 2)
|
||||
require.NotEmpty(t, first.NextPageToken)
|
||||
// Most recent first.
|
||||
require.Equal(t, common.ApplicationID("application-page-d"), first.Items[0].Application.ApplicationID)
|
||||
require.Equal(t, common.ApplicationID("application-page-c"), first.Items[1].Application.ApplicationID)
|
||||
}
|
||||
|
||||
func TestNewServiceRejectsMissingDeps(t *testing.T) {
|
||||
t.Parallel()
|
||||
cases := []struct {
|
||||
name string
|
||||
deps listmyapplications.Dependencies
|
||||
}{
|
||||
{"nil games", listmyapplications.Dependencies{Applications: applicationstub.NewStore()}},
|
||||
{"nil applications", listmyapplications.Dependencies{Games: gamestub.NewStore()}},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
_, err := listmyapplications.NewService(tc.deps)
|
||||
require.Error(t, err)
|
||||
})
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user