domain

package
v0.5.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 18, 2026 License: MIT Imports: 17 Imported by: 0

Documentation

Overview

Package domain defines game-independent membership contracts and domain logic. Adapters depend on this package; this package never imports an adapter or backend.

Index

Constants

View Source
const (
	MinTeams = 2
	MaxTeams = 16
)

MinTeams and MaxTeams bound the number of teams in a lobby.

View Source
const EmptyGameSettings = "{}"

EmptyGameSettings is stored for a lobby created without game settings.

View Source
const InvalidationSchemaVersion = 1
View Source
const InvalidationType = "lobby.changed"
View Source
const JoinCodeAlphabet = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789"
View Source
const JoinCodeLength = 8
View Source
const MaxGameSettingsBytes = 16 * 1024

MaxGameSettingsBytes bounds the canonical settings stored with each lobby.

View Source
const MaxMemberSettingsBytes = 4 * 1024

MaxMemberSettingsBytes bounds the canonical settings stored with each member.

View Source
const MaxRetentionBatchSize = 1000

MaxRetentionBatchSize bounds BatchSize, so one pass stays short.

View Source
const MaxSeatSettingsBytes = 4 * 1024

MaxSeatSettingsBytes bounds the canonical settings stored with each seat.

View Source
const MaxWatchersPerLobby = 50

MaxWatchersPerLobby caps the watchers a lobby can have at once, kicked and departed ones left out. A new watcher beyond it is refused with watchers_full; one who already watches keeps their row. Raise or lower it here; see the lobby README.

Variables

View Source
var (
	ErrUnauthenticated     = NewError(CodeUnauthenticated, "authentication required")
	ErrNotFound            = NewError(CodeNotFound, "lobby not found")
	ErrNotHost             = NewError(CodeNotHost, "host required")
	ErrLobbyFull           = NewError(CodeLobbyFull, "lobby is full")
	ErrTeamFull            = NewError(CodeTeamFull, "team is full")
	ErrPhaseConflict       = NewError(CodePhaseConflict, "operation unavailable in this phase")
	ErrNotReady            = NewError(CodeNotReady, "members are not ready")
	ErrStaleMembership     = NewError(CodeStaleMembership, "membership or client lease is stale")
	ErrIdempotencyConflict = NewError(CodeIdempotencyConflict, "request ID was used with different input")
	ErrInvalidInput        = NewError(CodeInvalidInput, "invalid input")
	ErrUnavailable         = NewError(CodeUnavailable, "service temporarily unavailable")
	ErrGameRunning         = NewError(CodeGameRunning, "the lobby's game is still running")
	ErrGameUnavailable     = NewError(CodeGameUnavailable, "the lobby started, but its game could not be created; start it again to retry")
	ErrWatcherKicked       = NewError(CodeWatcherKicked, "the host removed you from this lobby's watchers")
	ErrWatchersFull        = NewError(CodeWatchersFull, "this lobby has as many watchers as it allows")
	ErrPermissionDenied    = NewError(CodePermissionDenied, "permission denied")
	// Internal storage sentinel, never returned directly through player HTTP.
	ErrJoinCodeCollision = errors.New("lobby join code collision")
)

Functions

func ActiveWatchers

func ActiveWatchers(aggregate *Aggregate) int

ActiveWatchers counts the watchers of the aggregate who may watch.

func CanWatch

func CanWatch(aggregate *Aggregate, playerID string) bool

CanWatch reports whether a player may watch the lobby: an active member, or a watcher the host hasn't kicked.

func CloseAbandoned

func CloseAbandoned(aggregate *Aggregate)

CloseAbandoned closes a waiting lobby whose last person left. Its seats leave with them, like members who left, so a closed lobby holds no active member.

func EffectiveLeaseExpiry

func EffectiveLeaseExpiry(lease Lease) time.Time

func ElectHost

func ElectHost(members []Member) *string

ElectHost returns a detached player UUID; inactive history and seats are never eligible.

func HasLiveLease

func HasLiveLease(leases []Lease, playerID string, generation int64, now time.Time) bool

func LatestEffectiveLeaseExpiry

func LatestEffectiveLeaseExpiry(leases []Lease, playerID string, generation int64) (time.Time, bool)

LatestEffectiveLeaseExpiry includes released current-generation leases. Missing leases return false, allowing callers to handle corrupt/incomplete state safely.

func LobbyFull

func LobbyFull(aggregate *Aggregate) bool

LobbyFull reports whether the lobby has as many active members, people and seats, as teams. A team holds at most one member, so a full lobby has no room for another.

func NormalizeGameSettings

func NormalizeGameSettings(settings json.RawMessage) (json.RawMessage, error)

NormalizeGameSettings returns settings as one compact JSON object with sorted keys, so requests that differ only in formatting or key order match. Omitted settings become an empty object. The lobby never reads the values.

func NormalizeJoinCode

func NormalizeJoinCode(code string) (string, error)

func NormalizeMemberSettings

func NormalizeMemberSettings(settings json.RawMessage) (json.RawMessage, error)

NormalizeMemberSettings returns a member's settings as one compact JSON object with sorted keys, as NormalizeSeatSettings does for a seat. Omitted settings are refused.

func NormalizeName

func NormalizeName(name string, maximum int) (string, error)

func NormalizeSeatSettings

func NormalizeSeatSettings(settings json.RawMessage) (json.RawMessage, error)

NormalizeSeatSettings returns a seat's settings as one compact JSON object with sorted keys. A seat needs settings, so omitted ones are refused.

func PlayerChannel

func PlayerChannel(playerID string) (string, error)

func RoomChannel

func RoomChannel(scope Scope) (string, error)

func TeamNameKey

