La référence API provient des commentaires de documentation Go du code source et est rédigée en anglais.
package gameserver
import "github.com/nsgo-dev/game/pkg/online/gameserver"Vue d’ensemble
Package gameserver is experimental: its API and documented formats may change in a minor release. See the API stability policy. runs one or more matches of a game at fixed tick rates in a plain Go process, without an NSGo app, window or core.Scope.
The Update function a game gives game.Loop runs unchanged here: each match steps it with the same fixed dt, so dedicated-server code and client-side prediction share one simulation.
Index
- Constantes
- Variables
- func Go[T any](m *Match, fn func(context.Context) (T, error), cb func(T, error))
- func GuardCollector(g *Guard) func(io.Writer)
- func InboxCollector(name string, r netplay.InboxReporter) func(io.Writer)
- type AuthConfig
- type Capacity
- type Config
- type Directory
- type Group
- type Guard
- func NewGuard(limits Limits, policy LimitPolicy) *Guard
- func (g *Guard) Check(peer netplay.PeerID, packet netplay.Packet) (GuardAction, error)
- func (g *Guard) ReleaseReliable(peer netplay.PeerID, n int)
- func (g *Guard) ReserveReliable(peer netplay.PeerID, n int) error
- func (g *Guard) Reset(peer netplay.PeerID)
- func (g *Guard) Stats(peer netplay.PeerID) PeerStats
- func (g *Guard) Totals() PeerStats
- type GuardAction
- type Health
- func NewHealth(ready func() bool, metrics func() Metrics) *Health
- func (h *Health) AddCollector(c func(w io.Writer))
- func (h *Health) ObserveMatchTick(match string, d time.Duration)
- func (h *Health) ObserveTick(d time.Duration)
- func (h *Health) OnOverrun(next func(*Match, time.Duration, int)) func(*Match, time.Duration, int)
- func (h *Health) ServeHTTP(w http.ResponseWriter, r *http.Request)
- type HealthConfig
- type InspectMatch
- type InspectPeer
- type InspectProvider
- type InspectRoom
- type Inspector
- type Join
- type LeaveReason
- type LimitPolicy
- type Limits
- type LimitsConfig
- type ListenConfig
- type Match
- type MatchConfig
- type MatchHandler
- type Matchmaker
- type Matchup
- type MemoryDirectory
- func (d *MemoryDirectory) Heartbeat(address string, seenAt time.Time) error
- func (d *MemoryDirectory) List(region string) []ServerInfo
- func (d *MemoryDirectory) Place(region string) (ServerInfo, error)
- func (d *MemoryDirectory) Register(info ServerInfo) error
- func (d *MemoryDirectory) Remove(address string)
- type Metrics
- type NumericRange
- type Panic
- type PanicAction
- type PanicError
- type PeerStats
- type Policy
- type Query
- type Queue
- type RecordGrant
- type Reservation
- type ResultCommit
- type ResultReceipt
- type ResultsBackend
- func NewResultsBackend() *ResultsBackend
- func (b *ResultsBackend) Balance(account, currency string) int64
- func (b *ResultsBackend) BestScore(board, account string) (int64, bool)
- func (b *ResultsBackend) Commit(ctx context.Context, r ResultCommit) (ResultReceipt, error)
- func (b *ResultsBackend) DeliverScores(ctx context.Context, sink ScoreSink) error
- func (b *ResultsBackend) Has(matchID string) bool
- func (b *ResultsBackend) PendingScores() []ScoreGrant
- func (b *ResultsBackend) Record(key string) (RecordGrant, bool)
- type Room
- func (r *Room) Advance()
- func (r *Room) Broadcast(tx netplay.Transport, ch netplay.Channel, payload []byte, except ...netplay.PeerID) []netplay.PeerID
- func (r *Room) Capacity() int
- func (r *Room) Code() string
- func (r *Room) Deliver(from netplay.PeerID, p netplay.Packet) error
- func (r *Room) Drain(budget int, fn func(netplay.Packet)) int
- func (r *Room) End()
- func (r *Room) Epoch() uint64
- func (r *Room) ID() uint64
- func (r *Room) InboxStats() RoomInboxStats
- func (r *Room) MatchData() (epoch uint64, data *datatable.Snapshot)
- func (r *Room) Members() []netplay.PeerID
- func (r *Room) Recv(peer netplay.PeerID) (netplay.Packet, bool)
- func (r *Room) SetHandler(handler MatchHandler)
- func (r *Room) SetLabel(label map[string]string)
- func (r *Room) Signal(ctx context.Context, data []byte) ([]byte, error)
- func (r *Room) Start() error
- func (r *Room) StartWithData(data *datatable.Snapshot) error
- func (r *Room) State() RoomState
- func (r *Room) Terminate(grace time.Duration)
- func (r *Room) Tick() uint64
- type RoomInboxStats
- type RoomInfo
- type RoomLimits
- type RoomState
- type Rooms
- func NewRooms() *Rooms
- func (rs *Rooms) Claim(res Reservation, peer netplay.PeerID) (Join, error)
- func (rs *Rooms) Create(capacity int, private bool) (*Room, error)
- func (rs *Rooms) Join(id uint64, peer netplay.PeerID) (Join, error)
- func (rs *Rooms) JoinCode(code string, peer netplay.PeerID) (Join, error)
- func (rs *Rooms) JoinWithMeta(id uint64, peer netplay.PeerID, account string, meta []byte) (Join, error)
- func (rs *Rooms) Leave(id uint64, peer netplay.PeerID) bool
- func (rs *Rooms) LeaveWithReason(id uint64, peer netplay.PeerID, reason LeaveReason) bool
- func (rs *Rooms) List() []RoomInfo
- func (rs *Rooms) MemberCount() int
- func (rs *Rooms) Reserve(id uint64, account string, ttl time.Duration) (Reservation, error)
- func (rs *Rooms) SetCapacity(c Capacity, busy func() bool)
- func (rs *Rooms) SetLimits(l RoomLimits)
- func (rs *Rooms) Tick() []uint64
- type RoomsConfig
- type Rule
- type Runner
- type RuntimeInfo
- type ScoreGrant
- type ScoreSink
- type ServerInfo
- type SignedReservation
- type TLSConfig
- type Term
- type TermKind
- type Ticket
- type UDPListen
- type WalletGrant
- type WebSocketListen
Constantes
const (
// DefaultRoomInboxPerPeer is the most packets a room queues for one member when RoomLimits.PerPeer is zero.
DefaultRoomInboxPerPeer = 256
// DefaultRoomInboxWarning is the room backlog, across all members, that counts a warning when RoomLimits.Warning is zero.
DefaultRoomInboxWarning = 1024
)const ConfigVersion = 1ConfigVersion is the server.yaml version this package reads and writes.
const DefaultMaxPending = 256DefaultMaxPending is the number of asynchronous jobs a match accepts when Match.MaxPending is zero.
Variables
var (
// ErrMessageTooLarge reports a packet larger than Limits.MaxMessageSize.
ErrMessageTooLarge = errors.New("gameserver: message too large")
// ErrPendingLimit reports reliable bytes past Limits.MaxPendingReliable.
ErrPendingLimit = errors.New("gameserver: pending reliable data limit")
// ErrInvalidInput reports input refused by Guard.Validate.
ErrInvalidInput = errors.New("gameserver: invalid input")
// ErrPeerDisconnected reports a peer the guard has disconnected.
ErrPeerDisconnected = errors.New("gameserver: peer disconnected")
)var (
// ErrInvalidTicket reports a ticket with no player, a NaN rating, a party larger than one team, a non-positive room size, or a Teams count that does not divide the room size.
ErrInvalidTicket = errors.New("gameserver: invalid matchmaking ticket")
// ErrDuplicateTicket reports a ticket ID already waiting in the queue.
ErrDuplicateTicket = errors.New("gameserver: duplicate matchmaking ticket")
)var (
// ErrRoomNotFound reports a room ID or code that names no open room.
ErrRoomNotFound = errors.New("gameserver: room not found")
// ErrRoomFull reports a join to a room already at capacity.
ErrRoomFull = errors.New("gameserver: room full")
// ErrServerBusy reports that admission is capped or the server is overloaded.
ErrServerBusy = errors.New("gameserver: server busy")
// ErrRoomEnded reports an action on a room whose match has ended.
ErrRoomEnded = errors.New("gameserver: room match ended")
// ErrNotInRoom reports a packet from a peer that is not a room member.
ErrNotInRoom = errors.New("gameserver: peer is not in this room")
)var (
// ErrMailboxFull is returned by Post and Call when the match's mailbox
// already holds Mailbox callbacks.
ErrMailboxFull = errors.New("gameserver: match mailbox full")
// ErrMatchStopped is returned by Post and Call once the match has stopped,
// and by a pending Call whose callback was dropped or panicked.
ErrMatchStopped = errors.New("gameserver: match stopped")
)var ErrBusy = errors.New("gameserver: async job queue is full")ErrBusy reports that a match already has its maximum number of asynchronous jobs pending.
var ErrResultConflict = errors.New("gameserver: match result conflict")ErrResultConflict reports a retry that differs from the result already committed for its match, or a record grant whose version does not match the stored record.
var ErrResultInvalid = errors.New("gameserver: invalid match result")ErrResultInvalid reports a result with an empty match ID, record key, wallet account or currency, or score board or account, a record key granted twice, or a nil score sink.
var ErrRoomInboxFull = errors.New("gameserver: room inbox full")ErrRoomInboxFull reports a ChannelReliableOrdered packet refused because its member already has RoomLimits.PerPeer packets queued in the room and none of them is unreliable. Dropping a reliable packet would break its ordering guarantee, so the packet loop should disconnect that peer, as a WebSocketServer ends a client past its reliable cap.
Fonctions
func Go[T any](m *Match, fn func(context.Context) (T, error), cb func(T, error))Go runs fn in the background and invokes cb on the match goroutine before a later Update. A panic in fn is recovered and delivered as an error. If the match has MaxPending jobs already, cb runs immediately with ErrBusy.
func GuardCollector(g *Guard) func(io.Writer)GuardCollector returns a collector for Health.AddCollector that exports the guard's totals as nsgo_server_guard_packets_total, nsgo_server_guard_bytes_total, nsgo_server_guard_dropped_total and nsgo_server_guard_violations_total.
func InboxCollector(name string, r netplay.InboxReporter) func(io.Writer)InboxCollector returns a collector for Health.AddCollector that exports the transport's inbox counters as nsgo_net_inbox_unreliable_dropped_total, nsgo_net_inbox_reliable_refused_total and nsgo_net_inbox_reliable_warnings_total, each labeled transport="name".
Types
type AuthConfig struct {
GracePeriod time.Duration `yaml:"gracePeriod,omitempty"`
IdleTimeout time.Duration `yaml:"idleTimeout,omitempty"`
MaxPeers int `yaml:"maxPeers,omitempty"`
}AuthConfig is a server's admission settings: how long a dropped peer keeps its session, how long a peer may stay silent, and the most peers it holds.
type Capacity struct {
// MaxRooms caps the number of open rooms; Create past it returns ErrServerBusy.
MaxRooms int
// MaxMembers caps the number of members across all rooms; a join of a new member past it returns ErrServerBusy.
MaxMembers int
}Capacity limits process-wide admission across all rooms. A zero field leaves that limit off.
type Config struct {
Version int `yaml:"version"`
Listen ListenConfig `yaml:"listen"`
TLS *TLSConfig `yaml:"tls,omitempty"`
Auth AuthConfig `yaml:"auth,omitempty"`
Limits LimitsConfig `yaml:"limits,omitempty"`
Rooms RoomsConfig `yaml:"rooms,omitempty"`
Match MatchConfig `yaml:"match,omitempty"`
Health HealthConfig `yaml:"health,omitempty"`
}Config is one versioned server.yaml: a dedicated server's listeners, TLS files, admission, per-peer limits, rooms, match rate and health endpoint. It holds file paths, never credentials.
func DefaultConfig() ConfigDefaultConfig returns the settings dedicatedserver init writes: WebSocket on :8443 and UDP on :8444, a 1024-peer allowance with a 15s grace period, disconnect on abuse, four-seat rooms, a 60 Hz match and health on :9090.
func ParseConfig(data []byte) (*Config, error)ParseConfig decodes and validates one server.yaml. It refuses unknown fields and a second YAML document, and returns a *loaderr.Error naming the field and a fix.
func (c *Config) Marshal() ([]byte, error)Marshal validates the config and writes it as deterministic YAML, one field per line in declaration order, so a parsed and rewritten file keeps its bytes.
func (c *Config) Validate() errorValidate reports a wrong version, a server with no listener, a malformed address or origin, half a TLS pair, and an unknown policy or a negative duration, rate, cap or limit.
type Directory interface {
Register(ServerInfo) error
Heartbeat(address string, seenAt time.Time) error
Remove(address string)
List(region string) []ServerInfo
Place(region string) (ServerInfo, error)
}Directory tracks live game-server processes and chooses a placement target.
type Group struct {
// contains filtered or unexported fields
}Group is an ordered set of peers for a room, team or spectator list.
func (g *Group) Add(p netplay.PeerID) boolAdd inserts p once and reports whether the group changed.
func (g *Group) Broadcast(tx netplay.Transport, ch netplay.Channel, payload []byte, except ...netplay.PeerID) []netplay.PeerIDBroadcast sends payload to every member except the peers in except and returns the members whose send failed, in join order.
func (g *Group) Members() []netplay.PeerIDMembers returns peers in join order.
func (g *Group) Remove(p netplay.PeerID) boolRemove deletes p and reports whether the group changed.
type Guard struct {
Limits Limits
Policy LimitPolicy
// Validate rejects an input with an error before the simulation sees it.
// A non-nil error counts one violation for the peer.
Validate func(netplay.PeerID, netplay.Packet) error
// Now is the token-bucket clock; nil uses time.Now.
Now func() time.Time
// contains filtered or unexported fields
}Guard enforces per-peer limits and validates inputs before a simulation sees them. It is safe for concurrent use, so a metrics collector may read Totals while the packet loop checks packets.
func NewGuard(limits Limits, policy LimitPolicy) *GuardNewGuard returns a guard with limits and a policy.
func (g *Guard) Check(peer netplay.PeerID, packet netplay.Packet) (GuardAction, error)Check accounts packet for peer and returns what the caller should do. It rejects an oversized packet before any buffering and runs Validate only for an admitted packet; a rejected input never reaches the caller's simulation.
func (g *Guard) ReleaseReliable(peer netplay.PeerID, n int)ReleaseReliable returns n reserved reliable bytes for peer.
func (g *Guard) ReserveReliable(peer netplay.PeerID, n int) errorReserveReliable reserves n reliable bytes for peer, refusing past MaxPendingReliable.
func (g *Guard) Reset(peer netplay.PeerID)Reset forgets a peer's buckets and counters, for a reconnecting peer. The peer's counters stay in Totals.
func (g *Guard) Stats(peer netplay.PeerID) PeerStatsStats returns a peer's counters.
func (g *Guard) Totals() PeerStatsTotals returns the guard's counters summed across every peer it has seen, including the peers Reset forgot; PendingBytes covers only the peers still tracked.
type GuardAction uint8GuardAction is the result of Guard.Check.
const (
GuardAllow GuardAction = iota
GuardThrottle
GuardDisconnect
)type Health struct {
Ready func() bool
Metrics func() Metrics
// contains filtered or unexported fields
}Health serves a game server's deployment endpoints:
GET /healthz 200 while the process is alive GET /readyz 200 when Ready reports true, else 503 GET /metrics Prometheus text metrics from Metrics
Ready and Metrics are optional; a nil Ready is always ready and a nil Metrics reports zeros. Alongside the Metrics series, /metrics exports a per-match tick histogram and overrun counters (ObserveMatchTick, OnOverrun and Runner.Health) and whatever AddCollector appends, such as GuardCollector and InboxCollector.
func NewHealth(ready func() bool, metrics func() Metrics) *HealthNewHealth returns deployment endpoints.
func (h *Health) AddCollector(c func(w io.Writer))AddCollector appends c to /metrics: every scrape calls c after the built-in series. c writes complete series in the Prometheus text format and must be safe to call from the HTTP handler while the server runs; GuardCollector and InboxCollector are ready-made collectors, and a game may append its own series the same way.
func (h *Health) ObserveMatchTick(match string, d time.Duration)ObserveMatchTick records one tick of the named match in the nsgo_server_match_tick_seconds histogram. A Runner records every tick itself when its Health field is set; a game with its own loop may call ObserveMatchTick directly.
func (h *Health) ObserveTick(d time.Duration)ObserveTick records the duration of the last server tick for metrics.
func (h *Health) OnOverrun(next func(*Match, time.Duration, int)) func(*Match, time.Duration, int)OnOverrun returns a Runner.OnOverrun that counts each overrun and its missed ticks per match in nsgo_server_match_overruns_total and nsgo_server_match_missed_ticks_total, then calls next when next is set.
func (h *Health) ServeHTTP(w http.ResponseWriter, r *http.Request)ServeHTTP handles GET and HEAD requests for /healthz, /readyz, and /metrics, rejecting other methods and paths, the way servicehealth.Serve answers every service's probes.
type HealthConfig struct {
Addr string `yaml:"addr,omitempty"`
}HealthConfig is the host:port of the health and metrics endpoint, or empty to serve none.
type InspectMatch struct {
Name string `json:"name"`
Rate int `json:"rate"`
Ticks uint64 `json:"ticks"`
Overruns uint64 `json:"overruns"`
}InspectMatch is one match the server runs, as /admin/v1/matches lists it: its name, its tick rate in ticks per second, the ticks it has run and how many of them overran their budget.
type InspectPeer struct {
ID uint64 `json:"id"`
Room uint64 `json:"room"`
Inbox int `json:"inbox"`
}InspectPeer is one connected peer, as /admin/v1/peers lists it: its ID, the room it is in and how many messages wait in its inbox.
type InspectProvider interface {
Matches() []InspectMatch
Rooms() []InspectRoom
Peers() []InspectPeer
}InspectProvider supplies the match, room and peer lists an Inspector serves. The application implements it over its own server state; each method is called once per request and must return a snapshot without holding a match's lock across the response.
type InspectRoom struct {
ID uint64 `json:"id"`
State string `json:"state"`
Members int `json:"members"`
Created time.Time `json:"created"`
}InspectRoom is one room the server hosts, as /admin/v1/rooms lists it: its ID, its state, its member count and when it was created.
type Inspector struct {
// Authorizer authenticates operators, such as the *admin.Server of the game server's admin listener. When set, Authorize is not used.
Authorizer admin.Authorizer
// Authorize decides whether an admin request may proceed when Authorizer is nil. A nil Authorize denies every request.
Authorize func(*http.Request) bool
// Provider, when set, adds the /admin/v1/matches, /admin/v1/rooms and /admin/v1/peers views. Without it those routes answer 404.
Provider InspectProvider
// Pprof adds the /admin/v1/pprof/ routes. It is off by default, so a handler mounted only for its JSON views serves no profiles.
Pprof bool
}Inspector serves authenticated, read-only runtime inspection on an admin listener. It is intentionally a separate handler so a player-facing server never exposes profiling endpoints by accident. With an Authorizer, the operators of an operators file use it: a request without a valid session or token is refused with 401, and an operator without admin.PermServerRead (admin.PermServerPprof for the profiles) with 403, recorded in the audit log when the Authorizer is an *admin.Server. Without one, every route is refused with 401 unless Authorize allows the request.
func NewInspector(authorize func(*http.Request) bool) *InspectorNewInspector returns an authenticated admin inspection handler with the runtime view only; set Provider for the match, room and peer views and Pprof for profiles.
func NewOperatorInspector(a admin.Authorizer) *InspectorNewOperatorInspector returns an inspection handler for the operators a, such as an *admin.Server, authenticates, with the runtime view only; set Provider for the match, room and peer views and Pprof for profiles.
func (i *Inspector) ServeHTTP(w http.ResponseWriter, r *http.Request)ServeHTTP exposes GET /admin/v1/runtime, /admin/v1/matches, /admin/v1/rooms and /admin/v1/peers (with a Provider) and /admin/v1/pprof/* (with Pprof). Each request reads the runtime and the Provider afresh.
type Join struct {
Room *Room
Epoch uint64
Tick uint64
Snapshot []byte
}Join reports a peer's admission and, for a running match, the full snapshot it must apply before accepting deltas.
type LeaveReason uint8LeaveReason explains why a peer left a room.
const (
// LeaveQuit is a departure the peer asked for, and the reason Leave reports.
LeaveQuit LeaveReason = iota
// LeaveDropped is a connection lost without a goodbye.
LeaveDropped
// LeaveKicked is a removal by the server or the match.
LeaveKicked
// LeaveReplaced is a peer superseded by a new connection for the same player.
LeaveReplaced
)func (r LeaveReason) String() stringString returns the reason's name in lowercase, such as "quit" or "kicked".
type LimitPolicy uint8LimitPolicy is what a guard does with a peer that exceeds its limits.
const (
// LimitThrottle drops over-limit packets and keeps the peer connected.
LimitThrottle LimitPolicy = iota
// LimitDrop silently drops over-limit packets without a disconnect.
LimitDrop
// LimitDisconnect drops the packet and refuses the peer from then on. The transport session is left for the caller to end, with netplay.WebSocketServer.Kick or netplay.UDPServer.Kick, so the peer does not keep its slot while every packet is refused.
LimitDisconnect
)type Limits struct {
// PacketsPerSecond and BytesPerSecond are the sustained rates; Burst*
// allow a short burst on top, defaulting to one second's rate.
PacketsPerSecond float64
BytesPerSecond float64
BurstPackets float64
BurstBytes float64
// MaxMessageSize rejects a single packet before it is buffered.
MaxMessageSize int
// MaxPendingReliable bounds reliable bytes reserved but not yet released.
MaxPendingReliable int
}Limits bounds one peer's traffic. Zero values disable that bound.
type LimitsConfig struct {
Policy Policy `yaml:"policy,omitempty"`
PacketsPerSecond float64 `yaml:"packetsPerSecond,omitempty"`
BytesPerSecond float64 `yaml:"bytesPerSecond,omitempty"`
BurstPackets float64 `yaml:"burstPackets,omitempty"`
BurstBytes float64 `yaml:"burstBytes,omitempty"`
MaxMessageSize int `yaml:"maxMessageSize,omitempty"`
MaxPendingReliable int `yaml:"maxPendingReliable,omitempty"`
}LimitsConfig is the per-peer traffic guard: what it does past a limit, the sustained and burst rates, and the largest single message.
type ListenConfig struct {
WebSocket WebSocketListen `yaml:"websocket,omitempty"`
UDP UDPListen `yaml:"udp,omitempty"`
}ListenConfig selects the transports the server answers on; at least one address is required.
type Match struct {
// Name identifies the match in overrun reports and per-match metrics; a
// Runner replaces an empty name with match_<index> when it starts.
Name string
// Rate is how many updates run a second, 60 when 0 or negative.
Rate int
// Update moves the match on by dt, always 1/Rate seconds. It runs on the
// runner's goroutine and must return promptly.
Update func(dt time.Duration)
// OnStop runs once after the match's final tick when the context ends,
// for notifying peers or flushing state. Optional.
OnStop func()
// Mailbox bounds the callbacks queued by Post and Call that have not run
// yet, 1024 when 0 or negative.
Mailbox int
// PendingTimeout bounds how long Runner.Run waits for asynchronous jobs submitted through Go or Serial after the context ends. Five seconds when zero. Jobs that remain at the deadline receive context.DeadlineExceeded.
PendingTimeout time.Duration
// MaxPending caps asynchronous jobs submitted through Go or Serial. The default is DefaultMaxPending.
MaxPending int
// Data is the data table generation used for this match. Supply a snapshot
// before starting, or let the Runner pin one from its Data set before the
// first tick. Leave it unchanged once the match starts.
Data *datatable.Snapshot
// contains filtered or unexported fields
}Match is one game simulation stepped at Rate ticks per second.
func (m *Match) Call(ctx context.Context, fn func() error) errorCall runs fn on the match goroutine and waits for its result or for ctx to end. It returns ErrMailboxFull or ErrMatchStopped as Post does, and ErrMatchStopped when the match stops before fn runs or fn panics. Calling it from the match's own goroutine blocks until ctx ends, since fn can only run after the current callback returns.
func (m *Match) MailboxLen() intMailboxLen reports how many queued callbacks have not run yet.
func (m *Match) Post(fn func()) errorPost queues fn to run on the match goroutine before a future Update, in FIFO order with other posted work. It never blocks: a full mailbox returns ErrMailboxFull and a stopped match ErrMatchStopped. A panic in fn follows the runner's OnPanic policy, like a panic in Update.
func (m *Match) Serial(key string) *QueueSerial returns a queue that runs jobs for key in submission order. The key is scoped to the match, so two matches may reuse the same key independently.
type MatchConfig struct {
Rate int `yaml:"rate,omitempty"`
}MatchConfig is how often the server steps its matches, in steps per second.
type MatchHandler interface {
JoinAttempt(peer netplay.PeerID, account string, meta []byte) (accept bool, reason string)
Joined(peer netplay.PeerID)
Left(peer netplay.PeerID, reason LeaveReason)
Signal(data []byte) (reply []byte, err error)
Terminate(grace time.Duration)
}MatchHandler observes and controls a room match lifecycle. Implementations must be safe for callbacks from the room's owning server loop.
type Matchmaker struct {
// RoomSize is how many players one match seats.
RoomSize int
// BaseWindow is the initial allowed rating difference (default 100).
BaseWindow float64
// WindowGrowthPerSecond widens the window per second waited (default 10).
WindowGrowthPerSecond float64
// MaxWindow caps the widened window when positive.
MaxWindow float64
// Now is the clock used for waiting time; nil uses time.Now.
Now func() time.Time
// Teams is the number of balanced teams. Zero or one keeps a flat match.
Teams int
// TicketTTL sets a deadline for tickets whose Deadline is zero. Zero disables expiry.
TicketTTL time.Duration
// Rule replaces the default matching rule when set.
Rule Rule
// contains filtered or unexported fields
}Matchmaker queues tickets per mode and region and groups them into rooms. The zero value is not ready; construct one with NewMatchmaker.
func NewMatchmaker(roomSize int) *MatchmakerNewMatchmaker returns a matchmaker for rooms of roomSize players.
func (m *Matchmaker) Cancel(id uint64) boolCancel removes ticket id and reports whether it was waiting.
func (m *Matchmaker) Enqueue(t Ticket) errorEnqueue adds a ticket, defaulting its EnqueuedAt to the matchmaker's clock.
func (m *Matchmaker) Expire() []TicketExpire removes and returns expired tickets in deadline, enqueue time and ID order.
func (m *Matchmaker) Match() []MatchupMatch forms rooms from the waiting tickets, removes their tickets and returns the matches. Tickets that cannot fill a room stay queued, and expired tickets are removed first. With Teams above one, a room the rule returns that cannot be split into Teams teams of RoomSize/Teams players with every party whole is not formed, and its tickets stay queued.
func (m *Matchmaker) Waiting() []TicketWaiting returns copies of the queued tickets, oldest first.
type Matchup struct {
Mode, Region string
TicketIDs []uint64
Players []string
// Teams contains the deterministic team split when Matchmaker.Teams > 1.
Teams [][]string
}Matchup is a set of tickets assigned to one room.
type MemoryDirectory struct {
TTL time.Duration
// contains filtered or unexported fields
}MemoryDirectory is a deterministic in-process Directory for tests and one-process deployments.
func (d *MemoryDirectory) Heartbeat(address string, seenAt time.Time) errorHeartbeat marks the registered server at address as seen at seenAt, keeping it in the directory for another TTL.
func (d *MemoryDirectory) List(region string) []ServerInfoList returns the servers seen within the TTL (15 seconds when TTL is zero) in region, or in every region when region is empty, fewest rooms first. It forgets the servers that are past the TTL.
func (d *MemoryDirectory) Place(region string) (ServerInfo, error)Place returns the live server in region with the fewest rooms that has room for another, or ErrRoomFull when every live server is full.
func (d *MemoryDirectory) Register(info ServerInfo) errorRegister adds or replaces the server at info.Address, stamping it as seen now when SeenAt is zero. A server without an address or with a negative capacity is refused.
func (d *MemoryDirectory) Remove(address string)Remove drops the server at address from the directory.
type Metrics struct {
Peers int
Rooms int
TickNanos int64
BytesIn uint64
BytesOut uint64
}Metrics is the server state exposed to health and metrics endpoints.
type NumericRange struct{ Min, Max float64 }NumericRange is the inclusive range from Min to Max that a ticket's number must fall in.
type Panic struct {
// Match is the match whose goroutine panicked.
Match *Match
// Value is the value passed to panic.
Value any
// Stack is the goroutine stack trace captured at recovery.
Stack []byte
// Tick is the match's 1-based tick in which Update or a queued callback
// panicked, or 0 when OnStop panicked.
Tick uint64
// Time is when the panic was recovered.
Time time.Time
}Panic describes a panic recovered from a match's Update, a callback queued with Post or Call, or OnStop.
func (p Panic) Report() crashreport.CrashReportReport builds a crashreport.CrashReport from p, so a server-side panic file has the same JSON schema as a client crash report. The match's Name, when set, is recorded as the "match" metadata key.
type PanicAction uint8PanicAction is the outcome Runner.OnPanic chooses for a recovered panic.
const (
// StopMatch ends only the panicking match: it never ticks again (its
// state may be half-updated), its OnStop runs once, and every other match
// on the runner keeps going. It is the zero value and the default when
// OnPanic is nil.
StopMatch PanicAction = iota
// Crash stops every match, runs every OnStop, then re-panics with the
// recovered value from Run.
Crash
)type PanicError struct {
// Value is the recovered panic value.
Value any
// Stack is the goroutine stack captured at the panic.
Stack []byte
}PanicError reports a panic recovered from an asynchronous job.
func (e *PanicError) Error() stringError returns the panic value as an asynchronous job error.
type PeerStats struct {
Packets uint64
Bytes uint64
Dropped uint64
Violations uint64
PendingBytes int
}PeerStats counts one peer's traffic and refusals.
type Policy stringPolicy is what a guard does with a peer that exceeds its limits, as written in server.yaml.
const (
// PolicyThrottle drops over-limit packets and keeps the peer connected.
PolicyThrottle Policy = "throttle"
// PolicyDrop silently drops over-limit packets without disconnecting.
PolicyDrop Policy = "drop"
// PolicyDisconnect drops the packet and refuses the peer from then on.
PolicyDisconnect Policy = "disconnect"
)func (p Policy) GuardPolicy() (LimitPolicy, bool)GuardPolicy returns the LimitPolicy the config names, and false when it names none the guard knows. An empty policy is LimitThrottle, the zero policy.
type Query []TermQuery is the conditions a ticket places on the tickets it matches; every Must term must hold and no MustNot term may, and Should terms rank the candidates.
type Queue struct {
// contains filtered or unexported fields
}Queue serializes asynchronous jobs for one logical key. A job submitted to a Queue starts after the preceding job has completed and its callback has run on the match goroutine.
func (q *Queue) Go(fn func(context.Context) error, cb func(error))Go runs fn in the background and invokes cb on the match goroutine before a later Update. Jobs submitted to the same Queue run and report in order.
type RecordGrant struct {
Key string
Version uint64
Value []byte
}RecordGrant replaces the record at Key with Value. Version must equal the stored record's version, else the commit is a conflict.
type Reservation struct {
Room uint64
Account string
Expires time.Time
}Reservation is an opaque seat claim for one account until Expires.
type ResultCommit struct {
MatchID string
// Epoch and DataVersion identify the room epoch and pinned data tables
// that produced this result. Zero leaves either value unspecified.
Epoch uint64
DataVersion uint64
Records []RecordGrant
Wallet []WalletGrant
Scores []ScoreGrant
}ResultCommit is an idempotent match outcome with server-owned grants and scores.
type ResultReceipt struct {
MatchID string
Epoch uint64
DataVersion uint64
Applied bool
}ResultReceipt identifies a committed result and repeats its match metadata. Applied is false for an identical retry of a result already committed.
type ResultsBackend struct {
// contains filtered or unexported fields
}ResultsBackend is an in-memory store of committed match results, the records, balances and best scores they grant, and an outbox of score grants waiting for delivery. It is safe for concurrent use.
func NewResultsBackend() *ResultsBackendNewResultsBackend returns an empty backend.
func (b *ResultsBackend) Balance(account, currency string) int64Balance returns the accumulated wallet amount for account and currency.
func (b *ResultsBackend) BestScore(board, account string) (int64, bool)BestScore returns the highest score committed for board and account.
func (b *ResultsBackend) Commit(ctx context.Context, r ResultCommit) (ResultReceipt, error)Commit applies r's grants once per match ID and queues its score grants in the outbox. An identical retry returns a receipt with Applied false. A different result for the same match, or a record grant whose version does not match the stored record, is ErrResultConflict and applies nothing. An invalid result is ErrResultInvalid and applies nothing.
func (b *ResultsBackend) DeliverScores(ctx context.Context, sink ScoreSink) errorDeliverScores drains the score outbox in order. A failed delivery leaves the failed grant and all following grants queued for a later retry.
func (b *ResultsBackend) Has(matchID string) boolHas reports whether a result for matchID has been committed.
func (b *ResultsBackend) PendingScores() []ScoreGrantPendingScores returns a copy of score grants waiting for delivery.
func (b *ResultsBackend) Record(key string) (RecordGrant, bool)Record returns the current grant for key, if one has been committed.
type Room struct {
// contains filtered or unexported fields
}Room groups peers for one match. A room owns its members and inbox: packets delivered through one room are never visible to another. The inbox is bounded per member by RoomLimits.
func (r *Room) Advance()Advance increments the room's tick while a match runs.
func (r *Room) Broadcast(tx netplay.Transport, ch netplay.Channel, payload []byte, except ...netplay.PeerID) []netplay.PeerIDBroadcast sends payload to the room's current members in join order, skipping the peers in except (such as the sender), and returns the members whose send failed in that order.
func (r *Room) Capacity() intCapacity returns the maximum number of peers.
func (r *Room) Code() stringCode returns the join code of a private room, or "" for a public one.
func (r *Room) Deliver(from netplay.PeerID, p netplay.Packet) errorDeliver routes a packet from a member into this room's inbox. A peer outside the room cannot inject packets, so one room's traffic never reaches another. The member's queue is bounded by RoomLimits.PerPeer: past it an unreliable packet drops the member's oldest unreliable one, and a reliable packet that has none to evict is refused with ErrRoomInboxFull.
func (r *Room) Drain(budget int, fn func(netplay.Packet)) intDrain hands up to budget packets per member to fn, round robin in join order: each member's oldest packet, then each member's next, so a member that floods the room cannot take the turn of the others. It returns how many packets it handed. A budget of zero or less hands none. fn runs without the room's lock held and may call the room's methods.
func (r *Room) End()End ends the running match and discards the packets still queued in the room's inbox. The room stays open so its peers can see the result; a later Start begins the next epoch.
func (r *Room) Epoch() uint64Epoch returns the current match epoch. Every Start begins a new epoch.
func (r *Room) InboxStats() RoomInboxStatsInboxStats reads the room's inbox counters.
func (r *Room) MatchData() (epoch uint64, data *datatable.Snapshot)MatchData returns the current epoch and its pinned data together. The snapshot stays available after End until the next Start.
func (r *Room) Members() []netplay.PeerIDMembers returns the current peers in join order. A peer that leaves and joins again moves to the end.
func (r *Room) Recv(peer netplay.PeerID) (netplay.Packet, bool)Recv pops the next packet delivered by peer. Non-members and empty inboxes report false. To read every member fairly, use Drain.
func (r *Room) SetHandler(handler MatchHandler)SetHandler attaches the lifecycle handler. It should be called before joins.
func (r *Room) SetLabel(label map[string]string)SetLabel replaces the searchable metadata copied into RoomInfo snapshots.
func (r *Room) Signal(ctx context.Context, data []byte) ([]byte, error)Signal invokes a room handler's external signal with a copy of data on the calling goroutine and returns its reply. A room without a handler is ErrRoomEnded, and a ctx that has already ended returns its error without calling the handler.
func (r *Room) Start() errorStart begins a match, or starts the next one after End: the epoch advances and the tick resets to zero so every client can drop the previous match's tick state without waiting for the counter to wrap past it.
func (r *Room) StartWithData(data *datatable.Snapshot) errorStartWithData starts a match and pins data as part of the same epoch change. Use a snapshot from the data set when starting a new match, or the original snapshot when replaying one.
func (r *Room) Terminate(grace time.Duration)Terminate gives the match a shutdown grace period before ending the room.
type RoomInboxStats struct {
// Queued is the number of packets waiting for Recv or Drain, across all members.
Queued int
// Dropped counts the unreliable packets dropped because their member's queue was full.
Dropped uint64
// Refused counts the reliable packets Deliver refused with ErrRoomInboxFull.
Refused uint64
// Warnings counts the times Queued grew past RoomLimits.Warning: once per crossing, not once per packet.
Warnings uint64
// Backlog is true from the moment Queued passes RoomLimits.Warning until it falls to half of it.
Backlog bool
}RoomInboxStats reports a room's inbox. The counters only grow.
type RoomInfo struct {
ID uint64
Capacity int
State RoomState
Epoch uint64
Tick uint64
Members int
Private bool
Label map[string]string
}RoomInfo is a snapshot of a room for listing.
type RoomLimits struct {
// PerPeer is the most packets a room queues for one member. Zero uses DefaultRoomInboxPerPeer; a negative value removes the cap.
PerPeer int
// Warning is the backlog, across all of a room's members, that counts a warning in RoomInboxStats.Warnings: once when the backlog grows past it, and again only after it has fallen to half of it. Zero uses DefaultRoomInboxWarning; a negative value turns the warning off.
Warning int
}RoomLimits bounds the packets each room keeps until Recv or Drain takes them, so a match that falls behind its packet loop holds a fixed amount of memory instead of growing for as long as it stays slow.
Each member's queue holds at most PerPeer packets. A packet that arrives at a full queue evicts that member's oldest unreliable packet; when the queue holds only reliable packets, an arriving unreliable packet is the one dropped and an arriving reliable packet is refused with ErrRoomInboxFull. One member's flood therefore evicts only its own packets.
type RoomState uint8RoomState is a room's match lifecycle.
const (
RoomWaiting RoomState = iota // open, match not started
RoomRunning // match in progress
RoomEnded // match ended, next Start begins a new one
)func (s RoomState) String() stringString returns "waiting", "running", "ended", or "unknown" for an unrecognized state.
type Rooms struct {
// EmptyTimeout is how long an empty room stays open before Tick closes it.
EmptyTimeout time.Duration
// Snapshot, when set, returns the full state a late joiner needs before
// deltas. It is called for a join to a running match.
Snapshot func(*Room) []byte
// CodeGenerator makes private room codes; nil uses six random letters.
CodeGenerator func() string
// Now is the clock for empty-room timeouts; nil uses time.Now.
Now func() time.Time
// contains filtered or unexported fields
}Rooms manages the rooms of one server process.
func (rs *Rooms) Claim(res Reservation, peer netplay.PeerID) (Join, error)Claim converts a live reservation into a connected room member, passing res.Account to the match handler's JoinAttempt. The reservation is consumed in the same locked step that admits the peer, so no other join can take the seat in between; a claim that fails for any other reason, such as a handler refusal or a busy server, keeps the reservation until it expires. A reservation that does not exist or has expired is ErrRoomFull.
func (rs *Rooms) Create(capacity int, private bool) (*Room, error)Create opens a room. capacity <= 0 uses four players. A private room gets a code that JoinCode accepts.
func (rs *Rooms) Join(id uint64, peer netplay.PeerID) (Join, error)Join admits peer to room id. A join to a running match carries the full snapshot from Snapshot, so the joiner applies it before any delta.
func (rs *Rooms) JoinCode(code string, peer netplay.PeerID) (Join, error)JoinCode admits peer to the private room with code.
func (rs *Rooms) JoinWithMeta(id uint64, peer netplay.PeerID, account string, meta []byte) (Join, error)JoinWithMeta admits a peer after the match handler approves account and metadata.
func (rs *Rooms) Leave(id uint64, peer netplay.PeerID) boolLeave removes peer from room id and reports whether it was a member. The room closes after EmptyTimeout once its last member leaves.
func (rs *Rooms) LeaveWithReason(id uint64, peer netplay.PeerID, reason LeaveReason) boolLeaveWithReason removes a peer and notifies the match handler.
func (rs *Rooms) MemberCount() intMemberCount returns the number of members across all open rooms, the count MaxMembers caps.
func (rs *Rooms) Reserve(id uint64, account string, ttl time.Duration) (Reservation, error)Reserve holds one room seat for account until ttl elapses.
func (rs *Rooms) SetCapacity(c Capacity, busy func() bool)SetCapacity sets the process-wide admission limits and an optional busy callback. While busy reports true, Create and the join of a new member return ErrServerBusy; members already in a room keep resuming and leaving. busy runs without any Rooms or Room lock held, so it may call back into Rooms; a nil busy is never busy.
func (rs *Rooms) SetLimits(l RoomLimits)SetLimits changes the inbox limits of every open room and of the rooms Create opens later. Lowering PerPeer below what a member has queued drops that member's oldest unreliable packets at once and counts them; reliable packets already queued are kept.
func (rs *Rooms) Tick() []uint64Tick closes rooms that have been empty for at least EmptyTimeout and returns their IDs. A zero EmptyTimeout closes them as soon as Tick next runs.
type RoomsConfig struct {
DefaultCapacity int `yaml:"defaultCapacity,omitempty"`
EmptyTimeout time.Duration `yaml:"emptyTimeout,omitempty"`
MaxRooms int `yaml:"maxRooms,omitempty"`
MaxMembers int `yaml:"maxMembers,omitempty"`
}RoomsConfig is the room manager's settings: the seats a new room gets, how long an empty room stays open, and the process-wide room and member caps.
type Rule func(tickets []*Ticket, roomSize int, window func(*Ticket) float64) []MatchupRule chooses matches from a group of tickets that share a mode and region. window reports a ticket's current skill window at the rule's time. The default rule fills rooms with parties whose ratings fit; a game can replace it for custom matching.
type Runner struct {
// Matches are the matches to run. A nil Update is an error.
Matches []*Match
// Data supplies the current data table generation to every starting match
// that has no explicit snapshot. Load it before starting the Runner.
Data *datatable.Set
// Health, when set, records every match tick's duration in the health's
// nsgo_server_match_tick_seconds histogram. Wrap OnOverrun with the
// health's OnOverrun to count overruns and missed ticks per match too.
Health *Health
// OnOverrun, when set, reports a tick that finished past the next tick's
// deadline. lag is the time past the deadline and missed is how many whole
// intervals that covers (at least 1). The runner does not catch up the
// missed ticks: the deadline resets to one interval from when the slow
// update returns, so a slow update slows the match instead of running a
// burst.
OnOverrun func(m *Match, lag time.Duration, missed int)
// OnPanic, when set, reports a panic recovered from a match's Update, a
// callback queued with Post or Call, or OnStop and chooses the outcome. With StopMatch (the zero value, also
// the default when OnPanic is nil) only the panicking match ends: it
// never ticks again, its OnStop runs once, and the runner keeps going.
// With Crash every match stops, every OnStop runs, and Run re-panics
// with the recovered value.
OnPanic func(p Panic) PanicAction
}Runner steps the matches in Matches concurrently, each at its own rate, until its context is canceled.
func (r *Runner) Run(ctx context.Context) errorRun starts every match and blocks until ctx is canceled and each match has finished its current tick and run OnStop. It returns an error without starting anything when a match has no Update.
type RuntimeInfo struct {
Goroutines int `json:"goroutines"`
HeapBytes uint64 `json:"heapBytes"`
HeapInUse uint64 `json:"heapInUse"`
NumGC uint32 `json:"numGC"`
// GCPauseTotalNs is the cumulative stop-the-world pause time since the process started.
GCPauseTotalNs uint64 `json:"gcPauseTotalNs"`
}RuntimeInfo is a point-in-time process health snapshot.
type ScoreGrant struct {
Board, Account string
Score int64
}ScoreGrant records Score for Account on Board, keeping the account's best score.
type ScoreSink interface {
Deliver(context.Context, ScoreGrant) error
}ScoreSink receives scores from the result outbox. Deliver may be retried after a transient failure and must be idempotent for a score grant.
type ServerInfo struct {
Address string
Region string
Capacity int
Rooms int
SeenAt time.Time
}ServerInfo describes a game-server process in a directory.
type SignedReservation struct {
Reservation Reservation `json:"reservation"`
Signature []byte `json:"signature"`
}SignedReservation is a portable, signed seat claim for a room.
func SignReservation(res Reservation, key ed25519.PrivateKey) (SignedReservation, error)SignReservation encodes and signs a reservation with Ed25519.
func (s SignedReservation) Verify(key ed25519.PublicKey, now time.Time) errorVerify checks a signed reservation's signature and expiry at now.
type TLSConfig struct {
CertFile string `yaml:"certFile"`
KeyFile string `yaml:"keyFile"`
}TLSConfig names the certificate and key files for the WebSocket listener; both are required together.
type Term struct {
Kind TermKind
Field string
In []string
Range *NumericRange
Boost float64
}Term is one condition of a Query on a ticket's attribute Field: the string attribute is one of In, or the number attribute falls in Range. Kind decides whether the condition must hold, must not hold, or adds Boost (1 when Boost is zero) to the match's score when it holds.
type TermKind uint8TermKind is how a Term affects a match: Must and MustNot filter candidates, Should ranks them.
const (
// Must requires the term to hold.
Must TermKind = iota
// MustNot requires the term not to hold.
MustNot
// Should adds the term's Boost to the match's score when it holds.
Should
)type Ticket struct {
// ID identifies the ticket for cancellation and in a Match.
ID uint64
// Mode and Region group tickets that may meet.
Mode, Region string
// Rating is the party's skill rating; the window widens from it as the
// ticket waits.
Rating float64
// Party lists the players in the ticket. It must hold at least one player
// and is placed whole or not at all.
Party []string
// EnqueuedAt is when the ticket started waiting; zero uses the time it was
// enqueued.
EnqueuedAt time.Time
// Deadline is when the ticket stops waiting. A zero deadline never expires, unless the matchmaker's TicketTTL sets one at Enqueue.
Deadline time.Time
// Strings and Numbers are the ticket's attributes that other tickets' queries test. Enqueue copies them.
Strings map[string]string
Numbers map[string]float64
// Query is the conditions this ticket places on the tickets it meets; nil matches anyone.
Query Query
// MinCount, MaxCount and CountMultiple bound the number of players in a room this ticket anchors: at least MinCount, at most MaxCount and a multiple of CountMultiple. Zero means RoomSize, RoomSize and 1.
MinCount, MaxCount, CountMultiple int
}Ticket is one matchmaking request. A party stays together in a room.
func (t Ticket) Expired(now time.Time) boolExpired reports whether t has reached its non-zero deadline at now.
type UDPListen struct {
Addr string `yaml:"addr,omitempty"`
}UDPListen is the plain UDP listener's host:port.
type WalletGrant struct {
Account, Currency string
Amount int64
}WalletGrant changes Account's balance of Currency by Amount.
type WebSocketListen struct {
Addr string `yaml:"addr,omitempty"`
Origins []string `yaml:"origins,omitempty"`
}WebSocketListen is the WebSocket listener: Addr is a host:port, and Origins lists the HTTP origins a browser client may connect from, an empty list accepting any.