app

package
v0.3.1 Latest Latest
Warning

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

Go to latest
Published: Nov 16, 2026 License: MIT Imports: 30 Imported by: 0

Documentation

Overview

Package app builds the whole lobby from a Config: its stores, guest sessions, player tokens and their public keys, the games of LOBBY_GAMES and the game API they read, the Centrifugo publisher, authorizer and proxy, the retention that lobby requests run, and the lobby page. Its two hosts serve it on their own, the local server in cmd/lobby and the Lambda function in cmd/lobby-lambda, and a game's host can run it in its own process with Register, so there is one wiring.

New runs no schema changes: the local server migrates before it listens, and a deploy migrates before the Lambda function serves.

Index

Constants

View Source
const (
	DatabaseURLEnv                   = "LOBBY_DATABASE_URL"
	DatabaseMaxOpenConnectionsEnv    = "LOBBY_DATABASE_MAX_OPEN_CONNECTIONS"
	DatabaseMaxIdleConnectionsEnv    = "LOBBY_DATABASE_MAX_IDLE_CONNECTIONS"
	DatabaseConnectionMaxIdleTimeEnv = "LOBBY_DATABASE_CONNECTION_MAX_IDLE_TIME"
	// HTTPAddrEnv is read by the local server, cmd/lobby, alone.
	HTTPAddrEnv              = "LOBBY_HTTP_ADDR"
	PublicURLEnv             = "LOBBY_PUBLIC_URL"
	CentrifugoAPIURLEnv      = "LOBBY_CENTRIFUGO_API_URL"
	CentrifugoAPIKeyEnv      = "LOBBY_CENTRIFUGO_API_KEY"
	CentrifugoPublicURLEnv   = "LOBBY_CENTRIFUGO_PUBLIC_URL"
	ConnectionTokenSecretEnv = "LOBBY_CONNECTION_TOKEN_HMAC_SECRET"
	ProxySecretEnv           = "LOBBY_PROXY_SECRET"
	PlayerTokenKeysEnv       = "LOBBY_PLAYER_TOKEN_KEYS"
	PlayerTokenLifetimeEnv   = "LOBBY_PLAYER_TOKEN_LIFETIME"
	// AllowedOriginsEnv lists the games' sites whose own lobby UI calls the
	// player API from another origin, separated by commas.
	AllowedOriginsEnv = "LOBBY_ALLOWED_ORIGINS"
	// GamesEnv lists the games, gamehooks.GamesEnv.
	GamesEnv = gamehooks.GamesEnv
	// The retention settings, domain.RetentionPolicy; each one unset keeps
	// domain.DefaultRetention's value.
	RetentionIdlePeriodEnv      = "LOBBY_RETENTION_IDLE_PERIOD"
	RetentionMaximumAgeEnv      = "LOBBY_RETENTION_MAXIMUM_AGE"
	RetentionCreateRequestsEnv  = "LOBBY_RETENTION_CREATE_REQUESTS"
	RetentionExpiredSessionsEnv = "LOBBY_RETENTION_EXPIRED_SESSIONS"
	RetentionBatchSizeEnv       = "LOBBY_RETENTION_BATCH_SIZE"
	RetentionPassIntervalEnv    = "LOBBY_RETENTION_PASS_INTERVAL"
)

The lobby's environment. Every name has the LOBBY_ prefix, so a host that runs the lobby beside its own code keeps the two apart.

View Source
const (
	DefaultDatabaseMaxOpenConnections    = 2
	DefaultDatabaseMaxIdleConnections    = 2
	DefaultDatabaseConnectionMaxIdleTime = time.Minute
)

The pool defaults suit Lambda, where an instance serves one request at a time and every instance has its own pool. The local server widens it; see cmd/lobby.

View Source
const ConnectTimeout = 5 * time.Second

ConnectTimeout bounds OpenDatabase's first connection, well under Lambda's 10-second limit on a cold start's init.

View Source
const DefaultHTTPAddr = ":8890"

DefaultHTTPAddr is where the local server listens without LOBBY_HTTP_ADDR.

View Source
const SlowQueryThreshold = 200 * time.Millisecond

SlowQueryThreshold is how long a query may take before it is logged as slow.

View Source
const UIPath = "/lobby/ui/"

UIPath is where the lobby page is served.

Variables

This section is empty.

Functions

func LoadHTTPAddr

func LoadHTTPAddr(lookup func(string) (string, bool)) (string, error)

LoadHTTPAddr reads the address that the local server listens on, DefaultHTTPAddr unless LOBBY_HTTP_ADDR names another.

func NewCentrifugoClient

func NewCentrifugoClient(config Config) *gocent.Client

NewCentrifugoClient is the client of Centrifugo's HTTP API that config names.

func OpenDatabase

func OpenDatabase(config DatabaseConfig, logger *slog.Logger) (*gorm.DB, error)

OpenDatabase connects to the lobby's database with a bounded pool. It runs no schema changes. Failed and slow queries are logged through logger as warnings, with placeholders instead of their values.

func ParseOrigins

func ParseOrigins(value string) ([]string, error)

ParseOrigins reads a list of origins separated by commas, such as "https://island-battles.example.org, http://localhost:3000": each an http or https origin as browsers send it in the Origin header, in lower case, without a path, a trailing slash or a default port. Empty, it lists none.

Types

type Config

