mpl

module
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Nov 18, 2026 License: MIT

README

mpl: a generic multiplayer lobby

mpl is a lobby service for casual multiplayer games: guest players, join codes, teams, readiness, reconnect leases, seats that the game plays, watchers, and playing again in the same lobby. A game binds to it over HTTP, with signed hooks and a signed game API, and verifies its players with short-lived player tokens. The lobby knows nothing of any game: it stores each game's settings as opaque JSON and asks the game's hooks. Island Battles is the first game that uses it, and appears in this README only as an example.

This repository holds the Go module github.com/INTODAN/mpl, its API contracts, the Python client mpl-lobby-client, the lobby page, a mock game for the lobby's own tests, transport configuration and documentation. Its history starts in the Island Battles repository, where the lobby was the lobby/ directory.

go.mod, go.sum      The Go module github.com/INTODAN/mpl
domain/             Types, ports, errors, policies, and pure state rules
application/        Membership commands, teams, leases, binding, and publishing
app/                The whole lobby, built from its LOBBY_* configuration
auth/               Guest credentials, connection tokens and player tokens
playertoken/        Player token signing and verification, which games import
postgres/           Persistence and versioned schema migrations
httpapi/            HTTP routes and DTOs, the player API and the game API
gamehooks/          Signed HTTP hooks and game API client for games in other services
mockgame/           A mock game over HTTP, for the lobby's own tests
adminmcp/           Read-only MCP tools for operators' questions about lobbies
frontend/           The lobby page, its embedded asset handler and its tests
realtime/           Centrifugo authorization and the push publisher
internal/           Shared implementation helpers and test fixtures
api/                OpenAPI and event schema artifacts
cmd/                The lobby's local server, Lambda and migrate command, the OpenAPI exporter, the mock game's server
clients/            Go example and the Python client, its CLI and generator
centrifugo/         Centrifugo configuration
integration/        Live tests and the configurable runner
deploy/             The deployment: Terraform, the VM's Ansible, the plan checker and their tests
scripts/            The live tests' entry point, and the deploy scripts
docs/               Architecture and implementation records
.agents/skills/     Conventions for coding agents (see AGENTS.md)
.github/workflows/  Checks on every pull request, the release, and the deploy

Using the module

The repository is public, so the module is go-gettable:

go get github.com/INTODAN/mpl@vX.Y.Z

Go consumers import github.com/INTODAN/mpl/domain for contracts, github.com/INTODAN/mpl/application for services, github.com/INTODAN/mpl/app to run the whole lobby in their own process, github.com/INTODAN/mpl/gamehooks to serve a game's hooks and read the game API, and github.com/INTODAN/mpl/playertoken to verify players. There is no root Go package. A game's repository can also run the lobby from the pinned module version, for development and live tests, with go run github.com/INTODAN/mpl/cmd/lobby and go run github.com/INTODAN/mpl/cmd/migrate, and copy the API documents for its own code generators from go list -m -f '{{.Dir}}' github.com/INTODAN/mpl.

Python clients install mpl-lobby-client from PyPI (its README).

Commands

