Documentation
¶
Overview ¶
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.
The lobby calls a game's hooks with POST {hooks_url}/<hook>, JSON in and out, each signed with the game's shared secret (Sign, Verify). Client implements a domain.GameRegistration whose hooks make those calls, and NewHandler serves the hooks of a domain.GameRegistration that a game implements in Go. A game reads the lobby through the signed game API with GameAPIClient. ParseGames reads the games a lobby calls from its LOBBY_GAMES configuration. The lobby README ("Binding a game over HTTP") describes the protocol.
Index ¶
- Constants
- Variables
- func NewHandler(secret []byte, game domain.GameRegistration, options ...HandlerOption) (http.Handler, error)
- func ParseServiceURL(raw string) (*url.URL, error)
- func ReadSigned(request *http.Request, secret []byte, now time.Time) ([]byte, error)
- func Registrations(games []ConfiguredGame) []domain.GameRegistration
- func Secrets(games []ConfiguredGame) func(gameKey string) ([]byte, bool)
- func Sign(secret []byte, at time.Time, method, path string, body []byte) string
- func SignedPath(request *http.Request) string
- func Verify(secret []byte, header string, now time.Time, method, path string, body []byte) error
- func WriteProblem(response http.ResponseWriter, problem Problem)
- type AuthorizeWatchRequest
- type Client
- func (client *Client) ReadyCheck(ctx context.Context, lobbyID string, members []domain.ReadyMember, ...) error
- func (client *Client) ReadyGate(ctx context.Context, lobbyID string) (domain.ReadyCheck, error)
- func (client *Client) Registration(rules domain.StartRules, retention domain.LobbyRetention) domain.GameRegistration
- func (client *Client) RoundEnded(ctx context.Context, lobbyID string, round int64) (bool, error)
- func (client *Client) Start(ctx context.Context, snapshot domain.Snapshot) (string, error)
- func (client *Client) ValidateMemberSettings(ctx context.Context, lobbyID string, settings json.RawMessage) error
- func (client *Client) ValidateSeat(ctx context.Context, lobbyID, playerID string, settings json.RawMessage) (string, error)
- func (client *Client) ValidateSettings(ctx context.Context, lobbyID string, settings json.RawMessage, ...) error
- type ConfiguredGame
- type GameAPIClient
- type GameConfig
- type HandlerOption
- type Option
- type Problem
- type ReadyCheckRequest
- type ReadyMember
- type RetentionConfig
- type RoundEndedRequest
- type RoundEndedResponse
- type StartRequest
- type StartResponse
- type ValidateMemberSettingsRequest
- type ValidateSeatRequest
- type ValidateSeatResponse
- type ValidateSettingsRequest
Constants ¶
const ( // HookValidateSettings checks a lobby's game settings: // ValidateSettingsRequest, answered with 204, or 422 to refuse them. HookValidateSettings = "validate-settings" // HookValidateSeat checks a seat's settings and names the seat: // ValidateSeatRequest, answered with ValidateSeatResponse, or 422. HookValidateSeat = "validate-seat" // HookValidateMemberSettings checks a person's member settings: // ValidateMemberSettingsRequest, answered with 204, or 422. HookValidateMemberSettings = "validate-member-settings" // HookReadyCheck decides whether members may be ready: // ReadyCheckRequest, answered with 204, or 409 with the problem code // game_requirement, whose type and detail reach the player unchanged. HookReadyCheck = "ready-check" // HookStart creates the game of a started lobby's round: StartRequest, // answered with 200 and StartResponse. It must be idempotent by lobby // and round. HookStart = "start" // HookRoundEnded tells whether the game of a lobby's round has ended: // RoundEndedRequest, answered with RoundEndedResponse. HookRoundEnded = "round-ended" )
The hooks a game serves under its hooks URL.
const DefaultTimeout = 5 * time.Second
DefaultTimeout bounds each hook call and each game API request.
const GameAPIPath = "/lobby/v1/game-api"
GameAPIPath is where the lobby serves the game API, under the lobby's URL. A game's routes are under GameAPIPath + "/games/{game_key}".
const GamesEnv = "LOBBY_GAMES"
GamesEnv names the environment variable that lists the games the lobby calls over HTTP, as a JSON array of GameConfig.
const MaxBodyBytes = 1 << 20
MaxBodyBytes bounds the body of a hook call, its answer, and a game API request.
const MaxClockSkew = 5 * time.Minute
MaxClockSkew is how far a signature's time may be from the receiver's clock, either way, before the receiver refuses it as a replay.
const MaxDetailBytes = 1024
MaxDetailBytes bounds the detail of a game's refusal that the lobby passes on to the player. A longer one is cut at a rune boundary.
const MinSecretBytes = 32
MinSecretBytes is the shortest shared secret a game may have.
const ProblemContentType = "application/problem+json"
ProblemContentType is the media type of a Problem.
const SignatureHeader = "Lobby-Signature"
SignatureHeader carries a request's signature, in both directions: on the lobby's hook calls to a game, and on a game's calls to the game API.
Variables ¶
var ErrBadSignature = errors.New("the request's Lobby-Signature doesn't verify")
ErrBadSignature refuses a request whose signature is missing, malformed, too old or too new, or made with another secret. A receiver answers it with 401.
var Hooks = []string{HookValidateSettings, HookValidateSeat, HookValidateMemberSettings, HookReadyCheck, HookStart, HookRoundEnded}
Hooks lists every hook, in the order the lobby's life cycle reaches them.
Functions ¶
func NewHandler ¶
func NewHandler(secret []byte, game domain.GameRegistration, options ...HandlerOption) (http.Handler, error)
NewHandler serves a game's hooks from the Go functions of its registration, so a game written in Go mounts it at its hooks URL. Each request is POST .../<hook>, and the last element of the path names the hook, so the handler can be mounted under any prefix, with or without http.StripPrefix. It refuses a request whose Lobby-Signature doesn't verify with 401, before it reads anything else.
The registration's functions answer as they do in the lobby's own process. A validator's error is a 422 whose detail is the error's message, and a ReadyCheck's domain.GameRequirement a 409 game_requirement; an error that wraps domain.ErrUnavailable, or the context's, is a 503. A hook whose function is nil answers as the lobby treats a nil field: validate-settings accepts only `{}`, validate-seat and validate-member-settings refuse every value, ready-check accepts everyone, and round-ended answers false, so the lobby is never reopened. start needs StartGame, and answers 503 without it. The registration's Key, StartRules and Retention aren't used: the lobby's configuration holds them.
func ParseServiceURL ¶
ParseServiceURL accepts an absolute URL without a query or fragment: https, or http for a loopback host such as localhost or 127.0.0.1, which local development and tests use. A trailing slash is dropped.
func ReadSigned ¶
ReadSigned reads a request's body, at most MaxBodyBytes, and checks its Lobby-Signature with secret. It fails with ErrBadSignature, or with an error reading the body.
func Registrations ¶
func Registrations(games []ConfiguredGame) []domain.GameRegistration
Registrations returns the games' registrations, for the lobby policy.
func Secrets ¶
func Secrets(games []ConfiguredGame) func(gameKey string) ([]byte, bool)
Secrets returns a lookup of the games' shared secrets by game key, for the game API.
func Sign ¶
Sign returns the Lobby-Signature header value of a request: "t=<unix seconds>,v1=<hex HMAC-SHA256>". The HMAC, with the game's shared secret as its key, covers the time, the method, the request path (without the query) and the body, as t + "." + method + " " + path + "." + body.
func SignedPath ¶
SignedPath is the path that a request's signature covers: the path of the request as the client sent it, before any http.StripPrefix.
func Verify ¶
Verify checks a Lobby-Signature header value against the request it came with, at now. It fails with ErrBadSignature when the header is missing or malformed, its time is more than MaxClockSkew from now, or its HMAC differs. The HMACs are compared in constant time.
func WriteProblem ¶
func WriteProblem(response http.ResponseWriter, problem Problem)
WriteProblem answers with a Problem, as application/problem+json. A missing title is the status text.
Types ¶
type AuthorizeWatchRequest ¶
type AuthorizeWatchRequest struct {
PlayerID string `json:"player_id" format:"uuid" doc:"The player who asks to watch, as the lobby names them."`
}
AuthorizeWatchRequest is the body of the game API's authorize-watch.
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client calls one game's hooks, at its hooks URL, for the lobby. Each call is signed with the game's shared secret and has DefaultTimeout. A transport error, a timeout, a 5xx answer or any answer the protocol doesn't allow is reported as unavailable, which the player gets as 503; a game's 422 or 409 refusal becomes the matching lobby error.
func NewClient ¶
NewClient returns the client of the game with key, whose hooks are served under hooksURL (see ParseServiceURL), signed with secret, which has at least MinSecretBytes bytes.
func (*Client) ReadyCheck ¶
func (client *Client) ReadyCheck(ctx context.Context, lobbyID string, members []domain.ReadyMember, atStart bool) error
ReadyCheck calls ready-check. A 409 with the problem code game_requirement is the game's refusal, whose type and detail reach the player unchanged.
func (*Client) ReadyGate ¶
ReadyGate is a domain.ReadyGate whose check calls ready-check. The lobby runs the check inside the transaction of a ready or start request, so the call holds the room's lock for as long as it takes, at most the timeout, and the game should answer it quickly, from the request alone.
func (*Client) Registration ¶
func (client *Client) Registration(rules domain.StartRules, retention domain.LobbyRetention) domain.GameRegistration
Registration declares the game to the lobby policy with hooks that call the game, and the start rules and retention that the configuration fixes.
func (*Client) RoundEnded ¶
RoundEnded calls round-ended; it is a domain.GameOverCheck.
func (*Client) ValidateMemberSettings ¶
func (client *Client) ValidateMemberSettings(ctx context.Context, lobbyID string, settings json.RawMessage) error
ValidateMemberSettings calls validate-member-settings; it is a domain.MemberSettingsValidator.
func (*Client) ValidateSeat ¶
func (client *Client) ValidateSeat(ctx context.Context, lobbyID, playerID string, settings json.RawMessage) (string, error)
ValidateSeat calls validate-seat; it is a domain.SeatValidator.
func (*Client) ValidateSettings ¶
func (client *Client) ValidateSettings(ctx context.Context, lobbyID string, settings json.RawMessage, teams []domain.TeamDefinition) error
ValidateSettings calls validate-settings; it is a domain.GameSettingsValidator.
type ConfiguredGame ¶
type ConfiguredGame struct {
Registration domain.GameRegistration
Frontend frontend.Game
Secret []byte
Client *Client
}
ConfiguredGame is a game from LOBBY_GAMES, ready for the host to add to its lobby policy, its frontend catalog and its game API.
func LoadGames ¶
LoadGames reads LOBBY_GAMES through lookupEnv, such as os.LookupEnv, with ParseGames. Unset or empty, it configures no game.
func ParseGames ¶
func ParseGames(raw string, lookupEnv func(string) (string, bool), options ...Option) ([]ConfiguredGame, error)
ParseGames reads a LOBBY_GAMES value: a JSON array of GameConfig, with unique keys and no unknown fields. Each game's secret is read with lookupEnv. An empty value configures no game.
type GameAPIClient ¶
type GameAPIClient struct {
// contains filtered or unexported fields
}
GameAPIClient is a game's client of the lobby's game API: it reads the game's lobbies and checks their watchers, signed with the game's shared secret. It reaches only the game's own key.
func NewGameAPIClient ¶
func NewGameAPIClient(key, lobbyURL string, secret []byte, options ...Option) (*GameAPIClient, error)
NewGameAPIClient returns the game API client of the game with key, for the lobby at lobbyURL (see ParseServiceURL), such as https://lobby.example.com.
func (*GameAPIClient) AuthorizeWatch ¶
func (client *GameAPIClient) AuthorizeWatch(ctx context.Context, principal domain.Principal, scope domain.Scope) error
AuthorizeWatch checks that a player may watch a lobby of the game, as POST .../lobbies/{lobby_id}/authorize-watch. It is a domain.WatchAuthorizer that reads only the principal's player ID: nil for an active member or a watcher the host hasn't kicked, domain.ErrWatcherKicked for a kicked watcher, and domain.ErrNotFound for anyone else, a lobby that is gone and a scope of another game.
type GameConfig ¶
type GameConfig struct {
Key string `json:"key"`
Name string `json:"name"`
HooksURL string `json:"hooks_url"`
SecretEnv string `json:"secret_env"`
StartRules domain.StartRules `json:"start_rules"`
Retention RetentionConfig `json:"retention"`
Frontend frontend.Game `json:"frontend"`
}
GameConfig is one game in LOBBY_GAMES:
{"key": "example-game", "name": "Example Game",
"hooks_url": "https://game.example.com/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": "…", …}}
The game's shared secret is the value of the environment variable that SecretEnv names, at least MinSecretBytes bytes. StartRules and Retention are optional and fixed by the configuration, as a registration's fields are. Frontend holds the lobby page's catalog entry, frontend.Game, whose key and name come from Key and Name.
type HandlerOption ¶
type HandlerOption func(*hooksHandler)
HandlerOption changes a hooks handler.
func WithHandlerClock ¶
func WithHandlerClock(now func() time.Time) HandlerOption
WithHandlerClock replaces the clock that signatures are checked against.
type Option ¶
type Option func(*transport)
Option changes how a Client or a GameAPIClient calls.
func WithHTTPClient ¶
WithHTTPClient replaces http.DefaultClient. The client's own timeout, if any, applies as well.
func WithTimeout ¶
WithTimeout replaces DefaultTimeout.
type Problem ¶
type Problem struct {
Title string `json:"title,omitempty"`
Status int `json:"status"`
Detail string `json:"detail"`
Code string `json:"code,omitempty"`
// Type is the game's problem type of the code game_requirement.
Type string `json:"type,omitempty"`
}
Problem is the application/problem+json body of a refusal, from a hook or from the game API. Detail of a hook's 422 and 409 is shown to the player.
type ReadyCheckRequest ¶
type ReadyCheckRequest struct {
LobbyID string `json:"lobby_id"`
Members []ReadyMember `json:"members"`
AtStart bool `json:"at_start"`
}
ReadyCheckRequest is the body of ready-check: the one member getting ready, with AtStart false, or the start roster's people in the lobby's member order, with AtStart true.
type ReadyMember ¶
type ReadyMember struct {
PlayerID string `json:"player_id"`
DisplayName string `json:"display_name"`
Settings json.RawMessage `json:"settings"`
}
ReadyMember is a member that ready-check decides about. Settings are the member's member settings, or null when they set none.
type RetentionConfig ¶
type RetentionConfig struct {
IdlePeriod string `json:"idle_period"`
MaximumAge string `json:"maximum_age"`
}
RetentionConfig overrides when a game's lobbies are deleted, as time.ParseDuration strings such as "2h". An empty field keeps the lobby's default.
type RoundEndedRequest ¶
RoundEndedRequest is the body of round-ended.
type RoundEndedResponse ¶
type RoundEndedResponse struct {
Ended bool `json:"ended"`
}
RoundEndedResponse says whether the game of the round has ended. A round whose start created no game counts as ended, so the lobby can't be stuck.
type StartRequest ¶
StartRequest is the body of start: the started lobby as the game reads it through the game API.
type StartResponse ¶
type StartResponse struct {
GameID string `json:"game_id"`
}
StartResponse names the game that start created, or found, for the round.
type ValidateMemberSettingsRequest ¶
type ValidateMemberSettingsRequest struct {
LobbyID string `json:"lobby_id"`
Settings json.RawMessage `json:"settings"`
}
ValidateMemberSettingsRequest is the body of validate-member-settings.
type ValidateSeatRequest ¶
type ValidateSeatRequest struct {
LobbyID string `json:"lobby_id"`
PlayerID string `json:"player_id"`
Settings json.RawMessage `json:"settings"`
}
ValidateSeatRequest is the body of validate-seat. PlayerID is the player making the request, whom the lobby checks to be the host only afterwards.
type ValidateSeatResponse ¶
type ValidateSeatResponse struct {
DisplayName string `json:"display_name"`
}
ValidateSeatResponse names the seat that validate-seat accepted, in at most 40 characters.
type ValidateSettingsRequest ¶
type ValidateSettingsRequest struct {
LobbyID string `json:"lobby_id,omitempty"`
Settings json.RawMessage `json:"settings"`
Teams []domain.TeamDefinition `json:"teams"`
}
ValidateSettingsRequest is the body of validate-settings. LobbyID is absent while the lobby is being created, and Settings is `{}` when the request had none.