func TeamNameKey(name string) string

TeamNameKey is Unicode default case folding after trimming. Persist this key for the database uniqueness constraint; preserve the original normalized label.

func TeamTaken

func TeamTaken(aggregate *Aggregate, teamID string) bool

TeamTaken reports whether an active member, a person or a seat, is on the team. A taken team has no room for another member.

func ValidateGameKey

func ValidateGameKey(key string) error

func ValidateUUID

func ValidateUUID(value string) error

ValidateUUID accepts canonical lowercase UUID text only, without coercion.

func WatchChannel

func WatchChannel(scope Scope) (string, error)

WatchChannel is the channel where a lobby's game publishes for watchers: watch:<game_key>:<lobby_id>.

func WatcherCount

func WatcherCount(watchers []Watcher) int

WatcherCount counts the watchers who may watch.

Types

type AddSeatRequest

type AddSeatRequest struct {
	RequestID    string          `json:"request_id,omitempty"`
	TeamID       string          `json:"team_id"`
	SeatSettings json.RawMessage `json:"seat_settings"`
}

AddSeatRequest adds a seat that no person plays to a team. SeatSettings is a JSON object that only the game reads, such as the level of the bot that plays the seat. RequestID, optional, makes a retry safe: repeating it with the same team and settings adds no second seat, and with others fails with idempotency_conflict.

type Aggregate

type Aggregate struct {
	Lobby       Lobby
	Teams       []Team
	Members     []Member
	Leases      []Lease
	StartRoster StartRoster
	// Watchers holds every watcher row, kicked ones included.
	Watchers []Watcher
}

func (Aggregate) DeepCopy

func (aggregate Aggregate) DeepCopy() Aggregate

DeepCopy detaches every slice/pointer and normalizes nil lists to empty lists.

type Application

type Application interface {
	Create(context.Context, Principal, CreateRequest) (Snapshot, error)
	Join(context.Context, Principal, JoinRequest) (Snapshot, error)
	Snapshot(context.Context, Principal, Scope) (Snapshot, error)
	SelectTeam(context.Context, Principal, Scope, SelectTeamRequest) (Snapshot, error)
	SetReady(context.Context, Principal, Scope, ReadyRequest) (Snapshot, error)
	Start(context.Context, Principal, Scope) (Snapshot, error)
	// Reopen brings a started lobby whose game ended back to waiting, for
	// its next round. Any active person may call it.
	Reopen(context.Context, Principal, Scope) (Snapshot, error)
	// ChangeSettings lets the host replace the game settings and the teams
	// while the lobby waits.
	ChangeSettings(context.Context, Principal, Scope, ChangeSettingsRequest) (Snapshot, error)
	// AddSeat and RemoveSeat let the host change the seats that no person
	// plays while the lobby waits. RemoveSeat takes the seat's member ID.
	AddSeat(context.Context, Principal, Scope, AddSeatRequest) (Snapshot, error)
	RemoveSeat(context.Context, Principal, Scope, string) (Snapshot, error)
	// SetMemberSettings sets the caller's own member settings while the
	// lobby waits.
	SetMemberSettings(context.Context, Principal, Scope, MemberSettingsRequest) (Snapshot, error)
	Leave(context.Context, Principal, Scope) error
	Heartbeat(context.Context, Principal, Scope, HeartbeatRequest) (HeartbeatResult, error)
	ReleaseLease(context.Context, Principal, Scope, ReleaseLeaseRequest) error
	// Watch, Unwatch, Watchers and KickWatcher manage the people who watch a
	// lobby with its join code without taking a seat.
	Watch(context.Context, Principal, WatchRequest) (WatchAccess, error)
	Unwatch(context.Context, Principal, Scope) error
	Watchers(context.Context, Principal, Scope) ([]Watcher, error)
	KickWatcher(context.Context, Principal, Scope, string) error
}

type Authenticator

type Authenticator interface {
	CreateGuest(context.Context, CreateGuestRequest) (GuestSession, error)
	// Authenticate receives the complete Authorization header and parses strict Bearer.
	Authenticate(context.Context, string) (SessionVerification, error)
}

type Change

type Change struct {
	PublicChanged  bool
	PrivateChanged bool
	Revocations    []RevocationIntent
}

Change classifies persistence. Either flag or an intent requires persistence; only PublicChanged increments the room version and emits an invalidation.

func MergeChanges

func MergeChanges(changes ...Change) Change

MergeChanges preserves first-seen intent order while deduplicating exactly by scope, player and generation; distinct departures are never merged together.

func NormalizeExpired

func NormalizeExpired(aggregate *Aggregate, now time.Time, policy Policy) (Change, error)

NormalizeExpired derives visible connection state from durable current-generation leases. The caller holds the room lock; the store assigns versions and events.

func (Change) HasWrites

func (change Change) HasWrites() bool

type ChangePublisher

type ChangePublisher interface {
	PublishChange(ctx context.Context, room Lobby, change Change, stillDue RevocationCheck) error
}

ChangePublisher pushes a committed change to subscribers right after its transaction: one Invalidation carrying the room's version when PublicChanged, and an unsubscribe from the room channel for each revocation that stillDue confirms right before each attempt. It retries briefly and logs what still fails. The commit stands either way, and clients recover by re-reading the lobby over HTTP.

type ChangeSettingsRequest

type ChangeSettingsRequest struct {
	Teams        []TeamDefinition
	GameSettings json.RawMessage
}

ChangeSettingsRequest replaces a waiting lobby's game settings and teams, with the same rules as a create request's. The lobby's teams are rebuilt by position: the first definition renames the lobby's first team, and so on.

type Channel

type Channel struct {
	Namespace ChannelNamespace
	Scope     Scope
	PlayerID  string
}

