Die API-Referenz stammt aus den Go-Doc-Kommentaren im Quellcode und ist auf Englisch verfasst.
package gameserver
import "github.com/nsgo-dev/game/pkg/online/gameserver"Übersicht
Package gameserver 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
- Konstanten
- Variablen
- func GuardCollector(g *Guard) func(io.Writer)
- func InboxCollector(name string, r netplay.InboxReporter) func(io.Writer)
- 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 Join
- type LimitPolicy
- type Limits
- type Match
- type Matchmaker
- type Matchup
- type Metrics
- type Panic
- type PanicAction
- type PeerStats
- type Room
- func (r *Room) Advance()
- 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) Members() []netplay.PeerID
- func (r *Room) Recv(peer netplay.PeerID) (netplay.Packet, bool)
- func (r *Room) Start() error
- func (r *Room) State() RoomState
- func (r *Room) Tick() uint64
- type RoomInboxStats
- type RoomInfo
- type RoomLimits
- type RoomState
- type Rooms
- func NewRooms() *Rooms
- 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) Leave(id uint64, peer netplay.PeerID) bool
- func (rs *Rooms) List() []RoomInfo
- func (rs *Rooms) SetLimits(l RoomLimits)
- func (rs *Rooms) Tick() []uint64
- type Rule
- type Runner
- type Ticket
Konstanten
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
)Variablen
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 or a non-positive 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")
// 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 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.
Funktionen
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".
Typen
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.
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. 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 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()
}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) Len() intLen reports how many tickets are waiting.
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 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 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 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 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. 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) 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) 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) 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) Tick() uint64Tick returns the room's current fixed-step tick.
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
}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) 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) 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) 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 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
// 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 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 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.