La référence API provient des commentaires de documentation Go du code source et est rédigée en anglais.
package server
import "github.com/nsgo-dev/game/pkg/server"Vue d’ensemble
Package server 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
- Variables
- type Guard
- func NewGuard(limits Limits, policy LimitPolicy) *Guard
- func (g *Guard) Check(peer netpkg.PeerID, packet netpkg.Packet) (GuardAction, error)
- func (g *Guard) ReleaseReliable(peer netpkg.PeerID, n int)
- func (g *Guard) ReserveReliable(peer netpkg.PeerID, n int) error
- func (g *Guard) Reset(peer netpkg.PeerID)
- func (g *Guard) Stats(peer netpkg.PeerID) PeerStats
- type GuardAction
- type Health
- type Join
- type LimitPolicy
- type Limits
- type Match
- type Matchmaker
- type Matchup
- type Metrics
- type PeerStats
- type Room
- func (r *Room) Advance()
- func (r *Room) Capacity() int
- func (r *Room) Code() string
- func (r *Room) Deliver(from netpkg.PeerID, p netpkg.Packet) error
- func (r *Room) End()
- func (r *Room) Epoch() uint64
- func (r *Room) ID() uint64
- func (r *Room) Members() []netpkg.PeerID
- func (r *Room) Recv(peer netpkg.PeerID) (netpkg.Packet, bool)
- func (r *Room) Start() error
- func (r *Room) State() RoomState
- func (r *Room) Tick() uint64
- type RoomInfo
- type RoomState
- type Rooms
- func NewRooms() *Rooms
- func (rs *Rooms) Create(capacity int, private bool) (*Room, error)
- func (rs *Rooms) Join(id uint64, peer netpkg.PeerID) (Join, error)
- func (rs *Rooms) JoinCode(code string, peer netpkg.PeerID) (Join, error)
- func (rs *Rooms) Leave(id uint64, peer netpkg.PeerID) bool
- func (rs *Rooms) List() []RoomInfo
- func (rs *Rooms) Tick() []uint64
- type Rule
- type Runner
- type Ticket
Variables
var (
// ErrMessageTooLarge reports a packet larger than Limits.MaxMessageSize.
ErrMessageTooLarge = errors.New("server: message too large")
// ErrPendingLimit reports reliable bytes past Limits.MaxPendingReliable.
ErrPendingLimit = errors.New("server: pending reliable data limit")
// ErrInvalidInput reports input refused by Guard.Validate.
ErrInvalidInput = errors.New("server: invalid input")
// ErrPeerDisconnected reports a peer the guard has disconnected.
ErrPeerDisconnected = errors.New("server: peer disconnected")
)var (
// ErrInvalidTicket reports a ticket with no player or a non-positive room size.
ErrInvalidTicket = errors.New("server: invalid matchmaking ticket")
// ErrDuplicateTicket reports a ticket ID already waiting in the queue.
ErrDuplicateTicket = errors.New("server: duplicate matchmaking ticket")
)var (
// ErrRoomNotFound reports a room ID or code that names no open room.
ErrRoomNotFound = errors.New("server: room not found")
// ErrRoomFull reports a join to a room already at capacity.
ErrRoomFull = errors.New("server: room full")
// ErrRoomEnded reports an action on a room whose match has ended.
ErrRoomEnded = errors.New("server: room match ended")
// ErrNotInRoom reports a packet from a peer that is not a room member.
ErrNotInRoom = errors.New("server: peer is not in this room")
)Types
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(netpkg.PeerID, netpkg.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 on the server's packet loop and independent per peer.
func NewGuard(limits Limits, policy LimitPolicy) *GuardNewGuard returns a guard with limits and a policy.
func (g *Guard) Check(peer netpkg.PeerID, packet netpkg.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 netpkg.PeerID, n int)ReleaseReliable returns n reserved reliable bytes for peer.
func (g *Guard) ReserveReliable(peer netpkg.PeerID, n int) errorReserveReliable reserves n reliable bytes for peer, refusing past MaxPendingReliable.
func (g *Guard) Reset(peer netpkg.PeerID)Reset forgets a peer's buckets and counters, for a reconnecting peer.
func (g *Guard) Stats(peer netpkg.PeerID) PeerStatsStats returns a peer's counters.
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.
func NewHealth(ready func() bool, metrics func() Metrics) *HealthNewHealth returns deployment endpoints.
func (h *Health) ObserveTick(d time.Duration)ObserveTick records the duration of the last server tick for metrics.
func (h *Health) ServeHTTP(w http.ResponseWriter, r *http.Request)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 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.
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 Match struct {
// Name identifies the match in overrun reports; optional.
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()
}Match is one game simulation stepped at Rate ticks per second.
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
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) Match() []MatchupMatch forms rooms from the waiting tickets, removes their tickets and returns the matches. Tickets that cannot fill a room 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
}Match is a set of tickets assigned to one room.
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 PeerStats struct {
Packets uint64
Bytes uint64
Dropped uint64
Violations uint64
PendingBytes int
}PeerStats counts one peer's traffic and refusals.
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.
func (r *Room) Advance()Advance increments the room's tick while a match runs.
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 netpkg.PeerID, p netpkg.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.
func (r *Room) End()End ends the running match. 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) Members() []netpkg.PeerIDMembers returns the current peers in admission order not kept.
func (r *Room) Recv(peer netpkg.PeerID) (netpkg.Packet, bool)Recv pops the next packet delivered by peer. Non-members and empty inboxes report false.
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.
type RoomInfo struct {
ID uint64
Capacity int
State RoomState
Epoch uint64
Tick uint64
Members int
Private bool
}RoomInfo is a snapshot of a room for listing.
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() stringtype 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) 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 netpkg.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 netpkg.PeerID) (Join, error)JoinCode admits peer to the private room with code.
func (rs *Rooms) Leave(id uint64, peer netpkg.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) 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 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
// OnOverrun, when set, reports a tick whose Update ran longer than its
// interval. lag is the time past the interval and missed is how many whole
// intervals that covers. The runner does not catch up the missed ticks: the
// next tick is scheduled from now, so a slow update slows the match instead
// of running a burst.
OnOverrun func(m *Match, lag time.Duration, missed int)
}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 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
}Ticket is one matchmaking request. A party stays together in a room.