func ParseChannel

func ParseChannel(value string) (Channel, error)

type ChannelNamespace

type ChannelNamespace string
const (
	ChannelLobby  ChannelNamespace = "lobby"
	ChannelPlayer ChannelNamespace = "player"
	// ChannelWatch carries a lobby's game to its watchers and members. The
	// lobby authorizes it; the game decides what it publishes there.
	ChannelWatch ChannelNamespace = "watch"
)

type Clock

type Clock interface{ Now() time.Time }

type ConnectionToken

type ConnectionToken struct {
	Token        string    `json:"token"`
	ExpiresAt    time.Time `json:"expires_at"`
	WebsocketURL string    `json:"websocket_url"`
}

type ConnectionTokenIssuer

type ConnectionTokenIssuer interface {
	IssueConnectionToken(context.Context, SessionVerification) (ConnectionToken, error)
}

type CreateGuestRequest

type CreateGuestRequest struct {
	DisplayName string `json:"display_name"`
}

type CreateRequest

type CreateRequest struct {
	RequestID        string           `json:"request_id"`
	GameKey          string           `json:"game_key"`
	Name             string           `json:"name"`
	Teams            []TeamDefinition `json:"teams"`
	ClientInstanceID string           `json:"client_instance_id"`
	// GameSettings is an optional JSON object that only the game reads.
	// omitempty keeps the create fingerprint of a request without settings the
	// same as before settings existed.
	GameSettings json.RawMessage `json:"game_settings,omitempty"`
}

type CredentialHash

type CredentialHash [32]byte

CredentialHash is a SHA-256 bearer digest, never the raw bearer.

type CryptoIdentifiers

type CryptoIdentifiers struct{}

CryptoIdentifiers uses the operating system's cryptographic random source. Importing the package does not read randomness; each method reads on demand.

func (CryptoIdentifiers) Bytes

func (CryptoIdentifiers) Bytes(count int) ([]byte, error)

func (CryptoIdentifiers) JoinCode

func (CryptoIdentifiers) JoinCode() (string, error)

func (CryptoIdentifiers) UUID

func (source CryptoIdentifiers) UUID() (string, error)

type Error

type Error struct {
	Code    ErrorCode
	Message string
	// TeamIDs names the teams an error is about, such as the empty teams of
	// CodeEmptyTeams. They are safe to show the client.
	TeamIDs []string
	// Type is the game-defined problem type of CodeGameRequirement, a URI
	// such as urn:example:problem:choice-missing. It is safe to show
	// the client.
	Type  string
	Cause error
}

Error exposes a safe message and stable code. Cause is for internal diagnosis; HTTP adapters must never serialize Cause or an arbitrary wrapped error.

func GameRequirement

func GameRequirement(problemType, message string) *Error

GameRequirement is a game's refusal to let a member get ready, or a lobby start, for a ReadyCheck to return. problemType is a URI that names the game's problem, and message tells the player what to do; both are shown to the client.

func NewError

func NewError(code ErrorCode, message string) *Error

func (*Error) Error

func (err *Error) Error() string

func (*Error) Is

func (err *Error) Is(target error) bool

func (*Error) Unwrap

func (err *Error) Unwrap() error

type ErrorCode

type ErrorCode string
const (
	CodeUnauthenticated     ErrorCode = "unauthenticated"
	CodeNotFound            ErrorCode = "not_found"
	CodeNotHost             ErrorCode = "not_host"
	CodeLobbyFull           ErrorCode = "lobby_full"
	CodeTeamFull            ErrorCode = "team_full"
	CodePhaseConflict       ErrorCode = "phase_conflict"
	CodeNotReady            ErrorCode = "not_ready"
	CodeEmptyTeams          ErrorCode = "empty_teams"
	CodeStaleMembership     ErrorCode = "stale_membership"
	CodeIdempotencyConflict ErrorCode = "idempotency_conflict"
	CodeInvalidInput        ErrorCode = "invalid_input"
	CodeInvalidGameSettings ErrorCode = "invalid_game_settings"
	CodeInvalidSeatSettings ErrorCode = "invalid_seat_settings"
	// CodeInvalidMemberSettings refuses member settings that the game
	// doesn't accept, and every value for a game that takes none.
	CodeInvalidMemberSettings ErrorCode = "invalid_member_settings"
	// CodeGameRequirement is a game's own refusal, from its ReadyGate. The
	// error's Type names the game's problem.
	CodeGameRequirement ErrorCode = "game_requirement"
	// CodeGameRunning refuses to reopen a started lobby whose game hasn't
	// ended.
	CodeGameRunning ErrorCode = "game_running"
	// CodeGameUnavailable reports that a lobby started but its game could
	// not create the round's game. The lobby stays started, and the host
	// starts it again to retry.
	CodeGameUnavailable ErrorCode = "game_unavailable"
	CodeUnavailable     ErrorCode = "unavailable"
	// CodeWatcherKicked refuses a watcher whom the host kicked from the lobby.
	CodeWatcherKicked ErrorCode = "watcher_kicked"
	// CodeWatchersFull refuses a new watcher once the lobby has
	// MaxWatchersPerLobby of them.
	CodeWatchersFull ErrorCode = "watchers_full"
	// PermissionDenied is private proxy authorization only, not a player API code.
	CodePermissionDenied ErrorCode = "permission_denied"
)

func ErrorCodeOf

func ErrorCodeOf(err error) ErrorCode

type GameAPI

type GameAPI interface {
	GameSnapshot(context.Context, Scope) (Snapshot, error)
	AuthorizeGameWatch(ctx context.Context, scope Scope, playerID string) error
}

