server

package
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Oct 8, 2026 License: MIT Imports: 26 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package server wires HTTP routes and the WebSocket handshake to the lobby.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ParsePrefixes

func ParsePrefixes(s string) ([]netip.Prefix, error)

ParsePrefixes reads a comma-separated CIDR list ("" = none). A bare address counts as a single-host prefix.

Types

type AdmitRequest added in v0.4.0

type AdmitRequest struct {
	Who  room.Who
	Kind string // the handshake request: netproto.TQuick, TCreate or TJoin ("quick", "create", "join")
	Code string // join only: the room code as sent, upper-cased when well formed; it may name no room
}

AdmitRequest is what Admit decides on. It may gain fields; build it keyed.

type Admitter added in v0.4.0

type Admitter interface {
	Admit(req AdmitRequest) (code string, ok bool)
}

Admitter is optional on a Kit: Admit decides whether a player may go on at all, before quick play, create or join-by-code touches a room. A refusal (ok false) reaches the player like a room.Refuse code (same shape rules; a bad code becomes the core's full-room error) and no room is made, joined or counted against the room cap or the create and join limits; the core counts it as the "admit" reject. It runs on connection goroutines: keep it pure and safe for concurrent use; it must not block.

type BoardID added in v0.2.0

type BoardID struct{ Period, Key string }

BoardID names one leaderboard: GET /api/leaderboard?period=<Period>&key=<Key> (a missing key is ""). Key is the game's (Dogfight: none; a racing game: a track).

type Class

type Class uint8

Class is the rate class of a game message type (core types have their own).

const (
	ClassAll    Class = iota // only the connection's shared bucket
	ClassChoice              // the small choice bucket (pick-like; refusal kicks), then the shared one
)

type Kit

type Kit[S, M, X any] interface {
	Version() int                               // protocol version a hello must carry
	Decode(b []byte) (M, error)                 // one whole frame; the core reads Head()
	Settings(create M, now time.Time) (S, bool) // room settings of a create message; false = bad_room
	QuickSettings(now time.Time) S              // the room quick play makes when none is free
	Class(t string) Class                       // rate class of a game message type
	InRoom(m M) bool                            // a game message allowed after the handshake
	Row(s room.Summary[X]) any                  // one /api/rooms row
}

Kit is what a game plugs into the server. Its methods run on connection and HTTP goroutines: they must not touch shared state.

type Limits

type Limits struct {
	MaxConns         int     // open game sockets, server-wide
	MaxConnsIP       int     // open game sockets per client address
	MaxConnsNet      int     // open game sockets per IPv6 /48, summed over its /64 addresses
	CreatePerMinIP   float64 // room creations per address per minute (burst = same)
	JoinFailPerMinIP float64 // failed joins per address per minute (burst = same)
	JoinPerMinIP     float64 // successful joins per address per minute (burst = same)
	MsgRate          float64 // inbound messages per second per connection
	MsgBurst         int
	PickRate         float64 // pick messages per second per connection
	PickBurst        int
	PingRate         float64 // ping messages per second per connection
	PingBurst        int
	APIPerMinIP      float64 // JSON API requests per address per minute
	APIBurst         int
}

Limits bounds what one address, one connection and the whole server may use. Zero (or negative) fields take the defaults in DefaultLimits.

func DefaultLimits

func DefaultLimits() Limits

type Msg

type Msg[M, In any] interface {
	room.Msg[In]
	Latch(dropped M) M // m plus the one-shot presses of an input dropped over its rate
}

Msg is a decoded client message as the server sees it.

type Options

type Options struct {
	Web              fs.FS          // built client; index.html at the root
	Lag              time.Duration  // artificial outbound latency
	Origins          []string       // allowed WebSocket origin hosts; empty = same host only
	HandshakeTimeout time.Duration  // hello + create/join must finish within it; default 5s
	TrustProxy       []netip.Prefix // peers whose X-Real-IP names the client
	ConnectSrc       []string       // extra CSP connect-src sources, e.g. wss://host
	Limits           Limits
	Now              func() time.Time  // clock for the limiters; default time.Now
	Stats            Stats             // nil or not ready: /api/leaderboard and /api/me answer 503
	Metrics          *metrics.Registry // nil = not measured
}

type Server

type Server[S any, M Msg[M, In], In room.Input[In], X any] struct {
	// contains filtered or unexported fields
}

Server is the HTTP handler: the client at / and /r/{code}, static files under /, /healthz, the JSON API under /api/ (rooms, leaderboard, me), and the game socket at /ws. S, M, In and X are the game's settings, client message, tick input and lobby summary types; k is the game's Kit.

func New

func New[S any, M Msg[M, In], In room.Input[In], X any](l *lobby.Lobby[S, M, In, X], k Kit[S, M, X], o Options) *Server[S, M, In, X]

func (*Server[S, M, In, X]) Conns

func (s *Server[S, M, In, X]) Conns() int

Conns is the number of open game sockets.

func (*Server[S, M, In, X]) Drain

func (s *Server[S, M, In, X]) Drain(on bool)

Drain(true) hands the server over to a new version: players already in a room play on; every new socket is closed with 1012 (msgUpdating), as is each player's socket when its room ends; /api/* answers 503. Drain(false) serves again (rollback).

func (*Server[S, M, In, X]) FlushStats

func (s *Server[S, M, In, X]) FlushStats(ctx context.Context) bool

FlushStats makes every room hand its open tallies to the stats sink (see lobby.FlushStats); the drainer calls it before closing the stats store.

func (*Server[S, M, In, X]) ServeHTTP

func (s *Server[S, M, In, X]) ServeHTTP(w http.ResponseWriter, r *http.Request)

func (*Server[S, M, In, X]) Wait

func (s *Server[S, M, In, X]) Wait()

Wait blocks until every game socket handler has finished, close handshakes included. Call it after http.Server.Shutdown, which stops new sockets; rooms end when the lobby's context is cancelled.

type Stats

type Stats interface {
	Ready() bool
	Boards() []BoardID                  // the leaderboards served: the ?period=&key= whitelist
	Board(id BoardID) []byte            // body of an allowed board; nil = store closed
	Me(pilotHash string) ([]byte, bool) // the caller's body; false = unknown pilot
}

Stats serves the pilot API; nil = stats off (503). Safe for concurrent use.

Jump to

Keyboard shortcuts

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