Files
galaxy-game/lobby/internal/service/updategame/service.go
T
2026-04-25 23:20:55 +02:00

236 lines
6.4 KiB
Go

// Package updategame implements the `lobby.game.update` message type. It
// applies partial edits to a game record under the following rules:
//
// - in status `draft`: any field from the request schema is mutable;
// - in status `enrollment_open`: only `description` is mutable;
// - in every other status: no field is mutable and the call returns
// game.ErrConflict.
//
// Authorization is admin OR (user + private game + matching OwnerUserID).
// Non-owners receive shared.ErrForbidden.
package updategame
import (
"context"
"errors"
"fmt"
"log/slog"
"time"
"galaxy/lobby/internal/domain/common"
"galaxy/lobby/internal/domain/game"
"galaxy/lobby/internal/ports"
"galaxy/lobby/internal/service/shared"
)
// Service executes the update-game use case.
type Service struct {
games ports.GameStore
clock func() time.Time
logger *slog.Logger
}
// Dependencies groups the collaborators used by Service.
type Dependencies struct {
// Games persists the updated record.
Games ports.GameStore
// 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
}
// NewService constructs one Service with deps.
func NewService(deps Dependencies) (*Service, error) {
if deps.Games == nil {
return nil, errors.New("new update game service: nil game store")
}
clock := deps.Clock
if clock == nil {
clock = time.Now
}
logger := deps.Logger
if logger == nil {
logger = slog.Default()
}
return &Service{
games: deps.Games,
clock: clock,
logger: logger.With("service", "lobby.updategame"),
}, nil
}
// Input stores the arguments required to update one game record. Every
// mutable field is represented by a pointer so callers can distinguish
// "absent" from the zero value.
type Input struct {
// Actor identifies the caller.
Actor shared.Actor
// GameID identifies the record to update.
GameID common.GameID
// GameName updates the human-readable game name when non-nil.
GameName *string
// Description updates the human-readable description when non-nil.
Description *string
// MinPlayers updates the minimum approved participant count when
// non-nil.
MinPlayers *int
// MaxPlayers updates the target roster size when non-nil.
MaxPlayers *int
// StartGapHours updates the gap window length in hours when non-nil.
StartGapHours *int
// StartGapPlayers updates the gap window additional participant count
// when non-nil.
StartGapPlayers *int
// EnrollmentEndsAt updates the enrollment deadline when non-nil.
EnrollmentEndsAt *time.Time
// TurnSchedule updates the cron expression when non-nil.
TurnSchedule *string
// TargetEngineVersion updates the engine semver when non-nil.
TargetEngineVersion *string
}
// HasNonDescriptionFields reports whether input carries any mutation other
// than Description.
func (input Input) HasNonDescriptionFields() bool {
return input.GameName != nil ||
input.MinPlayers != nil ||
input.MaxPlayers != nil ||
input.StartGapHours != nil ||
input.StartGapPlayers != nil ||
input.EnrollmentEndsAt != nil ||
input.TurnSchedule != nil ||
input.TargetEngineVersion != nil
}
// Handle validates, authorizes, and applies the partial update. It returns
// the persisted record on success.
func (service *Service) Handle(ctx context.Context, input Input) (game.Game, error) {
if service == nil {
return game.Game{}, errors.New("update game: nil service")
}
if ctx == nil {
return game.Game{}, errors.New("update game: nil context")
}
if err := input.Actor.Validate(); err != nil {
return game.Game{}, fmt.Errorf("update game: actor: %w", err)
}
if err := input.GameID.Validate(); err != nil {
return game.Game{}, fmt.Errorf("update game: %w", err)
}
record, err := service.games.Get(ctx, input.GameID)
if err != nil {
return game.Game{}, fmt.Errorf("update game: %w", err)
}
if err := authorize(input.Actor, record); err != nil {
return game.Game{}, err
}
if err := enforceStatusGate(record.Status, input); err != nil {
return game.Game{}, err
}
applyPatch(&record, input, service.clock().UTC())
if err := record.Validate(); err != nil {
return game.Game{}, fmt.Errorf("update game: %w", err)
}
if err := service.games.Save(ctx, record); err != nil {
return game.Game{}, fmt.Errorf("update game: %w", err)
}
service.logger.InfoContext(ctx, "game updated",
"game_id", record.GameID.String(),
"status", string(record.Status),
"actor_kind", string(input.Actor.Kind),
)
return record, 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 update game %q",
shared.ErrForbidden, record.GameID.String())
}
// enforceStatusGate returns game.ErrConflict when the request attempts a
// field mutation disallowed by the current status.
func enforceStatusGate(status game.Status, input Input) error {
switch status {
case game.StatusDraft:
return nil
case game.StatusEnrollmentOpen:
if input.HasNonDescriptionFields() {
return fmt.Errorf(
"update game: only description is editable in status %q: %w",
status, game.ErrConflict,
)
}
return nil
default:
return fmt.Errorf(
"update game: status %q does not accept field updates: %w",
status, game.ErrConflict,
)
}
}
// applyPatch overwrites non-nil fields from input onto record. Callers must
// re-validate the result before persisting.
func applyPatch(record *game.Game, input Input, now time.Time) {
if input.GameName != nil {
record.GameName = *input.GameName
}
if input.Description != nil {
record.Description = *input.Description
}
if input.MinPlayers != nil {
record.MinPlayers = *input.MinPlayers
}
if input.MaxPlayers != nil {
record.MaxPlayers = *input.MaxPlayers
}
if input.StartGapHours != nil {
record.StartGapHours = *input.StartGapHours
}
if input.StartGapPlayers != nil {
record.StartGapPlayers = *input.StartGapPlayers
}
if input.EnrollmentEndsAt != nil {
record.EnrollmentEndsAt = input.EnrollmentEndsAt.UTC()
}
if input.TurnSchedule != nil {
record.TurnSchedule = *input.TurnSchedule
}
if input.TargetEngineVersion != nil {
record.TargetEngineVersion = *input.TargetEngineVersion
}
record.UpdatedAt = now
}