GameAPI is what a game reads from the lobby over the signed game API, in place of SnapshotReader and WatchAuthorizer, which need the lobby in the game's process. GameSnapshot returns the lobby as the game sees it (BuildGameSnapshot), or ErrNotFound. AuthorizeGameWatch checks that a player may watch the lobby, as AuthorizeWatch does: ErrWatcherKicked for a watcher the host kicked, ErrNotFound for anyone else.

type GameOverCheck

type GameOverCheck func(ctx context.Context, lobbyID string, round int64) (bool, error)

GameOverCheck reports whether the game that a started lobby plays in round is over. The lobby calls it with the lobby's ID before the transaction of a reopen request, so the game never reads its data while the lobby holds the room's lock. A game that has ended must stay ended. A game should also report a round whose start never created a game as over, so that the lobby can't be stuck.

To report that the check itself could not run, return the context's error or an error wrapping ErrUnavailable; any other error is reported as unavailable too.

type GameRegistration

type GameRegistration struct {
	// Key is the canonical game key used in requests, URLs and channels.
	Key string
	// ValidateSettings checks the game settings of a create or settings
	// change request. Nil means the game takes no settings and accepts only an
	// empty object.
	ValidateSettings GameSettingsValidator
	// StartRules adds start conditions to the lobby's default ones.
	StartRules StartRules
	// Retention overrides when the game's lobbies are deleted. Each zero
	// period keeps the policy's default.
	Retention LobbyRetention
	// ReadyGate lets the game keep members from getting ready, and a lobby
	// from starting, until they meet a condition of the game's own. Nil adds
	// no condition.
	ReadyGate ReadyGate
	// ValidateSeat checks the seat settings of a seat that the host adds to a
	// team, such as the level of the game's bot that plays it, and names the
	// seat. Nil means the game has no seats and refuses every one.
	ValidateSeat SeatValidator
	// ValidateMemberSettings checks the member settings that a person sets
	// for themselves in a waiting lobby, such as what plays for them. Nil
	// means the game takes no member settings and refuses every value.
	ValidateMemberSettings MemberSettingsValidator
	// GameOver tells whether the game of a lobby's round has ended, so that
	// the lobby can be reopened for its next round. Nil means the game's
	// lobbies play one game and are never reopened.
	GameOver GameOverCheck
	// StartGame creates the game of a lobby's round once the lobby has
	// committed its start, and again on a later start request while the game
	// hasn't confirmed one. Nil means the lobby calls nothing: the game binds
	// its own way, such as through application.GameBinding.
	StartGame GameStarter
}

GameRegistration declares one game that may use the lobby. Every field is a declaration the lobby applies without knowing the game, and a zero field keeps the lobby's default behavior, so new options are added as new fields.

func (GameRegistration) CheckGameOver

func (game GameRegistration) CheckGameOver(ctx context.Context, lobbyID string, round int64) (bool, error)

CheckGameOver asks the game whether the game of a lobby's round is over. Without a GameOver check, the lobby can't be reopened: it fails with ErrPhaseConflict. Errors of the check are reported as unavailable.

func (GameRegistration) CheckReady

func (game GameRegistration) CheckReady(ctx context.Context, lobbyID string) (ReadyCheck, error)

CheckReady loads the game's ready gate for a lobby, or returns nil when the game declares none. Its errors are reported as unavailable.

type GameSettingsValidator

type GameSettingsValidator func(ctx context.Context, lobbyID string, settings json.RawMessage, teams []TeamDefinition) error

GameSettingsValidator receives the settings of a create or settings change request as a canonical JSON object, `{}` when the request had none, with the lobby's ID, empty while the lobby is being created, and the request's validated teams in order, so settings can be checked against the lobby they configure. To reject them, return an error whose message is safe to show the client. To report that the check itself failed, return the context's error or an error wrapping ErrUnavailable.

type GameStarter

type GameStarter func(ctx context.Context, snapshot Snapshot) (gameID string, err error)

GameStarter receives the snapshot of a lobby that has just started, as the game reads it (domain.BuildGameSnapshot), and returns the ID of the game it created for the lobby's round. It must bind idempotently by lobby and round: a second call for the same round returns the same game. Any error is reported as game_unavailable, and the lobby stays started, so that the host can retry.

type GuestSession

type GuestSession struct {
	PlayerID    string    `json:"player_id"`
	AccessToken string    `json:"access_token"`
	ExpiresAt   time.Time `json:"expires_at"`
}

type HeartbeatRequest

type HeartbeatRequest struct {
	ClientInstanceID     string `json:"client_instance_id"`
	MembershipGeneration int64  `json:"membership_generation"`
}

type HeartbeatResult

type HeartbeatResult struct {
	Version              int64      `json:"version"`
	MembershipGeneration int64      `json:"membership_generation"`
	LeaseExpiresAt       time.Time  `json:"lease_expires_at"`
	DisconnectedUntil    *time.Time `json:"disconnected_until"`
}

type IdentifierSource

type IdentifierSource interface {
	UUID() (string, error)
	JoinCode() (string, error)
	Bytes(int) ([]byte, error)
}

type IdentityStore

type IdentityStore interface {
	CreateGuest(context.Context, Player, Session) error
	LookupByBearerHash(context.Context, CredentialHash) (*SessionVerification, error)
	LookupByPlayer(context.Context, string) (*SessionVerification, error)
}

IdentityStore creates player and unique player session atomically. Optional lookups return (nil,nil) only when absent; storage errors are never absence.

type Invalidation

type Invalidation struct {
	SchemaVersion int    `json:"schema_version"`
	EventID       string `json:"event_id"`
	GameKey       string `json:"game_key"`
	LobbyID       string `json:"lobby_id"`
	Version       int64  `json:"version"`
	Type          string `json:"type"`
}