All commands run from the repository root. Go comes from go.mod; Python 3.14+ with uv for the Python client and the live tests; Node 22 for the lobby page's tests.

  • Lint/Verify (Go): go vet ./... and golangci-lint run --timeout=5m ./... (v2.5.0, the version checks.yml pins)
  • Format: go fmt ./... (gofmt -l . lists the files that need it)
  • Test (disposable PostgreSQL containers): go test ./...
  • Check the API documents: go run ./cmd/export-lobby-openapi --output api/openapi.json --events-output api/events.json --game-api-output api/game-api.openapi.json --check; without --check, it writes them
  • Check the generated Python models: uv run --project clients/lobby-python/tools --locked python clients/lobby-python/scripts/generate.py --check; without --check, it regenerates them
  • Python client tests: uv run --project clients/lobby-python --locked pytest clients/lobby-python/tests
  • Lobby page tests: node --test frontend/*.test.mjs
  • Live tests with the mock game (Linux Docker or Podman): ./scripts/test-acceptance.sh --mock-game (the acceptance runner)
  • Deploy tests (the plan checker, the deploy bucket's sync, the VM's templates rendered by Ansible): python3 -I -m unittest discover -s deploy -p 'test_*.py'; they need ansible-playbook (deploy README)
  • Deploy configuration: in deploy/terraform, terraform fmt -check -recursive, terraform init -backend=false, terraform validate and terraform test (mocked providers); in deploy/ansible, ansible-playbook -i localhost, --syntax-check site.yml and ansible-lint

Go database tests use disposable PostgreSQL containers through Testcontainers. On rootless Podman, run systemctl --user enable --now podman.socket once, then export DOCKER_HOST=unix://$XDG_RUNTIME_DIR/podman/podman.sock and TESTCONTAINERS_RYUK_DISABLED=true before running them. Live tests run the lobby's own server, cmd/lobby, with the mock game or a game's host beside it; see the acceptance runner. Game-specific endpoint checks belong to the game host's suite.

After changing the player API, the game API or the events, export the API documents and regenerate the Python models in the same change. On a rebase conflict in generated files, regenerate them instead of merging by hand.

Checks on every pull request

.github/workflows/checks.yml runs these checks on every pull request to main, as parallel jobs. Each shows as its own check on the pull request:

Job Runs
Go go vet, golangci-lint (pinned to the version in the workflow), a gofmt -l check, and go test with Testcontainers on the runner's Docker
API contract the API documents' --check and the generated Python models' --check
Python the Python client's tests, with uv --locked
JS node --test for the lobby page's tests in frontend/
Live (mock game) ./scripts/test-acceptance.sh --mock-game: the lobby, its migrate command and the mock game against disposable PostgreSQL and Centrifugo containers
Deploy the deploy tests, Ansible's syntax check and lint, and Terraform's format check, validation and tests with mocked providers; nothing reaches AWS

It also has a workflow_call trigger, so the release workflow runs the same checks with uses: ./.github/workflows/checks.yml before it tags. When you change the golangci-lint version in the workflow, change the one you run locally to match.

Releases

.github/workflows/release.yml releases the lobby. It runs only when someone with write access starts it by hand, from main (workflow_dispatch, with the version to release, higher than every earlier one); merging to main releases nothing. It runs the checks, then tags the commit vX.Y.Z, which is the version go get github.com/INTODAN/mpl@vX.Y.Z resolves, creates the GitHub release, and publishes mpl-lobby-client at the same version to PyPI with trusted publishing, in the GitHub environment pypi; no PyPI token exists. Versions continue the lobby's versions from the Island Battles repository, where it was tagged lobby/vX.Y.Z; the first release here is v0.3.0.

Before the first release, the PyPI project's trusted publisher must name this repository, the workflow release.yml and the environment pypi, and the environment should be limited to main.

Deploying

The lobby runs on AWS Lambda behind CloudFront on its own name, lobby.<domain>, with Postgres and Centrifugo on a Lightsail VM that it shares with its tenants, the games whose database lives there. deploy/README.md has the runbook: the Terraform configuration and its state, taking over a VM that runs already, the DNS records, the VM deploy, the tenants and the Deploy workflow. Merging deploys nothing; the owner starts each deploy by hand, from main.

Running the lobby

The lobby runs on its own, as a server that games reach over the network:

  • cmd/migrate brings the lobby's own database (LOBBY_DATABASE_URL) to this build's schema with postgres.Migrate, and reads nothing else but the pool settings. A deploy runs it before a new build serves, since the Lambda host never changes the schema. The lobby's database holds only the lobby's tables: a game keeps its own data in a database of its own, which may be on the same server, and nothing joins the two.
  • cmd/lobby is the local server, for development and live tests. It listens on LOBBY_HTTP_ADDR, :8890 by default, brings the lobby's schema up to date before it listens (postgres.Migrate, under an advisory lock), and keeps a pool of 10 connections unless LOBBY_DATABASE_MAX_OPEN_CONNECTIONS says otherwise.
  • cmd/lobby-lambda serves the same lobby from AWS Lambda behind a Function URL, with response streaming (lambdaurl, the RESPONSE_STREAM invoke mode). It ends each request's work 2 seconds before the invocation's deadline, answers 503 until it has started and tries to start again at most every 10 seconds, runs no schema changes, and keeps Lambda's pool of 2 connections. It isn't deployed yet: Island Battles' Lambda still runs the lobby in its own process.
  • Package app builds the whole lobby from an app.Config, for both commands and for a game's host that runs the lobby in its own process (Island Battles in production, until the lobby is deployed on its own), so there is one wiring: the stores, guest sessions, player tokens and the JWKS, the games of LOBBY_GAMES and the game API, the Centrifugo publisher, authorizer and proxy, retention, and the lobby page. app.New(config, database, centrifugo, logger, options...) builds it; Lobby.Handler() serves it on its own, and Lobby.Register(router, api) on a host's router and Huma API. app.WithHookOptions passes options to the hook clients, such as an in-memory transport, and app.WithObserver tells the host about authenticated players and the causes of failures that the responses leave out.

The lobby's own server serves:

Path What
/lobby/v1/* The player API (api/openapi.json), with the public keys at /lobby/v1/jwks.json
/lobby/v1/game-api/* The game API (api/game-api.openapi.json)
/internal/lobby/centrifugo/* Centrifugo's subscribe and refresh proxy
/lobby/ui/ The lobby page; / redirects there
/openapi.json, /docs The player API's document and its documentation
/healthz 204

Retention runs as in a host's process: at the end of lobby requests, at most once a minute per process unless a pass found a backlog (Deleting old data).

Configuration

Both commands read the same environment; every name starts with LOBBY_. .env.example lists them with local values.

Variable
LOBBY_DATABASE_URL The lobby's own PostgreSQL database, postgres://…, which holds only the lobby's tables. Required.
LOBBY_DATABASE_MAX_OPEN_CONNECTIONS, LOBBY_DATABASE_MAX_IDLE_CONNECTIONS, LOBBY_DATABASE_CONNECTION_MAX_IDLE_TIME The pool: 2 (10 on the local server), 2 and 1m by default.
LOBBY_HTTP_ADDR The local server's host:port, :8890 by default.
LOBBY_PUBLIC_URL Where players and games reach the lobby, an origin without a path, such as https://lobby.example.org. It is the iss of player tokens, so a game uses it as the lobby's URL. Required.
LOBBY_CENTRIFUGO_PUBLIC_URL The WebSocket URL that connection tokens send players to, ws:// or wss://. Required.
LOBBY_CENTRIFUGO_API_URL, LOBBY_CENTRIFUGO_API_KEY Centrifugo's HTTP API, which each committed change is pushed to. Required.
LOBBY_CONNECTION_TOKEN_HMAC_SECRET Signs Centrifugo connection tokens; Centrifugo's client.token.hmac_secret_key. Required.
LOBBY_PROXY_SECRET The X-Lobby-Proxy-Secret of Centrifugo's proxy calls. Required.
LOBBY_PLAYER_TOKEN_KEYS, LOBBY_PLAYER_TOKEN_LIFETIME The player token keys, required, and their lifetime, 15m by default.
LOBBY_GAMES The games, at least one (Configuration of HTTP games), with each game's secret in the variable its secret_env names. Required.
LOBBY_ALLOWED_ORIGINS The games' sites, separated by commas, whose own lobby UI, such as a game's web client, calls the player API from another origin, such as https://island-battles.example.org: each an origin without a path. The player API under /lobby/v1/ answers them with CORS: Access-Control-Allow-Origin set to the request's origin (never *), Vary: Origin and Access-Control-Expose-Headers: Retry-After, and a preflight with 204, GET, POST, PUT, DELETE, Authorization, Content-Type and Access-Control-Max-Age: 600. Any other origin, and the game API, the Centrifugo proxy and the lobby page, get no CORS headers. Optional; unset, no other site may call the player API.
LOBBY_RETENTION_IDLE_PERIOD, LOBBY_RETENTION_MAXIMUM_AGE, LOBBY_RETENTION_CREATE_REQUESTS, LOBBY_RETENTION_EXPIRED_SESSIONS, LOBBY_RETENTION_BATCH_SIZE, LOBBY_RETENTION_PASS_INTERVAL Retention: the lobbies' idle period and maximum age, the create requests' idempotency window, how long expired sessions are kept, the rows a pass deletes of each kind and the least time between passes. Each unset keeps DefaultRetention()'s value.

A setting that is missing or invalid stops the lobby from starting, and the error names the variables, never their values.

Starting a game while the lobby is locked

A ready or start request holds a database connection, and the room's lock, while the lobby calls the game's ready-check hook, and a game may read the same lobby through the game API before it answers, as Island Battles does at the start. The game API reads without the lock (Service.GameSnapshot), so a start never waits on itself: its transaction holds one connection, and the game's read takes another (app tests this on a pool of 2). On Lambda an instance serves one request at a time, so the game's read reaches another instance. The local server serves many requests at once, and other requests to the same lobby hold their connections while they wait for the lock, so its pool is wider: 10 connections.

Schema migrations

The PostgreSQL schema is versioned SQL in postgres/migrations/. A host calls postgres.Migrate(ctx, db) before using the stores. It runs every pending migration in one transaction under a PostgreSQL advisory lock and records each in lobby_schema_migrations, so concurrent runs wait for each other and a failed run changes nothing. A database whose lobby tables were created before versioning is recorded at migration 1 without running it, but only if it has every table and column that migration 1 creates. If some tables or columns are missing, Migrate fails and names them.

To change the schema, add the next file, NNNN_description.sql numbered without gaps, and update the GORM record in the same change; a test fails when records and columns differ. Never edit an applied migration: Migrate fails when an applied file has changed. Migrations cannot use statements that PostgreSQL refuses inside a transaction, such as CREATE INDEX CONCURRENTLY.

A host can version its own tables with postgres.MigrationSet, which takes its own history table and files. Island Battles does this for its map templates.

Temporary browser frontend

The frontend is a plain HTML/CSS/JavaScript playground for two players. The games of LOBBY_GAMES list themselves in its catalog, so the frontend names none of its own. The lobby serves it at /lobby/ui/. Open that address in two tabs or browsers, choose a game, and create or join using the shared code. Assets are embedded in the Go executable; no frontend build or dependency installation is needed. The page can also: copy an invite link (?join=CODE) that joins the lobby after the name step; watch a lobby by code or ?watch=CODE link without a seat, for a game whose catalog entry names a watcher document (POST /lobby/v1/watches, the watch channel, DELETE …/watch); list a lobby's watchers for its members, with a Remove button for the host (GET …/watchers, DELETE …/watchers/{player_id}), whose kicked watcher is told so and returned to the start screen; and let the game's settings form choose the teams. See the frontend README.

Domain and application services

domain/ owns records, request types, errors, policies, state helpers, and repository ports. application/ owns commands and coordinates those contracts: membership.go groups create/join/snapshot, while teams, lifecycle, leases, binding, and publishing have focused files. Tests live beside the package they exercise.

Application services depend on domain contracts. Auth, PostgreSQL, HTTP, and realtime adapters depend inward on the domain and, where needed, application services. Neither inner package imports an adapter, Huma/GORM/gocent, or any game. Shared nullable-field helpers stay private under internal/optional. Importing a package performs no I/O.

Service construction and transaction helpers live in application:

service, err := application.NewService(store, clock, identifiers, policy)
aggregate, err := application.TransactNormalized(ctx, store, clock, policy, scope, command)

The constructor accepts domain.Store, domain.Clock, domain.IdentifierSource, and domain.Policy. Transaction callbacks use domain.Mutation. The service keeps its dependencies and timed mutation helper private.

The pure expiry normalizer lives in domain:

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

TransactNormalized performs one Store.Transact. Inside its callback it captures one UTC clock value, normalizes the original aggregate, then runs the command against aggregate.DeepCopy(). A successful command replaces the aggregate and returns MergeChanges(cleanup, commandChange). A rejected command discards its copy, returns cleanup with a nil callback error so cleanup commits, then returns the captured command error after commit. A store failure wins over that captured error. A normalization error rolls back. Callbacks must contain no network calls or external side effects. runMutation and exported TransactNormalized share a private transactNormalizedTimed helper. Service callbacks receive the same captured UTC time used for normalization, so no clock boundary can change halfway through a command; realtime authorization uses the exported helper.

For example, at an expired host's grace deadline, normalization deactivates that host, records a generation-specific revocation and transfers host. Its attempted start is rejected after cleanup; the store nevertheless commits expiry and one new version/invalidation. No phase/start-roster edits from the rejected command survive. On successful start, any cleanup and the start share one version increment. Build every response from the post-commit returned aggregate.

Frozen pure helpers:

DefaultPolicy(games ...GameRegistration) Policy
(Policy).Validate() error
(Policy).Game(string) (GameRegistration, error)
(Policy).ValidateGame(string) error
(Policy).ValidateGameSettings(ctx context.Context, gameKey, lobbyID string, settings json.RawMessage, teams []TeamDefinition) (json.RawMessage, error)
NormalizeGameSettings(json.RawMessage) (json.RawMessage, error)
(Policy).ValidateSeatSettings(ctx context.Context, gameKey, lobbyID, playerID string, settings json.RawMessage) (json.RawMessage, string, error)
NormalizeSeatSettings(json.RawMessage) (json.RawMessage, error)
(Member).IsSeat() bool
(Policy).ValidateScope(Scope) error
DefaultRetention() RetentionPolicy
(Policy).LobbyRetention(string) LobbyRetention
(Policy).RetentionCutoffs(time.Time) RetentionCutoffs
(RetentionResult).Backlog(int) bool
(*Lobby).MarkConnected(time.Time)
ValidateGameKey(string) error
ValidateUUID(string) error
NormalizeName(string, int) (string, error)
TeamNameKey(string) string
ValidateTeamDefinitions([]TeamDefinition) ([]TeamDefinition, error)
NormalizeJoinCode(string) (string, error)
RoomChannel(Scope) (string, error)
PlayerChannel(string) (string, error)
ParseChannel(string) (Channel, error)
ElectHost([]Member) *string
EffectiveLeaseExpiry(Lease) time.Time
LatestEffectiveLeaseExpiry([]Lease, string, int64) (time.Time, bool)
HasLiveLease([]Lease, string, int64, time.Time) bool
FindMember(*Aggregate, string) *Member
LobbyFull(*Aggregate) bool
TeamTaken(*Aggregate, string) bool
FindLease(*Aggregate, string, int64, string) *Lease
(Aggregate).DeepCopy() Aggregate
MergeChanges(...Change) Change
BuildSnapshot(Aggregate, string) (Snapshot, error)
BuildGameSnapshot(Aggregate) (Snapshot, error)

A team holds one member, a person or a seat, so a lobby holds as many members as it has teams. ValidateTeamDefinitions accepts 2 to 16 teams with unique names; a create request chooses no capacity, and Lobby.Capacity is the number of teams. TeamTaken reports whether an active member is on a team, which makes selecting it or adding a seat to it fail with team_full, and LobbyFull whether the lobby has as many active members as teams, which makes a join or a new seat fail with lobby_full. A start with two members on one team, which only a lobby created before this rule can have, fails with not_ready.

FindMember and FindLease return mutable pointers into the aggregate; missing records return nil. Lease helpers take player ID then generation; FindLease additionally takes client UUID. Lease lists belong to one aggregate. LatestEffectiveLeaseExpiry includes released leases of the requested generation and returns false for absent history. Released effective expiry is min(expiry, release), so a late release cannot extend grace. HasLiveLease excludes released tuples and uses strict expiry > now. ElectHost uses active members that aren't seats, ordered by join sequence then membership ID, returning a detached player-ID pointer or nil.

The exact lease error ordering is membership-history existence (outsider: ErrNotFound), generation equality (otherwise ErrStaleMembership), then tuple policy. Unknown current-generation heartbeat and inactive/released-tuple heartbeat return ErrStaleMembership. Unknown current-generation release and repeated released-tuple release succeed without changes, including an inactive historical membership. Heartbeats never create or reopen tuples. Explicit join with a new client UUID establishes a lease. Persist Lobby.NextJoinSequence=2 after the creator receives sequence 1; increment under the room lock for every new/reactivated membership, never derive it from active members.

Policy defaults are explicit: DefaultPolicy(registrations...) supplies 15s heartbeat, 45s lease, 60s grace, 24h session, 5m connection JWT, 60s subscription authorization and DefaultRetention(). Policy{} is invalid. Policies must have positive durations, heartbeat shorter than lease, token/subscription lifetimes no longer than session, a valid retention policy (see Deleting old data), and a nonempty list of registrations with unique canonical game keys. Constructors validate then retain a detached registration slice.

The host declares each game with a GameRegistration. The lobby applies its fields without knowing the game, and a zero field keeps the default behavior, so new declarations are added as new fields:

  • Key is the canonical game key.
  • ValidateSettings checks the optional game_settings object of a create or settings-change request against the request's validated teams, func(ctx, lobbyID string, settings json.RawMessage, teams []TeamDefinition) error, with an empty lobby ID while the lobby is being created, so a game can require settings that fit the lobby, such as a map with one starting position per team. A nil validator means the game takes no settings and accepts only {}.
  • StartRules adds start conditions to the default ones: at least two members, at least one of them a person, each with a team, ready and connected, or not_ready. With EveryTeamNeedsMember, a start with an empty team fails with empty_teams, whose team_ids list the empty teams in team order. Snapshots carry the game's rules as start_rules, so clients can explain why the lobby can't start yet.
  • Retention overrides the policy's LobbyRetention, the idle period and the maximum age after which the game's lobbies are deleted. The maximum age runs from the start of the lobby's current round: its creation, or the last time it was reopened. Each zero period keeps the default.
  • ReadyGate lets the game keep members from getting ready, and a lobby from starting, until they meet a condition of the game's own, such as a choice in their member settings. The lobby calls it with the lobby's ID before the transaction of a ready request with ready: true or a start, so a game that reads its own data reads it without the room's lock held, and runs the ReadyCheck it returns inside the transaction: for the member getting ready (one ReadyMember, atStart false), after the lobby's own checks (active member, waiting phase, a team), and once for the whole start roster (every member's ID, display name and member settings, atStart true), after the start rules, so the game can name the members who must act in a refusal that the host sees. Each ReadyMember carries the member's Settings, their member settings or nil, so a game that decides from them reads nothing and returns its check at once. The check returns nil or GameRequirement(problemType, message), which fails the request with 409 game_requirement, whose type is the game's problem type URI and whose detail is the game's message for the player. A gate or check that can't decide reports unavailable. Data the gate reads itself is read before the lock, so a member must keep meeting a condition on it once they do while the lobby waits; member settings come from inside the transaction. Clearing readiness never asks the gate. A nil gate adds no condition.
  • GameOver tells whether the game of a lobby round has ended, func(ctx, lobbyID string, round int64) (bool, error), so that a member can reopen the lobby for another game. The lobby calls it before the transaction of a reopen request, like the ready gate. A game that has ended must stay ended. A game should report a round whose start never created a game as over, so the lobby can't be stuck. A check that can't run returns the context's error or one wrapping ErrUnavailable. A nil check means the game's lobbies play one game: reopening fails with phase_conflict.
  • ValidateSeat lets the host add seats that no person plays, such as the game's bot, and checks each seat's seat_settings, func(ctx, lobbyID, playerID string, settings json.RawMessage) (string, error). It receives the settings as a canonical object, with the ID of the player making the request, and returns the seat's display name, such as Bot (level 2). The lobby checks that this player is the host of a waiting lobby only afterwards, inside its transaction, so a game whose seat settings name a player, such as the one who may run the seat, compares that player with playerID and leaves the host check to the lobby; a game that doesn't need it ignores it. A rejection becomes invalid_seat_settings with the validator's message; a validator that can't run returns the context's error or one wrapping ErrUnavailable. A nil validator means the game has no seats, and every seat is refused with invalid_seat_settings.
  • ValidateMemberSettings lets each person set their own member settings for the game, such as what plays for them, func(ctx, lobbyID string, settings json.RawMessage) error. It receives the settings as a canonical object; a rejection becomes invalid_member_settings with the validator's message, and a validator that can't run returns the context's error or one wrapping ErrUnavailable. A nil validator means the game takes no member settings, and every value is refused with invalid_member_settings.
  • StartGame creates the game of a started lobby's round, func(ctx, snapshot Snapshot) (gameID string, err error). The lobby calls it right after a start commits, outside the transaction, with the snapshot as the game reads it (BuildGameSnapshot, with the game's start rules), and records the round as bound (Lobby.BoundRound, column lobby_rooms.bound_round, not in the public snapshot). Any error, or an empty game ID, fails the start request with 502 game_unavailable, and the lobby stays started; the host's next start request on a started lobby whose round isn't bound calls it again, and once it is bound, start requests return the snapshot without calling it. So the game must bind idempotently by lobby and round. A nil StartGame calls nothing: the game binds its own way, such as through application.GameBinding (see Binding a game to a started lobby). Binding a game over HTTP describes the games that set it.

ValidateGameSettings first canonicalizes the settings with NormalizeGameSettings: one compact JSON object with sorted keys and at most MaxGameSettingsBytes, and {} when the request had none. The validator receives that canonical object and the request's teams in order, after they pass ValidateTeamDefinitions. A rejection becomes invalid_game_settings with the validator's message as the client-facing detail, and the create request fails without writes. A validator that can't run returns the context's error or one wrapping ErrUnavailable. The lobby stores the canonical object with the room, includes it in the create fingerprint and returns it as lobby.game_settings in every snapshot, including the started snapshot a game binding receives. The host can change the settings and the teams while the lobby waits; the same validator checks the new settings against the new teams.

Store.Create atomically saves its original authorized BuildSnapshot response alongside the validated create fingerprint and request key; code uniqueness collisions return the internal ErrJoinCodeCollision sentinel, which services bound to five attempts. Change.PrivateChanged preserves lease/counter writes without implying an event. Change.PublicChanged implies persistence and one invalidation/version increment. Revocation intents contain scope/player/generation. The store validates them before commit and never calls the network. MergeChanges preserves first-seen order and deduplicates exact intents.

IdentityStore.CreateGuest inserts a Player and its one Session atomically. LookupByBearerHash and LookupByPlayer return stored SessionVerification{Principal, ExpiresAt}, nil on absence and errors on infrastructure failure. CredentialHash is a SHA-256 [32]byte. The verifier, not the lookup, rejects expired sessions. Authenticator.Authenticate takes the complete Authorization header; IssueConnectionToken takes its verified result. Neither input grants caller-chosen identity.

SubscriptionAuthorizer.AuthorizeSubscription(ctx, authenticatedPlayerID, canonicalChannel) returns SubscriptionAuthorization.AllowedUntil; use typed ErrPermissionDenied/ErrUnauthenticated for denials and ErrUnavailable for outages. Parsing enforces syntax; policy validates game registration separately. ChangePublisher.PublishChange(ctx, lobby, change, stillDue) pushes a committed change: one lobby.changed invalidation carrying the room's version when PublicChanged, and an unsubscribe from the room channel for each revocation, which covers every device of that player. Before every attempt it asks the RevocationCheck whether each revocation still applies.

BuildSnapshot filters inactive history, orders active members and teams, copies nullable fields and the frozen roster, emits non-null arrays and excludes leases/session information. Its caller must normalize under lock before building the response. The HTTP adapter separately enforces presence for required nullable team_id and required boolean ready before creating domain requests.

Changing a lobby's settings

The host can replace a waiting lobby's game_settings and teams, as often as they like, with PUT /lobby/v1/games/{game_key}/lobbies/{lobby_id}/settings and {teams, game_settings?}, the same two fields with the same rules as a create request (ChangeSettings, in application/settings.go). A game whose settings decide the number of teams, such as an Island Battles map, sends the new teams with them.

  • Who and when. An active member that isn't the host gets not_host, and someone else not_found; a lobby that isn't waiting is phase_conflict. Invalid teams are invalid_input and settings the game refuses invalid_game_settings, checked before the transaction as on create.
  • Teams, rebuilt by position. The lobby's first team keeps its ID and order and takes the first new name, and so on, so members on kept teams stay where they are. New teams are added at the end. Teams beyond the new count are deleted: a person on one stays in the lobby without a team, and a seat on one is removed as DELETE …/seats/{seat_id} removes it, leaving inactive history. A change that would leave more members than teams (every person, and each seat on a kept team) fails with lobby_full and changes nothing; the host removes a seat or picks more teams.
  • What else changes. Every person's ready is cleared, also on a kept team, so everyone confirms the new settings; seats stay ready. The capacity becomes the new number of teams. The change bumps the version and publishes lobby.changed, like every public mutation. Settings and teams equal to the lobby's, after canonicalization and trimming, change nothing: no version, no event, no ready cleared.
  • Storage. No schema change. Store.Transact accepts changed settings and teams only while the lobby waits and has no start roster, only as a rebuild by position (kept teams keep ID and order, new ones follow in order) and only with the capacity equal to the team count. It writes the teams around the membership writes so no constraint fails halfway: renamed teams first move to a placeholder normalized name and new teams are inserted, then the memberships are written (members leave removed teams, or take new ones), then removed teams are deleted and renamed teams take their new names. Two teams can therefore swap names, and a kept team can take the name of a removed one.
Playing again in the same lobby

A lobby plays one game per round. lobby.round starts at 1. Once the game of the round has ended, any active person in the lobby brings it back to waiting with POST /lobby/v1/games/{game_key}/lobbies/{lobby_id}/reopen (Reopen, in application/lifecycle.go), which returns the snapshot, and the host can start the next game as before the first one.

  • Who and when. Any active person; anyone else, including a member who left during the game, gets not_found. A lobby that already waits comes back unchanged, so two members who reopen it at once both succeed and the second call is a no-op. A closed lobby, or one of a game that declares no GameOver check, is phase_conflict, and a started lobby whose game hasn't ended game_running (409).
  • What it changes. The phase becomes waiting, round goes up by one, the start roster is emptied and every person's ready is cleared; seats stay ready. Members, teams, seats, the host, the game settings and every member's member settings stay. The change bumps the version and publishes lobby.changed; there is no other event. While the lobby waits, people can join it, members change team and the host changes the settings and seats, as before a first game. A player who left during the game is simply no longer a member.
  • Asking the game. The lobby reads the room, asks the game's GameOver about that round before its transaction, so the game never reads its data while the room is locked, and then checks in the transaction that the lobby is still started in the round it asked about. When another request reopened and started the lobby meanwhile, it asks again about the new round, at most three times. A game that ended stays ended, so the answer can't go stale within a round.
  • Storage. Migration 0008 adds lobby_rooms.round (1 for existing rooms; a check keeps it positive) and gives the stored create responses that a retry replays round: 1. Store.Transact refuses any change to a non-empty start roster and any change of round, except the reopen itself: a started lobby that goes back to waiting must move to the next round with an empty roster, and the store then deletes the roster's rows. The next start writes a new roster. Migration 0009 adds round_started_at (the creation time for existing rooms), which a reopen sets to the time of the reopen; the store refuses a change of it without the round change. A game keeps its games apart by lobby and round, such as Island Battles' unique index on a game's lobby and round, and serves the newest.
Seats that no person plays

The host can fill a team with a seat that the game plays, such as a default bot, and play alone. POST /lobby/v1/games/{game_key}/lobbies/{lobby_id}/seats with {request_id?, team_id, seat_settings} adds one, and DELETE …/seats/{seat_id} removes it; both return the snapshot and publish lobby.changed. seat_settings is the game's own JSON object (Island Battles: {"bot_level": 2}), canonicalized like game settings with NormalizeSeatSettings (at most MaxSeatSettingsBytes) and checked by the game's ValidateSeat for the player making the request, before the transaction, which also names the seat and then checks that the player is the host.

  • Who and when. Only the host (otherwise not_host), only while the lobby waits (otherwise phase_conflict). A team_id that isn't one of the lobby's teams, and a seat_id that names no seat of the lobby, are invalid_input. Removing a removed seat again changes nothing. Adding takes an optional request_id (UUID): repeating it with the same team and settings returns the current snapshot (200) without a second seat, even after the host removed the seat, and with another team or settings fails with idempotency_conflict, as a create does. Without one, each call adds a seat.
  • What a seat is. A seat is a membership of kind seat with its seat_settings, so it has a stable member ID (the seat_id) and its own player ID, which a lobby_players row without a session holds. It takes its team, which then holds no other member (team_full), counts toward the lobby's capacity (lobby_full) and toward the two members a start needs, is always ready on its team, holds no lease, never disconnects and never hosts. Expiry normalization skips it. Two seats of one name are told apart with a number, such as Bot (level 2) #2.
  • Snapshots. Every member has kind, human or seat, and seat_settings, the seat's object or null for a person. Clients show a seat's display_name and leave its readiness alone.
  • Starting. The start roster includes each seat with its player ID and team, like any member, and the started snapshot carries its settings, so the game binding plays it. A start still needs at least one person: the host, who starts it, must be on a team and ready. A lobby whose last person leaves has no host and closes, so seats alone never start. A ReadyGate checks only the roster's people; seats never get ready through it.
  • Storage. Migration 0005 adds kind (human for existing rows), seat_settings and seat_request_id (unique per lobby when set) to lobby_memberships. A seat's player row is inserted with the seat and never reused. When a waiting lobby closes because its last person left, its seats become inactive too. A removed seat stays as inactive history, like a member who left. Retention deletes seats with their lobby, then their players once nothing references them.

Seats are memberships rather than a table of their own so that everything that names a lobby's players keeps working: the start roster's player and member keys and game bindings that read the roster's player IDs. Watchers are a separate table, since they take no seat.

Member settings

Each person in a lobby sets their own settings for the game, such as what plays for them (Island Battles: their bot), with PUT /lobby/v1/games/{game_key}/lobbies/{lobby_id}/member-settings and {"member_settings": {...}} (setLobbyMemberSettings; SetMemberSettings, in application/member_settings.go). It returns the snapshot. The lobby stores the settings without reading them, as it stores seat settings, and the game only checks them, so a game needs no table of its own that refers to the lobby's.

  • Who and when. Only an active member, and only for themselves (someone else gets not_found), and only while the lobby waits (otherwise phase_conflict). Seats have no member settings.
  • Checking. member_settings is canonicalized like seat settings with NormalizeMemberSettings (one JSON object, at most MaxMemberSettingsBytes, 4 KiB) and checked by the game's ValidateMemberSettings with the lobby's ID, before the transaction, so the game never runs while the room is locked. Anything else is 422 invalid_member_settings, whose detail is the game's message; a game without a validator refuses every value.
  • What it changes. New settings clear the caller's ready, so the start always sees what the person confirmed by getting ready again, bump the version and publish lobby.changed. Settings equal to the stored ones, after canonicalization, change nothing: the same version, no event, and the caller stays ready.
  • Snapshots. Every member has member_settings, the object the person set or null, and every member sees every member's. A ReadyGate's check gets each member's settings as ReadyMember.Settings, and the started snapshot carries them, so the game binding reads what each roster player chose from the snapshot.
  • How long they last. They stay when the person leaves and rejoins, and when the lobby is reopened for its next round. Retention deletes them with the lobby.
  • Storage. Migration 0010 adds the nullable member_settings jsonb column to lobby_memberships. jsonb reorders keys and spacing, so the store reads the object back compact with sorted keys, as the lobby wrote it.
Watchers

Anyone with a guest session and a lobby's join code can watch it without taking a seat, in any phase: waiting, started, or closed while the lobby still exists. Watching is generic; the game decides what a watcher may read and publishes it on the lobby's watch channel.

  • Watching. POST /lobby/v1/watches with {game_key, join_code} adds the caller's watcher row, or finds the one they have, and returns {game_key, lobby_id, channel, member}, where channel is watch:<game_key>:<lobby_id>. A wrong code, and a code of another game, are not_found. An active member gets no watcher row and keeps their member access (member: true). DELETE /lobby/v1/games/{game_key}/lobbies/{lobby_id}/watch removes the row and unsubscribes the watcher from the watch channel.
  • Listing and kicking. GET …/watchers lists the watchers that the host hasn't kicked, by display name and player ID, for the lobby's active members. DELETE …/watchers/{player_id} lets the host kick one, in any phase: the publisher unsubscribes them from the watch channel right after the commit, as it does a departing member from the room channel, and the join code no longer lets them watch with that session (watcher_kicked, 403). A kick bars that player ID, which is the guest session, not the person: a new guest session can watch again with the code, and in a waiting lobby a kicked watcher can still join as a member. A kicked watcher's row stays, and leaving doesn't clear it.
  • Cap. A lobby has at most domain.MaxWatchersPerLobby (50) watchers who may watch, kicked and departed ones not counted. A new watcher beyond it is refused with watchers_full (409); one who already watches finds their row as before. Change the constant in domain/types.go to raise or lower it; the web client's sentence and the OpenAPI text don't state the number.
  • Members aren't watchers. An active member gets no watcher row, and a watcher who joins the lobby has their row removed in the join, so watcher_count and the list never count a member. A kicked row stays, and joining doesn't clear it.
  • No effect on the lobby. A watcher counts toward nothing: not the lobby's capacity, a team's member, the start roster, leases, the grace period or retention. Watching doesn't mark the lobby connected, so a watched lobby is deleted when it would be without watchers, and its watcher rows with it. A watcher can't read the members' snapshot, heartbeat or get ready.
  • Snapshots and events. The snapshot's watcher_count counts the watchers who may watch. Starting to watch, leaving and kicking change it, which is a lobby change, announced with lobby.changed.
  • The watch channel. Centrifugo's watch namespace keeps 128 messages of history for 300 s, like the others. The subscribe and sub-refresh proxies allow watch:<game_key>:<lobby_id> for an active member or a watcher that the host hasn't kicked, and never for a channel of another game or lobby. The room channel stays the members'. A game publishes there with realtime.Publisher.Publish and domain.WatchChannel.
  • Game reads. application.Service implements domain.WatchAuthorizer: AuthorizeWatch(ctx, principal, scope) admits an active member or a watcher the host hasn't kicked, returns watcher_kicked for a kicked one and not_found otherwise, also for a lobby that is gone. A game uses it for the reads it opens to watchers. It reads only the principal's player ID, which a player token gives the game.
  • Storage. Migration 0006 adds lobby_watchers (lobby_id, player_id, display_name, joined_at, kicked_at), keyed by lobby and player. The aggregate carries the rows, kicked ones included; a store refuses a mutation that removes a kicked row, and writes only the rows a mutation changed, so heartbeats write none. Both foreign keys are ON DELETE CASCADE, so a build that doesn't know the table can still delete lobbies and players once watcher rows exist. Retention deletes them with their lobby, and a player is deleted only once no watcher row references them.

Production dependencies are SystemClock{} (UTC wall clock) and CryptoIdentifiers{} (cryptographic UUIDv4, unbiased join-code sampling, random byte slices). Their methods perform clock/random reads only when called; pure validation/copy helpers do not use them. Bytes rejects negative lengths without panicking.

Pushing changes to clients

Postgres holds only state. No table holds messages waiting to be sent, and nothing runs between requests:

  • application.NewPublishingStore(store, publisher) wraps a domain.Store. After Create or Transact commits, it pushes the change before returning, so the request that made a change also delivers it. Before each unsubscribe attempt it re-reads the room and skips a player who holds a newer active membership, so a push that waits between retries never drops the subscription of a player who rejoined meanwhile.
  • realtime.NewPublisher(client, logger, realtime.DefaultPushRetry()) is the shared helper that pushes to Centrifugo's HTTP API. It sends all of one call's messages in a single request, makes up to three attempts within about a second, and retries only the messages that failed, with stable idempotency keys. What still fails is logged as an error and returned. The commit stands, and clients recover by re-reading over HTTP. PublishChange serves the lobby, and Publish(ctx, ...Publication) serves a game's own events, such as Island Battles' generation events on PlayerChannel.
  • Expiry is applied lazily. Every command, the heartbeat included, and every Centrifugo subscribe or sub-refresh proxy call normalizes due lease and grace deadlines in its transaction and pushes the result. A lobby with a connected member is therefore normalized within one heartbeat or refresh, and a lobby nobody is connected to is normalized on its next access.

Centrifugo keeps history for the lobby, player and watch namespaces, so a reconnecting client recovers recent messages before it reconciles over HTTP.

Deleting old data

Lobby data is deleted once it is past its retention period, in small batches at the end of lobby requests. There is no timer, so when nobody uses the lobby nothing runs, and nothing grows either. Policy.Retention holds the periods, and DefaultRetention() gives:

Data Deleted Default
Create requests After the idempotency window, or with the lobby they created. A retry inside the window replays the original response; a later one, or one after its lobby was deleted, creates a new lobby. 24 hours after the request
Sessions After they have been expired for a grace period, which covers requests that verified one just before it expired 1 hour after expiry
Players, seats' players included Once no session, room host, membership, watcher, start roster or create request references them. Only players older than a session and its grace are checked, since younger ones still have theirs. As soon as nothing references them
Lobbies, in any phase, with their teams, memberships, watchers, leases and start roster When nobody has been connected for the idle period, and in any case at the maximum age, counted from the start of its current round: its creation, or the last time it was reopened. A GameRegistration.Retention can override either period for its game. 1 hour idle, 1 day since its round started

Each room records last_connected_at, the last time a client created, joined, heartbeated, released a lease or left. Reading a snapshot doesn't count. It also records round_started_at, when its current round began: its creation for round 1, and the time of the last reopen for later rounds, so a group that plays again in one lobby is not cut off in the middle of a round. Nothing else restarts the maximum age, and created_at keeps its meaning. round_started_at is not part of the snapshot or its events. The idle period and the maximum age must both be longer than a lease plus its grace, so a member who can still reconnect never loses the lobby to idleness. Started lobbies are deleted like the others: a game authorizes from its own frozen roster, takes no part in cleanup and keeps working after its lobby is gone.

  • postgres.NewRetentionStore(db) implements domain.RetentionStore. DeleteExpired(ctx, policy.RetentionCutoffs(now)) deletes create requests, then sessions, then lobbies, then the players they freed. Each step is its own transaction that locks at most BatchSize rows with FOR UPDATE SKIP LOCKED and deletes them, child rows before rooms. The steps are independent: one that fails is reported in the returned error, and the later steps still run. A lobby that a request holds is left for a later pass, so a pass never waits on a lobby in use, and passes on different instances don't wait on each other. It touches only lobby tables.
  • application.NewRetention(store, clock, policy, logger) decides when a pass runs. RunIfDue(ctx) runs one when PassInterval has passed since the last pass in this process, or right away when the last pass filled a batch, so a backlog drains a batch per request. Only one pass runs at a time per process, and other requests skip instead of waiting. A pass outlives a canceled request, has its own 5 second timeout, and logs failures instead of failing the request.
  • httpapi.Register(api, app, authenticator, issuer, playerTokens, retention) calls RunIfDue after each lobby request. Pass nil to delete nothing.

The defaults are a batch of 50 rows of each kind and a pass interval of one minute. A pass that finds nothing costs four indexed queries, about once a minute per instance, and a full pass is four short transactions that each lock at most 50 rows, typically a few milliseconds. Retention periods are hours long, so a minute's delay doesn't matter. A backlog, such as the first pass on a database that never deleted anything, drains at 50 rows of each kind per lobby request without making any one request much slower.

Player tokens

A game learns who sends a request from a player token: a short-lived JWT that the lobby signs and the game verifies with the lobby's public keys, without the lobby's database and without a call to the lobby per request. The guest credential stays the lobby's own: a game never sees it.

  • Getting one: a client calls POST /lobby/v1/player-tokens (operation issuePlayerToken) with its guest credential and {"game_key": "island-battles"}, and gets {"token", "expires_at"}. A game_key that no registered game has is not_found. The client sends the token to the game as Authorization: Bearer <token>, gets a new one at about 80 % of its life, and once more when the game answers 401.
  • The token: a compact JWS signed with Ed25519, header {"alg": "EdDSA", "kid": …, "typ": "JWT"}. Its claims are iss, the lobby's public URL; sub, the player ID; aud, the game key; iat and exp, Unix seconds; and name, the player's display name, so the game needs no name lookup. A token lasts 15 minutes, and never past its session's expiry.
  • The keys: the host passes auth.NewPlayerTokens(keys, issuer, lifetime, clock, policy) to httpapi.Register. playertoken.ParseKeySet reads the keys from LOBBY_PLAYER_TOKEN_KEYS, a comma-separated list of kid:seed pairs, where seed is a 32-byte Ed25519 seed in base64url without padding. The first key signs; all are published at GET /lobby/v1/jwks.json (operation getLobbyPublicKeys), a JWKS with Cache-Control: public, max-age=300. To rotate, put the new key first and keep the old one for 15 minutes, the longest a token lasts, then remove it. Island Battles' deploy, for example, does this as its deploy README describes. LOBBY_PLAYER_TOKEN_LIFETIME can shorten tokens for development, from 1m to 15m.
Verifying players in a game

A game imports the game-neutral package playertoken, which depends on nothing else in the lobby:

keys, err := playertoken.NewJWKSSource("https://lobby.example.org/lobby/v1/jwks.json")
verifier, err := playertoken.NewVerifier("https://lobby.example.org", keys)

token, ok := playertoken.FromAuthorization(request.Header.Get("Authorization"))
player, err := verifier.Verify(ctx, token, "quiz-demo") // player.ID, player.Name

Verify checks the header's alg, which must be EdDSA (so none and HS256 are refused), the signature with the key that kid names, iss, aud (the game's own key) and exp, with 30 seconds of leeway. Every failure is playertoken.ErrInvalid, which the game answers with 401. Any other error means the keys couldn't be read, such as an unreachable lobby; answer it with 503.

  • JWKSSource fetches the JWKS on first use and keeps it for the response's max-age. A token that names a kid it doesn't have makes it fetch again, so a new key works at once, but it fetches at most once a minute, so forged kids can't flood the lobby. When a fetch fails, it keeps the keys it has.
  • While the lobby and the game run in one process, as in Island Battles, the lobby's *playertoken.KeySet is itself the key source: playertoken.NewVerifier(issuer, keys).

Binding a game to a started lobby

Game integrations reuse three entry points:

  • application.NewGameBinding(gameKey, snapshotReader, persist) checks scope, current membership, host, started phase, and frozen roster/team consistency on every request, including replays. The callback receives all configured teams in order and returns the game's own result type. Use the lobby application as the snapshot reader so membership expiry is normalized before authorization. A lobby that was reopened and started again binds again: the snapshot's lobby.round tells the rounds apart, so a game binds one game per lobby round.
  • httpapi.RegisterGameBinding(api, operation, binding, authenticator) registers a game-owned POST endpoint accepting {game_key, lobby_id}. It supplies bearer authentication, principal extraction, typed success responses, and shared problem responses. The operation supplies its path, ID, tags, and description. Game endpoints are registered explicitly and remain outside the lobby-only SDK export.
  • postgres.BindOnce(database, uniqueLobbyConstraint, load, create) supplies the transaction and concurrent-conflict recovery for PostgreSQL-backed games. load returns nil when absent and an error for incomplete stored game state. create writes the game and its associated state using the supplied transaction. Only a conflict on the specified unique lobby-link constraint triggers a reload; all other errors roll back and propagate. Pass a database with the request context attached.

A game's constructor only selects its key and connects its persistence callback:

binding, err := application.NewGameBinding("quiz-demo", lobbyService,
    func(ctx context.Context, started domain.Snapshot) (QuizMatch, error) {
        return quizStore.Bind(ctx, started)
    })

quizStore.Bind owns the game's schema, result type, and translation of lobby teams into game state. It must atomically create or return the same game for the lobby round; PostgreSQL integrations can use BindOnce for that orchestration. It must not start external side effects inside the transaction. No game rows are created by the normal lobby start operation.

These in-process helpers remain for a game in the lobby's own process. Island Battles no longer uses them: it binds over HTTP. Generic lobby code imports no game and does not assume numeric game IDs or team colors.

Binding a game over HTTP

A game can run in a service of its own, in any language: the lobby calls its hooks over HTTP, and the game reads the lobby through the game API. Package gamehooks implements both sides for Go, and mockgame is a small game built on it that the lobby's integration tests play against, over real HTTP servers (mockgame/integration_test.go); cmd/mock-game serves it for the live suite (integration README). A game can still be registered in the lobby's own process with Go functions, as before.

Island Battles is the example HTTP game (its backend README), in its own repository. Its LOBBY_GAMES entry is backend/lobbyadapter/lobby_game.json, with hooks_url at the game's /game/lobby-hooks and its secret in LOBBY_GAME_SECRET_ISLAND_BATTLES. It serves its hooks with gamehooks.NewHandler: its settings, seat and member settings validators, a ready check that answers from the request's members unless an uploaded bot needs its package read, or, at the start, its bot seats, a start that binds the round's game with BindOnce-style idempotence, and round-ended. It reads lobbies and authorizes watchers with gamehooks.GameAPIClient, and verifies players with playertoken. Locally and in the live tests, the lobby runs on its own (cmd/lobby) and the backend reaches it at ISLAND_BATTLES_LOBBY_URL. In production, until the lobby is deployed on its own, the backend builds the lobby in its own process and Lambda with app, and both sides send their requests through an http.RoundTripper that calls the other side's http.Handler in memory; the requests are signed and checked as over a network.

Configuration

The host lists the games it calls in LOBBY_GAMES, a JSON array; gamehooks.LoadGames(os.LookupEnv) reads it:

[{"key": "example-game", "name": "Example Game",
  "hooks_url": "https://game.example.com/game/lobby-hooks",
  "secret_env": "LOBBY_GAME_SECRET_EXAMPLE_GAME",
  "start_rules": {"every_team_needs_member": true},
  "retention": {"idle_period": "2h", "maximum_age": "48h"},
  "frontend": {"result_url": "/game/{lobby_id}/result"}}]
  • key, name, hooks_url and secret_env are required. hooks_url uses https, or http for a loopback host such as 127.0.0.1 in development and tests. secret_env names the environment variable that holds the game's shared secret, at least 32 bytes; the configuration never holds the secret itself. Unknown fields are refused.
  • start_rules and retention are fixed by the configuration, as a registration's StartRules and Retention fields are; retention periods are Go durations, and an absent one keeps the default.
  • frontend is the game's frontend catalog entry, every field of frontend.Game but key and name, which come from the game's. A game on a site of its own, which the lobby page loads its screens from, names that site as origin and gives absolute URLs there, such as {"origin": "https://game.example.org", "result_url": "https://game.example.org/game/{lobby_id}/result"}: https, or http on localhost for local development. The lobby refuses to start with a URL on any other origin. Its site must answer the lobby's origin with CORS (Mount it with a game catalog).

Each gamehooks.ConfiguredGame holds the game's Registration, whose hooks call the game (gamehooks.Client), its Frontend entry and its Secret. The host adds gamehooks.Registrations(games) to its policy, the frontend entries to its catalog, and serves the game API with httpapi.RegisterGameAPI(api, lobbyService, gamehooks.Secrets(games)) on a Huma API of its own, so the player API's document never lists it.

Hooks: the lobby calls the game

Each hook is POST {hooks_url}/<hook>, with a JSON body, signed (see below), and has 5 seconds to answer.

Hook Body Answer Registration field
validate-settings {lobby_id, settings, teams}; lobby_id is absent while the lobby is being created 204, or 422 to refuse ValidateSettings
validate-seat {lobby_id, player_id, settings}; player_id is the player adding the seat, whom the lobby checks to be the host only afterwards 200 {display_name}, or 422 ValidateSeat
validate-member-settings {lobby_id, settings} 204, or 422 ValidateMemberSettings
ready-check {lobby_id, members: [{player_id, display_name, settings}], at_start} 204, or 409 with code game_requirement ReadyGate
start {snapshot}, the started lobby as GET on the game API returns it 200 {game_id} StartGame
round-ended {lobby_id, round} 200 {ended} GameOver
  • A refusal is an application/problem+json body. The detail of a 422 becomes the detail of the lobby's invalid_game_settings, invalid_seat_settings or invalid_member_settings, and the type and detail of a 409 game_requirement reach the player unchanged. Both are shown to players, so write them for players.
  • A transport error, a timeout, a 5xx, and any answer the table doesn't allow (a 401 included) make the player's request fail with 503 unavailable, as when an in-process game is unavailable. The start hook is the exception: see below.
  • settings are canonical JSON objects, compact with sorted keys; a member's settings are null when they set none. teams are the request's validated teams, [{name}], in order.
  • ready-check runs inside the transaction of the ready or start request, so it holds the lobby's row lock while it runs, and other requests to the lobby wait for it: answer it quickly, from its body. The other hooks run outside any transaction. A game can read the lobby through the game API from any hook, since the game API reads without waiting for the lock.
  • round-ended must answer true for a round whose start created no game, so the lobby is never stuck, and a round that ended must stay ended.
Starting idempotently
  1. The host's POST …/start commits the start: the lobby is started, with its frozen roster, before the game hears of it.
  2. The lobby then calls start with the snapshot. The game creates the game of the lobby's round, or finds the one it already created for that lobby and round, and answers its ID. It must bind idempotently by (lobby, round): a timed-out call may have succeeded, and two start requests can call it at once. postgres.BindOnce does this for a game on PostgreSQL.
  3. When the game confirms, the lobby records the round in lobby_rooms.bound_round and answers the start request with the snapshot. Later start requests return the snapshot without calling the game.
  4. When the call fails, the start request fails with 502 game_unavailable, and the lobby stays started. The host's next POST …/start calls start again. Nobody else's does: a start request from another member fails with not_host first.
Signing

Every hook call and every game API request carries Lobby-Signature: t=<unix seconds>,v1=<hex HMAC-SHA256(secret, t + "." + method + " " + path + "." + body)>, with the game's shared secret. path is the request's path as sent, without the query; body is the raw body, empty for a GET. For example, the secret 0123456789abcdef0123456789abcdef signs POST /game/lobby-hooks/start with the body {} at 1700000000 as t=1700000000,v1=3c6505b8849a6df2536beae76ee23be92057394a296d73decbd889a150d20c5d.

The receiver refuses with 401 a signature that is missing or malformed, more than 5 minutes from its clock either way, or whose HMAC differs, compared in constant time; it checks the signature before it reads anything else. In Go, gamehooks.Sign and gamehooks.Verify do this, and gamehooks.NewHandler(secret, registration) serves a game's hooks from the Go functions of a domain.GameRegistration: it verifies the path the lobby sent, so it can be mounted under any prefix, with or without http.StripPrefix, but not behind a proxy that rewrites the path.

Game API: the game reads the lobby

Under /lobby/v1/game-api/games/{game_key}/, signed with that game's secret, so a game reaches only its own key; its OpenAPI document is api/game-api.openapi.json. In Go, gamehooks.NewGameAPIClient(key, lobbyURL, secret) calls it.

  • GET lobbies/{lobby_id} returns the lobby's snapshot as the game sees it: the player API's snapshot with every member and no player behind it, so membership_generation is 0. It replaces the in-process SnapshotReader. A lobby that is gone, or another game's, is 404.
  • POST lobbies/{lobby_id}/authorize-watch with {player_id} answers 204 for an active member or a watcher the host hasn't kicked, and 403 otherwise, with the code watcher_kicked for a kicked watcher and permission_denied for anyone else. It replaces WatchAuthorizer.AuthorizeWatch; GameAPIClient.AuthorizeWatch implements that interface.
A game author's checklist
  • Pick a key (lowercase letters, digits and single hyphens) and a shared secret of at least 32 random bytes, and give the lobby's host the LOBBY_GAMES entry and the secret's environment variable.
  • Serve all six hooks under one URL, over https. Check Lobby-Signature on every call, before anything else, and refuse with 401.
  • Answer within 5 seconds. Return 422 with a detail for players to refuse settings, 409 game_requirement with your own problem type to keep a member from getting ready, and 5xx only when you can't decide.
  • Answer ready-check quickly, from its body: the lobby waits for it with the lobby locked.
  • Make start idempotent by (lobby ID, round), and answer the same game_id every time for a round.
  • Make round-ended true for a round that has no game, and keep a round ended once it is.
  • Read lobbies and authorize watchers through the signed game API, not the lobby's database.
  • Authenticate players with player tokens for your game key, verified with the lobby's JWKS, never with the guest credential.
  • Add your frontend entry (result URL, modules, links) to frontend in LOBBY_GAMES.

Admin MCP tools

adminmcp answers an operator's questions about lobbies and players through Model Context Protocol tools, on a server built with the official Go SDK. A game's own admin server registers them next to its game tools; Island Battles, for example, does so in backend/cmd/admin-mcp.

  • adminmcp.OpenDatabase(ctx, url, logger) connects with a single connection whose sessions start with default_transaction_read_only=on and a 5-second statement_timeout. Statements always use the extended protocol, so one query is one statement. A superuser's sessions SET ROLE pg_read_all_data, with a warning, because a read-only transaction leaves a superuser powers such as reading server files. That is best-effort; only a role that is not a superuser makes the tools fully read-only.
  • adminmcp.ReadOnly(ctx, db, read) runs read in a read-only transaction that is always rolled back, so a SET in it ends with it, and then releases the session's advisory locks, which outlive the rollback. Every tool runs in one, the game's included.
  • adminmcp.CheckCredentialsHidden(transaction) fails with ErrCredentialsReadable when a role that is neither a superuser nor the table's owner can read lobby_sessions.bearer_hash, such as a read-only role whose grants a migration has outrun. Run it before any SQL an operator writes.
  • adminmcp.AddTools(server, db, options) registers overview, list_lobbies, get_lobby and find_players. They read only the lobby_* tables, through the records in postgres/models.go, and never the sessions' bearer_hash. Options.Games adds the game's counts to overview and the linked game's ID to each lobby. A game keeps its data in a database of its own, never the lobby's, so Games.Overview and Games.GameIDs take the call's context and read the game's database themselves, such as in their own ReadOnly transaction.

A member counts as connected while a lease of its current membership has neither expired nor been released, as domain.NormalizeExpired decides. The tools read this from the timestamps but never apply expiry, so they change nothing. get_lobby says when retention deletes the lobby at the latest, from Options.LobbyRetention, which defaults to DefaultRetention().

Licence

MIT.

Directories

Path Synopsis
Package adminmcp answers an operator's questions about lobbies and players through Model Context Protocol tools.
Package adminmcp answers an operator's questions about lobbies and players through Model Context Protocol tools.
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.
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.
Package application coordinates lobby commands, game binding, and pushing committed changes.
Package application coordinates lobby commands, game binding, and pushing committed changes.
Package auth issues and verifies generic lobby guest credentials.
Package auth issues and verifies generic lobby guest credentials.
Command lobby-example is a small manual client for the generic lobby API.
Command lobby-example is a small manual client for the generic lobby API.
cmd
export-lobby-openapi command
Command export-lobby-openapi writes the player-facing lobby OpenAPI document, the invalidation event schema and the game API's own OpenAPI document, without constructing any production infrastructure.
Command export-lobby-openapi writes the player-facing lobby OpenAPI document, the invalidation event schema and the game API's own OpenAPI document, without constructing any production infrastructure.
lobby command
Command lobby serves the lobby on its own with net/http, for local development and live tests.
Command lobby serves the lobby on its own with net/http, for local development and live tests.
lobby-lambda command
Command lobby-lambda serves the lobby from AWS Lambda behind a Function URL.
Command lobby-lambda serves the lobby from AWS Lambda behind a Function URL.
migrate command
Command migrate brings the lobby's database to the schema this build expects: the lobby's versioned migrations (postgres.Migrate), which keep existing rows, and nothing else.
Command migrate brings the lobby's database to the schema this build expects: the lobby's versioned migrations (postgres.Migrate), which keep existing rows, and nothing else.
mock-game command
Command mock-game serves the lobby's mock game, package mockgame, over HTTP, so that live tests can configure a lobby host with a game that it calls over HTTP, as integration/run.py --mock-game does.
Command mock-game serves the lobby's mock game, package mockgame, over HTTP, so that live tests can configure a lobby host with a game that it calls over HTTP, as integration/run.py --mock-game does.
Package domain defines game-independent membership contracts and domain logic.
Package domain defines game-independent membership contracts and domain logic.
Package frontend serves the temporary browser client for the generic lobby API.
Package frontend serves the temporary browser client for the generic lobby API.
Package gamehooks lets the lobby call a game over HTTP, and a game read the lobby over HTTP, so that the two can run as separate services.
Package gamehooks lets the lobby call a game over HTTP, and a game read the lobby over HTTP, so that the two can run as separate services.
Package httpapi exposes the reusable, player-facing lobby API.
Package httpapi exposes the reusable, player-facing lobby API.
internal
optional
Package optional handles detached copies and value equality for nullable fields.
Package optional handles detached copies and value equality for nullable fields.
testutil
Package testutil provides disposable infrastructure for lobby package tests.
Package testutil provides disposable infrastructure for lobby package tests.
Package mockgame is a tiny game that the lobby calls over HTTP, for the lobby's own tests.
Package mockgame is a tiny game that the lobby calls over HTTP, for the lobby's own tests.
Package playertoken signs and verifies the lobby's player tokens: short-lived JWTs that tell a game which player sends a request, so the game needs neither the lobby's database nor a call to the lobby for each request.
Package playertoken signs and verifies the lobby's player tokens: short-lived JWTs that tell a game which player sends a request, so the game needs neither the lobby's database nor a call to the lobby for each request.
Package postgres contains PostgreSQL adapters for the generic lobby domain.
Package postgres contains PostgreSQL adapters for the generic lobby domain.
Package realtime adapts authenticated Centrifugo subscriptions and publications to the generic lobby.
Package realtime adapts authenticated Centrifugo subscriptions and publications to the generic lobby.

Jump to

Keyboard shortcuts

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