type Config struct {
	// Database is read by OpenDatabase; New takes an open database.
	Database DatabaseConfig
	// PublicURL is where players and games reach the lobby, such as
	// https://lobby.example.org, and the iss of its player tokens.
	PublicURL string
	// CentrifugoAPIURL and CentrifugoAPIKey reach Centrifugo's HTTP API,
	// which the lobby pushes its changes to; see NewCentrifugoClient.
	CentrifugoAPIURL string
	CentrifugoAPIKey string
	// CentrifugoPublicURL is the WebSocket URL that connection tokens send
	// players to.
	CentrifugoPublicURL string
	// ConnectionTokenSecret signs Centrifugo connection tokens; Centrifugo
	// verifies them with the same secret.
	ConnectionTokenSecret string
	// ProxySecret is the header value Centrifugo sends with its subscribe
	// and refresh proxy calls.
	ProxySecret string
	// PlayerTokenKeys sign player tokens: playertoken.ParseKeySet.
	PlayerTokenKeys *playertoken.KeySet
	// PlayerTokenLifetime is how long a player token lasts, at most
	// playertoken.MaxLifetime; zero is playertoken.MaxLifetime.
	PlayerTokenLifetime time.Duration
	// Games is LOBBY_GAMES: a JSON array of gamehooks.GameConfig, at least
	// one game.
	Games string
	// GameSecrets are the values of the variables that the games name as
	// their secret_env, by name.
	GameSecrets map[string]string
	// Retention says when lobby data is deleted; a zero field keeps
	// domain.DefaultRetention's.
	Retention domain.RetentionPolicy
	// AllowedOrigins are the games' sites, such as
	// https://island-battles.example.org, whose own lobby UI calls the player
	// API from another origin: Handler answers them with CORS. A host that
	// runs the lobby in its own process serves its pages on the lobby's
	// origin and needs none.
	AllowedOrigins []string
}

Config is everything the lobby needs besides its database and Centrifugo connections: LoadConfig reads it from the LOBBY_* environment, and a host that runs the lobby in its own process fills it from its own settings.

func LoadConfig

func LoadConfig() (Config, error)

LoadConfig reads the lobby's settings from the environment.

func LoadConfigFromLookup

func LoadConfigFromLookup(lookup func(string) (string, bool)) (Config, error)

LoadConfigFromLookup reads and checks the lobby's settings through lookup, such as os.LookupEnv. Every setting is required except the pool limits, the player token lifetime and the retention settings, which have defaults, and the allowed origins, without which no other site may call the player API. Errors name variables, never their values.

func (Config) LookupGameSecret

func (config Config) LookupGameSecret(name string) (string, bool)

LookupGameSecret reads a game's shared secret by the variable that its secret_env names.

type DatabaseConfig

type DatabaseConfig struct {
	URL                   string
	MaxOpenConnections    int
	MaxIdleConnections    int
	ConnectionMaxIdleTime time.Duration
}

DatabaseConfig says where PostgreSQL is and bounds the lobby's pool.

func LoadDatabaseConfigFromLookup

func LoadDatabaseConfigFromLookup(lookup func(string) (string, bool)) (DatabaseConfig, error)

LoadDatabaseConfigFromLookup reads the database settings through lookup: LOBBY_DATABASE_URL, which is required, and the optional pool limits. They are all that the migrate command, cmd/migrate, reads.

type Lobby

type Lobby struct {
	// contains filtered or unexported fields
}

Lobby is the lobby's services, ready to serve.

func New

func New(config Config, database *gorm.DB, centrifugo *gocent.Client, logger *slog.Logger, opts ...Option) (*Lobby, error)

New builds the lobby on database, whose schema is up to date, and pushes its changes through centrifugo, the client of Centrifugo's HTTP API (see NewCentrifugoClient). It starts no goroutines and holds nothing that outlives a request besides database's pool, which the host owns and closes.

func (*Lobby) GameAPI

func (lobby *Lobby) GameAPI() http.Handler

GameAPI serves the game API, under gamehooks.GameAPIPath, for a host that carries a game's calls to it in memory.

func (*Lobby) Handler

func (lobby *Lobby) Handler() (http.Handler, error)

Handler is the lobby on its own: Register's routes, with the player API's OpenAPI document at /openapi.json and its documentation at /docs, a redirect from / to the lobby page, and GET /healthz, which answers 204. The player API answers the configured AllowedOrigins with CORS.

func (*Lobby) PlayerTokenKeys

func (lobby *Lobby) PlayerTokenKeys() *playertoken.KeySet

PlayerTokenKeys are the keys that sign player tokens. A game in the lobby's process verifies tokens with them, as a playertoken.KeySource, instead of the lobby's JWKS.

func (*Lobby) Register

func (lobby *Lobby) Register(router chi.Router, api huma.API) error

Register serves the lobby on router: the player API, under /lobby/v1, on api, which router serves; the game API, under gamehooks.GameAPIPath; the Centrifugo proxy, under /internal/lobby/centrifugo; and the lobby page, under UIPath. A host that runs the lobby in its own process registers it on its own router and API; the lobby's own hosts serve Handler.

type Observer

type Observer struct {
	// Authenticated is told the player of each verified guest session.
	Authenticated func(ctx context.Context, playerID string)
	// Error is told the cause of a failure that the response leaves out: an
	// authentication that could not run, such as with the database down, and
	// a Centrifugo proxy call answered 503.
	Error func(ctx context.Context, err error)
}

Observer is told what a host records about requests, such as the error lines of a game's host that runs the lobby in its own process. A nil field is told nothing.

type Option

type Option func(*options)

Option changes how New builds the lobby.

func WithHookOptions

func WithHookOptions(hookOptions ...gamehooks.Option) Option

WithHookOptions passes options to the clients of the games' hooks, such as gamehooks.WithHTTPClient with a transport that reaches a game in the same process.

func WithObserver

func WithObserver(observer Observer) Option

WithObserver tells observer about requests.

Jump to

Keyboard shortcuts

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