type JoinRequest

type JoinRequest struct {
	GameKey          string `json:"game_key"`
	JoinCode         string `json:"join_code"`
	ClientInstanceID string `json:"client_instance_id"`
}

type Lease

type Lease struct {
	LobbyID          string     `json:"lobby_id"`
	PlayerID         string     `json:"player_id"`
	Generation       int64      `json:"generation"`
	ClientInstanceID string     `json:"client_instance_id"`
	ExpiresAt        time.Time  `json:"expires_at"`
	ReleasedAt       *time.Time `json:"released_at"`
}

func FindLease

func FindLease(aggregate *Aggregate, playerID string, generation int64, clientID string) *Lease

type Lobby

type Lobby struct {
	ID       string `json:"id"`
	GameKey  string `json:"game_key"`
	Name     string `json:"name"`
	JoinCode string `json:"join_code"`
	// Capacity is the number of teams, which is the number of members the
	// lobby holds, since a team holds at most one member.
	Capacity int   `json:"capacity"`
	Phase    Phase `json:"phase"`
	// Round numbers the lobby's games, from 1. Reopening a started lobby
	// after its game ended raises it by one and makes the lobby wait again,
	// so a game tells the lobby's games apart by lobby and round.
	Round        int64     `json:"round"`
	Version      int64     `json:"version"`
	HostPlayerID *string   `json:"host_player_id"`
	CreatedAt    time.Time `json:"created_at"`
	// GameSettings is the canonical JSON object chosen at creation. The host
	// can replace it, with the teams, while the lobby waits. The lobby stores
	// it without reading it.
	GameSettings json.RawMessage `json:"game_settings"`
	// NextJoinSequence is persisted, including when older memberships deactivate.
	NextJoinSequence int64 `json:"-"`
	// LastConnectedAt is the last time a client showed it was connected, by
	// creating, joining, heartbeating, releasing a lease or leaving. The
	// retention pass deletes the lobby once it is older than the idle period.
	LastConnectedAt time.Time `json:"-"`
	// RoundStartedAt is when the lobby's current round began: its creation
	// for round 1, and the time of the last reopen for later rounds. The
	// retention pass counts the maximum age from it. It is not part of the
	// public snapshot.
	RoundStartedAt time.Time `json:"-"`
	// BoundRound is the last round whose game the game's StartGame hook
	// confirmed, or 0 for none. A started lobby whose BoundRound is behind
	// its Round has no game yet, so a new start request calls the hook again.
	// It is not part of the public snapshot.
	BoundRound int64 `json:"-"`
}

func (*Lobby) MarkConnected

func (room *Lobby) MarkConnected(now time.Time)

MarkConnected records that a client was connected at now. It never moves the time back, so a slower clock on another instance can't shorten it.

func (Lobby) Scope

func (room Lobby) Scope() Scope

type LobbyCutoffs

type LobbyCutoffs struct {
	GameKey            string
	IdleBefore         time.Time
	RoundStartedBefore time.Time
}

LobbyCutoffs delete a game's lobbies that nobody has been connected to since IdleBefore, and those whose current round started before RoundStartedBefore: the round starts at the lobby's creation, or the last time it was reopened.

type LobbyRetention

type LobbyRetention struct {
	// IdlePeriod runs from the last time any member was connected.
	IdlePeriod time.Duration
	// MaximumAge runs from the start of the lobby's current round: its
	// creation, or the last time it was reopened. It applies even to a lobby
	// in use.
	MaximumAge time.Duration
}

LobbyRetention says when a lobby is deleted, in any phase. A game can override either period in its registration; a zero field keeps the default.

type Member

type Member struct {
	ID                string     `json:"id"`
	PlayerID          string     `json:"player_id"`
	DisplayName       string     `json:"display_name"`
	Generation        int64      `json:"generation"`
	Active            bool       `json:"active"`
	TeamID            *string    `json:"team_id"`
	Ready             bool       `json:"ready"`
	JoinedAt          time.Time  `json:"joined_at"`
	JoinSequence      int64      `json:"join_sequence"`
	DisconnectedUntil *time.Time `json:"disconnected_until"`
	// Kind is MemberHuman, or MemberSeat for a seat that the host added. An
	// empty kind is a human.
	Kind MemberKind `json:"kind"`
	// SeatSettings is the canonical JSON object that the game checked when
	// the host added the seat, and nil for a human. The lobby stores it
	// without reading it.
	SeatSettings json.RawMessage `json:"seat_settings"`
	// MemberSettings is the canonical JSON object that the game checked when
	// the person last set their own settings for the game, such as what plays
	// for them, or nil when they set none. It stays when the person leaves and
	// rejoins, and when the lobby is reopened for its next round. The lobby
	// stores it without reading it.
	MemberSettings json.RawMessage `json:"member_settings"`
	// SeatRequestID is the request ID that added the seat, or empty when it
	// had none. It never leaves the lobby.
	SeatRequestID string `json:"-"`
}

func FindMember

func FindMember(aggregate *Aggregate, playerID string) *Member

FindMember and FindLease return pointers into the aggregate for locked mutation. Missing records return nil. FindLease never infers or bypasses generation checks.

func (Member) IsSeat

func (member Member) IsSeat() bool

IsSeat reports whether no person plays the member.

type MemberKind

type MemberKind string

MemberKind says who takes a member's place in the lobby.

const (
	// MemberHuman is a person with a guest session, who joined the lobby.
	MemberHuman MemberKind = "human"
	// MemberSeat is a seat that no person plays, such as a game's bot, which
	// the host added to a team. It is always ready, holds no lease and never
	// hosts, and the game plays it from its seat settings.
	MemberSeat MemberKind = "seat"
)

type MemberSettingsRequest

type MemberSettingsRequest struct {
	MemberSettings json.RawMessage `json:"member_settings"`
}

MemberSettingsRequest sets the caller's own member settings, a JSON object that only the game reads, such as what plays for them.

type MemberSettingsValidator

type MemberSettingsValidator func(ctx context.Context, lobbyID string, settings json.RawMessage) error

MemberSettingsValidator receives the member settings that a person sets for themselves in a lobby, as a canonical JSON object, with the lobby's ID. To reject them, return an error whose message is safe to show the client. To report that the check itself failed, return the context's error or an error wrapping ErrUnavailable.

type Mutation

type Mutation func(*Aggregate) (Change, error)

type Phase

type Phase string
const (
	PhaseWaiting Phase = "waiting"
	PhaseStarted Phase = "started"
	PhaseClosed  Phase = "closed"
)

type Player

type Player struct {
	ID          string
	DisplayName string
	CreatedAt   time.Time
}

type PlayerToken

type PlayerToken struct {
	Token     string    `json:"token"`
	ExpiresAt time.Time `json:"expires_at"`
}

PlayerToken is a short-lived signed token that tells one game who the player is; see the playertoken package.

type PlayerTokenIssuer

type PlayerTokenIssuer interface {
	// IssuePlayerToken signs a token for the verified session's player and
	// gameKey, a registered game; any other key is ErrNotFound.
	IssuePlayerToken(ctx context.Context, verification SessionVerification, gameKey string) (PlayerToken, error)
	PublicKeys() playertoken.JWKS
}

PlayerTokenIssuer signs the player tokens that games verify with the lobby's public keys, and publishes those keys.

type Policy

type Policy struct {
	HeartbeatInterval       time.Duration
	LeaseDuration           time.Duration
	GraceDuration           time.Duration
	SessionDuration         time.Duration
	ConnectionTokenDuration time.Duration
	SubscriptionDuration    time.Duration
	Retention               RetentionPolicy
	Games                   []GameRegistration
}

func DefaultPolicy

func DefaultPolicy(games ...GameRegistration) Policy

DefaultPolicy is explicit: the zero Policy is invalid, never silently defaulted.

func (Policy) Game

func (policy Policy) Game(key string) (GameRegistration, error)

Game returns the registration for a game key.

func (Policy) LobbyRetention

func (policy Policy) LobbyRetention(gameKey string) LobbyRetention

LobbyRetention returns the periods for a game's lobbies: the game's overrides, with the policy's defaults for the fields it leaves zero. A game that is no longer registered gets the defaults.

func (Policy) RetentionCutoffs

func (policy Policy) RetentionCutoffs(now time.Time) RetentionCutoffs

RetentionCutoffs derives the cutoffs of a pass that runs at now.

func (Policy) Validate

func (policy Policy) Validate() error

func (Policy) ValidateGame

func (policy Policy) ValidateGame(key string) error

func (Policy) ValidateGameSettings

func (policy Policy) ValidateGameSettings(ctx context.Context, gameKey, lobbyID string, settings json.RawMessage, teams []TeamDefinition) (json.RawMessage, error)

ValidateGameSettings normalizes settings and checks them with the game's validator against the lobby's validated teams. lobbyID is empty while the lobby is being created. It returns the canonical settings to store with the lobby.

func (Policy) ValidateMemberSettings

func (policy Policy) ValidateMemberSettings(ctx context.Context, gameKey, lobbyID string, settings json.RawMessage) (json.RawMessage, error)

ValidateMemberSettings normalizes a person's member settings and checks them with the game's validator for the lobby. It returns the canonical settings to store with the member. A game without a validator takes no member settings and refuses every value with CodeInvalidMemberSettings.

func (Policy) ValidateScope

func (policy Policy) ValidateScope(scope Scope) error

func (Policy) ValidateSeatSettings

func (policy Policy) ValidateSeatSettings(ctx context.Context, gameKey, lobbyID, playerID string, settings json.RawMessage) (json.RawMessage, string, error)

ValidateSeatSettings normalizes a seat's settings and checks them with the game's seat validator, for the player making the request. It returns the canonical settings to store with the seat and the seat's display name. A game without a seat validator has no seats and refuses every one with CodeInvalidSeatSettings.

type Principal

type Principal struct {
	PlayerID    string `json:"player_id"`
	SessionID   string `json:"-"`
	DisplayName string `json:"display_name"`
}

type ReadyCheck

type ReadyCheck func(members []ReadyMember, atStart bool) error

ReadyCheck reports whether members may be ready. It gets the one member who is getting ready, with atStart false, or the whole start roster in the lobby's member order, with atStart true, so a refusal at the start can name the members who must act, who are not the host who sees it. It returns nil, or an error from GameRequirement that names the game's problem type and says what to do. Any other error is reported as unavailable.

type ReadyGate

type ReadyGate func(ctx context.Context, lobbyID string) (ReadyCheck, error)

ReadyGate loads what a game needs to decide which members of a lobby may get ready. Each ReadyMember carries the member's settings, so a game that decides from them alone reads nothing and returns its check at once. The lobby calls the gate with the lobby's ID before the transaction of a request that sets a member ready or starts the lobby, so a game that does read data of its own never reads it while the lobby holds the room's lock. The returned ReadyCheck then runs inside the transaction, for the member getting ready or for every member of the start roster. Data the gate read first may be stale by then, so a member must keep meeting a condition on that data once they do, for as long as the lobby is waiting.

To report that the gate itself could not run, return the context's error or an error wrapping ErrUnavailable; any other error is reported as unavailable too.

type ReadyMember

type ReadyMember struct {
	PlayerID    string
	DisplayName string
	// Settings are the member's member settings, the canonical JSON object
	// that the game checked when they set it, or nil when they set none.
	Settings json.RawMessage
}

ReadyMember is a member that a ReadyCheck decides about.

type ReadyRequest

type ReadyRequest struct {
	Ready bool `json:"ready"`
}

HTTP adapters must reject omitted ready; false is a valid explicit value.

type ReleaseLeaseRequest

type ReleaseLeaseRequest struct {
	ClientInstanceID     string `json:"client_instance_id"`
	MembershipGeneration int64  `json:"membership_generation"`
}

type RetentionCutoffs

type RetentionCutoffs struct {
	BatchSize int
	// CreateRequestsBefore deletes create requests made before it.
	CreateRequestsBefore time.Time
	// SessionsExpiredBefore deletes sessions that expired before it.
	SessionsExpiredBefore time.Time
	// PlayersCreatedBefore limits which players are checked for references.
	// A player whose session was deleted was created before it, so younger
	// players are skipped without being checked.
	PlayersCreatedBefore time.Time
	// Games holds one entry per registered game.
	Games []LobbyCutoffs
	// OtherGames applies to lobbies of games that are no longer registered.
	OtherGames LobbyCutoffs
}

RetentionCutoffs are the instants before which a pass deletes data, all derived from one clock reading.

type RetentionPolicy

type RetentionPolicy struct {
	// CreateRequests is the idempotency window of a create request: a retry
	// inside it replays the original response, and the record is deleted after.
	CreateRequests time.Duration
	// ExpiredSessions is how long an expired session is kept before it is
	// deleted, which covers requests that verified it just before it expired.
	ExpiredSessions time.Duration
	// Lobbies is the default for games that don't override it.
	Lobbies LobbyRetention
	// BatchSize bounds the rows one pass deletes from each kind of data.
	BatchSize int
	// PassInterval is the least time between two passes in one process while
	// the previous pass found no backlog.
	PassInterval time.Duration
}

RetentionPolicy says when the retention pass deletes lobby data and how much work one pass may do. Nothing is deleted before its period has passed.

func DefaultRetention

func DefaultRetention() RetentionPolicy

DefaultRetention keeps create requests for a day, expired sessions for an hour, and lobbies for an hour after their last connection or a day after the start of their current round: their creation, or the last time they were reopened. A pass deletes at most 50 rows of each kind, at most once a minute per process unless the previous pass found more to delete.

type RetentionResult

type RetentionResult struct {
	CreateRequests int
	Sessions       int
	Lobbies        int
	Players        int
}

RetentionResult counts what one pass deleted. Players counts the players no longer referenced by anything, and Lobbies the rooms with their child rows.

func (RetentionResult) Backlog

func (result RetentionResult) Backlog(batchSize int) bool

Backlog reports whether a kind of data filled its batch, so more may wait.

type RetentionRunner

type RetentionRunner interface {
	RunIfDue(context.Context)
}

RetentionRunner runs a retention pass at the end of a request when one is due. It reports failures itself and never fails the request.

type RetentionStore

type RetentionStore interface {
	DeleteExpired(context.Context, RetentionCutoffs) (RetentionResult, error)
}

RetentionStore deletes lobby data past its cutoffs, at most cutoffs.BatchSize rows of each kind, each kind in its own short transaction. It skips rows another transaction holds, so it never waits on a lobby in use, and deletes a room's child rows before the room.

type RevocationCheck

type RevocationCheck func(context.Context, RevocationIntent) (bool, error)

RevocationCheck reports whether a committed revocation still applies. It is false once the player holds a newer active membership, so a late unsubscribe never drops the subscription of a player who rejoined meanwhile.

type RevocationIntent

type RevocationIntent struct {
	PlayerID   string `json:"player_id"`
	Scope      Scope  `json:"scope"`
	Generation int64  `json:"generation"`
	Watch      bool   `json:"watch"`
}

RevocationIntent unsubscribes a player from the room channel once the change that deactivated this membership generation has committed. With Watch set, it unsubscribes a watcher who left or was kicked from the watch channel instead, and Generation is 0.

type Scope

type Scope struct {
	GameKey string `json:"game_key"`
	LobbyID string `json:"lobby_id"`
}

type SeatValidator

type SeatValidator func(ctx context.Context, lobbyID, playerID string, settings json.RawMessage) (displayName string, err error)

SeatValidator receives the settings of a seat that the host adds, as a canonical JSON object, with the lobby's ID and the ID of the player making the request, and returns the display name that the lobby shows for the seat, such as "Bot (level 2)". The lobby checks that the player is the host of a waiting lobby only afterwards, inside its transaction, so a game that ties a seat to a player compares the player it names with playerID and leaves the host check to the lobby. To reject the settings, return an error whose message is safe to show the client. To report that the check itself failed, return the context's error or an error wrapping ErrUnavailable.

type SelectTeamRequest

type SelectTeamRequest struct {
	TeamID *string `json:"team_id"`
}

HTTP adapters must reject omitted team_id before constructing this request. TeamID=nil means an explicit request to clear the selected team.

type Session

type Session struct {
	ID         string
	PlayerID   string
	BearerHash CredentialHash
	CreatedAt  time.Time
	ExpiresAt  time.Time
}

type SessionVerification

type SessionVerification struct {
	Principal Principal
	ExpiresAt time.Time
}

SessionVerification carries stored identity and expiry. Callers must verify now < ExpiresAt; a repository lookup alone is not authentication.

type Snapshot

type Snapshot struct {
	Lobby                Lobby       `json:"lobby"`
	Teams                []Team      `json:"teams"`
	Members              []Member    `json:"members"`
	StartRoster          StartRoster `json:"start_roster"`
	MembershipGeneration int64       `json:"membership_generation"`
	Channel              string      `json:"channel"`
	// StartRules are the game's declared start conditions. The service fills
	// them from the policy; snapshots built elsewhere leave them zero.
	StartRules StartRules `json:"start_rules"`
	// WatcherCount counts the watchers who may watch, kicked ones left out.
	WatcherCount int `json:"watcher_count"`
}

func BuildGameSnapshot

func BuildGameSnapshot(aggregate Aggregate) (Snapshot, error)

BuildGameSnapshot is the snapshot that a lobby's game reads, through the start hook or the game API: the view of every member, with no player behind it, so MembershipGeneration is 0. Callers apply deadline normalization first, as for BuildSnapshot.

func BuildSnapshot

func BuildSnapshot(aggregate Aggregate, playerID string) (Snapshot, error)

BuildSnapshot constructs a detached, ordered authorized view from the committed aggregate. Deadline normalization must precede this helper under the store lock.

type SnapshotReader

type SnapshotReader interface {
	Snapshot(context.Context, Principal, Scope) (Snapshot, error)
}

SnapshotReader authorizes current membership and returns a detached snapshot. Application implements this boundary, including expiry normalization.

type StartRoster

type StartRoster []StartRosterEntry

type StartRosterEntry

type StartRosterEntry struct {
	PlayerID  string `json:"player_id"`
	TeamID    string `json:"team_id"`
	MemberID  string `json:"member_id"`
	TeamOrder int    `json:"team_order"`
}

type StartRules

type StartRules struct {
	// EveryTeamNeedsMember refuses to start while a team has no member.
	EveryTeamNeedsMember bool `json:"every_team_needs_member"`
}

StartRules are conditions a game declares for starting its lobbies, on top of the default that at least two members are ready and every active member has chosen a team. The zero value adds none. Snapshots carry them, so clients can explain why a lobby can't start yet.

func (StartRules) Check

func (rules StartRules) Check(teams []Team, roster StartRoster) error

Check reports the first rule that the frozen roster breaks. An empty team fails with CodeEmptyTeams, whose TeamIDs list the empty teams in order.

type Store

Store returns detached copies. Transact locks the room before loading children, invokes Mutation exactly once, and atomically persists its changes. Callback errors roll back. PublicChanged increments version exactly once. A store never calls the network; ChangePublisher pushes committed changes. Create returns the saved original snapshot on an identical idempotent replay. A join-code unique collision returns ErrJoinCodeCollision for bounded retry.

type SubscriptionAuthorization

type SubscriptionAuthorization struct{ AllowedUntil time.Time }

type SubscriptionAuthorizer

type SubscriptionAuthorizer interface {
	// Arguments are trusted Centrifugo authenticated user UUID and canonical channel.
	// Denials return ErrPermissionDenied/ErrUnauthenticated; outages ErrUnavailable.
	AuthorizeSubscription(context.Context, string, string) (SubscriptionAuthorization, error)
}

type SystemClock

type SystemClock struct{}

SystemClock is the production UTC clock. Tests can inject their own Clock.

func (SystemClock) Now

func (SystemClock) Now() time.Time

type Team

type Team struct {
	ID      string `json:"id"`
	LobbyID string `json:"lobby_id"`
	Name    string `json:"name"`
	Order   int    `json:"order"`
}

Team is one side of a lobby. It holds at most one active member: one person or one seat.

type TeamDefinition

type TeamDefinition struct {
	Name string `json:"name"`
}

TeamDefinition names one team of a new lobby. A team holds at most one member: one person or one seat.

func ValidateTeamDefinitions

func ValidateTeamDefinitions(definitions []TeamDefinition) ([]TeamDefinition, error)

ValidateTeamDefinitions checks a new lobby's teams: from MinTeams to MaxTeams, with unique names. A team holds at most one member, so the number of teams is also the number of members the lobby holds.

type WatchAccess

type WatchAccess struct {
	Scope   Scope  `json:"scope"`
	Channel string `json:"channel"`
	Member  bool   `json:"member"`
}

WatchAccess is what a person who asked to watch a lobby receives: the lobby, and the channel its game publishes on for watchers. Member is true for an active member, who keeps their member access instead of becoming a watcher; the watch channel is open to them too.

type WatchAuthorizer

type WatchAuthorizer interface {
	AuthorizeWatch(context.Context, Principal, Scope) error
}

WatchAuthorizer lets a game check that a player may watch a lobby, for the reads it opens to watchers: an active member, or a watcher the host hasn't kicked. It returns ErrNotFound otherwise, also for a lobby that is gone.

type WatchRequest

type WatchRequest struct {
	GameKey  string `json:"game_key"`
	JoinCode string `json:"join_code"`
}

WatchRequest asks to watch the lobby of a game that has this join code.

type Watcher

type Watcher struct {
	PlayerID    string     `json:"player_id"`
	DisplayName string     `json:"display_name"`
	JoinedAt    time.Time  `json:"joined_at"`
	KickedAt    *time.Time `json:"kicked_at"`
}

Watcher is a person outside the lobby's members who watches it with the join code. A watcher takes no seat and counts toward nothing: not capacity, the start roster, leases, grace or retention. The game decides what a watcher may read. A watcher who leaves is removed; one the host kicked stays, with KickedAt set, so the code doesn't let them back in.

func FindWatcher

func FindWatcher(aggregate *Aggregate, playerID string) *Watcher

FindWatcher returns a pointer into the aggregate for locked mutation, or nil when the player has no watcher row.

func (Watcher) Watching

func (watcher Watcher) Watching() bool

Watching reports whether the watcher may still watch.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL