Documentation
¶
Overview ¶
Package gameserver is experimental: its API and documented formats may change in a minor release; see https://nsgo.games/docs/stability/.
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 ¶
- Constants
- 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)
- func Inherited(name string) (net.Listener, bool)
- func LinkCollector(name string, tx netplay.Transport) func(io.Writer)
- func LoadCollector(load func() Load) func(io.Writer)
- func RefuseHelloWhenBusy(busy func() bool, next func(netplay.Hello) error) func(netplay.Hello) error
- func RefuseIdentifyWhenBusy(busy func() bool, next func(netplay.PeerID, []byte) (string, error)) func(netplay.PeerID, []byte) (string, error)
- func RefuseWhenBusy(busy func() bool, next func(netplay.PeerID, []byte) error) func(netplay.PeerID, []byte) error
- func RegisterAdminCommands(r *admin.Registry, cfg AdminCommands) error
- type AdminCommands
- type AuthConfig
- type Autosave
- type Capacity
- type Config
- type Directory
- type Drain
- type DrainStep
- type DrainTransport
- type Group
- type 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
- func (g *Guard) WrapTransport(inner netplay.Transport) netplay.Transport
- type GuardAction
- type Handoff
- type 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)
- func (h *Health) SetBusyReadiness(busy func() bool, hold time.Duration)
- func (h *Health) SetDraining(draining bool)
- type HealthConfig
- type HealthOption
- type Host
- type HostPolicy
- type InspectMatch
- type InspectPeer
- type InspectProvider
- type InspectRoom
- type Inspector
- type Join
- type LeaveReason
- type LimitPolicy
- type Limits
- type LimitsConfig
- type ListenConfig
- type Load
- type LoadPolicy
- type LobbyEvent
- type LobbyEventKind
- type Match
- type MatchConfig
- type MatchHandler
- type MatchLoad
- 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 ModeConfig
- type NumericRange
- type Panic
- type PanicAction
- type PanicError
- type PeerKicker
- type PeerStats
- type Policy
- type Query
- type Queue
- type RecordGrant
- type Reservation
- type ResultCommit
- type ResultReceipt
- type 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) AllReady() bool
- func (r *Room) Broadcast(tx netplay.Transport, ch netplay.Channel, payload []byte, ...) []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) HasPassword() bool
- func (r *Room) Host() netplay.PeerID
- 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) Name() string
- func (r *Room) Ready(peer netplay.PeerID) bool
- 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) SetReady(peer netplay.PeerID, ready bool) error
- func (r *Room) SetSetting(by netplay.PeerID, key, value string) error
- func (r *Room) Setting(key string) (string, bool)
- func (r *Room) Settings() map[string]string
- func (r *Room) Signal(ctx context.Context, data []byte) ([]byte, error)
- func (r *Room) Start() error
- func (r *Room) StartBy(peer netplay.PeerID) 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 RoomFilter
- type RoomInboxStats
- type RoomInfo
- type RoomLimits
- type RoomOptions
- type RoomState
- type 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) CreateWith(host netplay.PeerID, o RoomOptions) (*Room, error)
- func (rs *Rooms) Find(f RoomFilter) []RoomInfo
- func (rs *Rooms) Get(id uint64) (*Room, bool)
- 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) JoinOrCreate(capacity int, peer netplay.PeerID) (Join, error)
- func (rs *Rooms) JoinPassword(id uint64, peer netplay.PeerID, password string) (Join, error)
- func (rs *Rooms) JoinPasswordWithMeta(id uint64, peer netplay.PeerID, password, account string, meta []byte) (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) LobbyEvents() []LobbyEvent
- func (rs *Rooms) MemberCount() int
- func (rs *Rooms) QuickJoin(mode string, peer netplay.PeerID) (Join, error)
- 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) SetLoad(c Capacity, load func() Load)
- func (rs *Rooms) Tick() []uint64
- type RoomsConfig
- type Rule
- type Runner
- type RuntimeInfo
- type ScoreGrant
- type ScoreSink
- type ServerInfo
- type SignedReservation
- type Store
- type TLSConfig
- type Term
- type TermKind
- type Ticket
- type Transport
- type UDPListen
- type WalletGrant
- type WebSocketListen
Examples ¶
Constants ¶
const ( // DefaultLoadWindow is the sliding window Runner.Load aggregates over when // LoadPolicy.Window is zero or negative. DefaultLoadWindow = 10 * time.Second // DefaultLoadOverrunRatio is the fraction of overrunning ticks within // LoadPolicy.Window at which Runner.Load reports Busy when // LoadPolicy.OverrunRatio is zero. DefaultLoadOverrunRatio = 0.05 // DefaultReadyHold is how long busy must stay false before Health clears // its automatic not-ready state when hold is zero. DefaultReadyHold = 5 * time.Second )
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 = 1
ConfigVersion is the server.yaml version this package reads and writes.
const DefaultAutosaveInterval = 30 * time.Second
DefaultAutosaveInterval is how long a dirty key waits before Autosave snapshots and writes it when Autosave.Every is zero or negative.
const DefaultDrainDeadline = 30 * time.Second
DefaultDrainDeadline is how long Drain.Run waits for active rooms to finish when Drain.Deadline is zero or negative.
const DefaultIdleTimeout = 2 * time.Minute
DefaultIdleTimeout is how long a room may stay empty before Host stops its match when IdleTimeout is zero.
const DefaultMaxPending = 256
DefaultMaxPending 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") // ErrOwnerUpdateRateLimited reports a replication owner-update packet past Limits.OwnerUpdatesPerSecond. ErrOwnerUpdateRateLimited = errors.New("gameserver: owner update rate limited") )
var ( // ErrNotHost reports an action only the room's host may take. ErrNotHost = errors.New("gameserver: not the room host") // ErrNotReady reports a start before every non-host member was ready. ErrNotReady = errors.New("gameserver: not every member is ready") // ErrPasswordRequired reports a join to a password-protected room without JoinPassword. ErrPasswordRequired = errors.New("gameserver: room password required") // ErrWrongPassword reports a join with the wrong room password. ErrWrongPassword = errors.New("gameserver: wrong room password") )
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 ErrNoCapacity = errors.New("gameserver: no room capacity left")
ErrNoCapacity reports QuickJoin with no room to join and no room to open, because Rooms.Capacity.MaxRooms is reached.
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.
var ErrUnknownMode = errors.New("gameserver: unknown mode")
ErrUnknownMode reports QuickJoin called for a mode the server does not configure.
var ErrUpgradeInProgress = errors.New("gameserver: graceful upgrade already in progress")
ErrUpgradeInProgress is returned when Upgrade is called while another Upgrade on the same Handoff is still waiting for its child process.
var ErrUpgradeUnsupported = errors.New("gameserver: graceful upgrade is unsupported on this platform")
ErrUpgradeUnsupported is returned by Handoff.Upgrade on platforms that do not support passing listening file descriptors across exec (such as Windows and WebAssembly).
Functions ¶
func Go ¶
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 ¶
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 ¶
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".
func Inherited ¶
Inherited returns a listener passed to this process by a parent Handoff.Upgrade or by systemd socket activation (LISTEN_PID / LISTEN_FDS / LISTEN_FDNAMES).
Each named listener can be claimed at most once; subsequent calls for the same name return (nil, false). For an unnamed single systemd socket (LISTEN_FDS=1 with empty LISTEN_FDNAMES), pass name "". Inherited sets FD_CLOEXEC on every inherited descriptor so they do not leak into unrelated child processes.
func LinkCollector ¶
LinkCollector returns a collector for Health.AddCollector that exports per-peer link quality metrics from tx when tx implements netplay.LinkReporter: nsgo_net_link_rtt_seconds, nsgo_net_link_rttvar_seconds, nsgo_net_link_loss_ratio, nsgo_net_link_bytes_sent_total, nsgo_net_link_bytes_recv_total, nsgo_net_link_packets_sent_total, nsgo_net_link_packets_recv_total, nsgo_net_link_send_rate_bytes_per_second, nsgo_net_link_queued_bytes and nsgo_net_link_drain_seconds, each labeled transport="name",peer="<id>".
func LoadCollector ¶
LoadCollector returns a collector for Health.AddCollector that exports a Runner.Load snapshot as Prometheus gauges:
- nsgo_server_load_busy
- nsgo_server_load_overrun_ratio
- nsgo_server_load_mailbox_warning
- nsgo_server_match_tick_p50_seconds{match=...}
- nsgo_server_match_tick_p99_seconds{match=...}
- nsgo_server_match_overrun_ratio{match=...}
- nsgo_server_match_mailbox_len{match=...}
- nsgo_server_match_mailbox_warning{match=...}
func RefuseHelloWhenBusy ¶
func RefuseHelloWhenBusy(busy func() bool, next func(netplay.Hello) error) func(netplay.Hello) error
RefuseHelloWhenBusy wraps a netplay.Auth.VerifyHello callback the same way RefuseWhenBusy wraps Auth.Verify.
func RefuseIdentifyWhenBusy ¶
func RefuseIdentifyWhenBusy(busy func() bool, next func(netplay.PeerID, []byte) (string, error)) func(netplay.PeerID, []byte) (string, error)
RefuseIdentifyWhenBusy wraps a netplay.Auth.Identify callback the same way RefuseWhenBusy wraps Auth.Verify.
func RefuseWhenBusy ¶
func RefuseWhenBusy(busy func() bool, next func(netplay.PeerID, []byte) error) func(netplay.PeerID, []byte) error
RefuseWhenBusy wraps a netplay.Auth.Verify callback so new handshakes are refused while busy reports true, before next runs. Refusals return a structured *netplay.RejectError with Code netplay.RejectServerFull and Reason "busy". Resuming sessions bypass Auth.Verify in netplay and are not refused. A nil busy never refuses; a nil next accepts when not busy.
func RegisterAdminCommands ¶
func RegisterAdminCommands(r *admin.Registry, cfg AdminCommands) error
RegisterAdminCommands registers the dedicated server's built-in operator commands ("rooms", "kick", "broadcast", "drain", "tables", "version") on r. Only commands whose corresponding fields in cfg are set are registered; "version" is always registered.
Types ¶
type AdminCommands ¶
type AdminCommands struct {
// Rooms supplies the "rooms" command (admin.PermServerRead).
Rooms *Rooms
// Load, when set (typically runner.Load), appends the runner's load
// summary (busy state, overrun ratio, tick p50/p99, and per-match load)
// to the "rooms" command output.
Load func() Load
// Kick handles "kick <peer> [reason]" (admin.PermServerKick).
// When nil and Transports has at least one non-nil entry, "kick" calls
// Kick on each transport in order until one succeeds (ignoring
// netplay.ErrUnknownPeer). Supply Kick directly when multiple transports
// can share numeric PeerIDs and need disambiguation.
Kick func(ctx context.Context, peer netplay.PeerID, reason string) error
// Transports are fallback kick targets when Kick is nil. Nil entries are ignored.
Transports []PeerKicker
// Broadcast handles "broadcast <text>" (admin.PermServerBroadcast).
Broadcast func(ctx context.Context, text string) error
// Drain handles "drain" (admin.PermServerDrain), typically by starting an
// ordered gameserver.Drain (for example canceling the server's run context).
Drain func(ctx context.Context) error
// Data supplies "tables reload" (admin.PermServerReload).
Data *datatable.Set
// Version is the string returned by "version" (admin.PermServerRead).
// When empty, "version" reports the Go module version from build info and runtime.Version().
Version string
}
AdminCommands configures the dedicated server built-in commands registered by RegisterAdminCommands. Only commands whose corresponding fields are configured are registered; "version" is always registered.
type AuthConfig ¶
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 Autosave ¶
type Autosave struct {
// Every is how long a dirty key waits before it is snapshotted and written.
// DefaultAutosaveInterval (30s) when zero or negative.
Every time.Duration
// Store persists encoded snapshots, such as FileStore(dir) or a custom store.
Store Store
// Snapshot encodes the current state for key as YAML or JSON text. It runs
// on the attached match's goroutine between ticks, or on the caller's
// goroutine during Flush once the match is no longer ticking.
Snapshot func(key string) ([]byte, error)
// OnError, when set, receives snapshot and write failures. Write failures
// are reported from the background writer goroutine without holding locks.
OnError func(key string, err error)
// contains filtered or unexported fields
}
Autosave performs write-behind persistence of a persistent world without stalling Match.Update on disk or database I/O.
Call MarkDirty from Update whenever a key's state changes, and Attach to the Match that owns that state. At each Every interval, due dirty keys are snapshotted on the match goroutine between ticks and written on a background goroutine. Multiple MarkDirty calls for the same key coalesce into one snapshot, and a newer snapshot supersedes an unwritten older one. A failed write keeps the key dirty and retries with exponential backoff so the latest snapshot wins. Call Flush from Match.OnStop or during a graceful drain to snapshot and persist all dirty state before exit.
func (*Autosave) Attach ¶
Attach connects a to m so due dirty keys are snapshotted on m's goroutine between ticks and written on a background goroutine. Calling Attach more than once with the same match is a no-op.
func (*Autosave) Flush ¶
Flush snapshots every currently dirty key (ignoring Every and retry backoff) and waits until those snapshots and any already-queued or in-flight writes finish or ctx ends. While the attached match is ticking, snapshots are taken on the match goroutine between ticks; once the match has stopped (such as inside Match.OnStop) or when unattached, Flush snapshots directly. Do not call Flush from inside Match.Update.
type Capacity ¶
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
// OverrunRatio, when positive with SetLoad, also marks admission busy when
// Load.OverrunRatio passes it even if Load.Busy is false (for example 0.05
// for 5%). Zero relies on Load.Busy and Load.MailboxWarning.
OverrunRatio float64
// Window is the load measurement window associated with OverrunRatio.
// Configure Runner.LoadPolicy.Window to control the window Runner.Load aggregates.
Window time.Duration
}
Capacity limits process-wide admission across all rooms. A zero field leaves that limit off.
type Config ¶
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"`
Admin *admin.Config `yaml:"admin,omitempty"`
}
Config is one versioned server.yaml: a dedicated server's listeners, TLS files, admission, per-peer limits, rooms, match rate, health endpoint and optional admin listener. It holds file paths, never credentials.
func DefaultConfig ¶
func DefaultConfig() Config
DefaultConfig 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 ¶
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.
type Directory ¶
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 Drain ¶
type Drain struct {
// Health, when set, turns /readyz to 503 at step 1 while keeping /healthz 200.
Health *Health
// Transports are put into draining mode at step 2, have their remaining
// connected peers kicked with reason "shutdown" at step 6, and are closed
// at step 7. Nil entries are ignored.
Transports []DrainTransport
// Rooms, when set, is awaited at step 4 until every open room has ended
// (RoomEnded) or holds no members.
Rooms *Rooms
// Deadline bounds the wait from the start of Run; DefaultDrainDeadline (30s)
// when zero or negative. Time spent in earlier steps counts against it.
Deadline time.Duration
// Notice, when set, runs at step 3 with the remaining time until Deadline so
// the game can broadcast a restart warning to connected peers.
Notice func(remaining time.Duration)
// OnStep, when set, is called after each step with its elapsed duration and
// any error (such as context.DeadlineExceeded or context.Canceled from
// DrainStepWaitRooms, or a transport Kick/Close failure).
OnStep func(step DrainStep, took time.Duration, err error)
}
Drain runs a dedicated server's ordered shutdown sequence: flip /readyz to 503, refuse new handshakes with reason "draining", notify connected peers, wait for active rooms to end or empty up to Deadline, cancel the Runner so pending async jobs and OnStop finish, kick remaining peers with reason "shutdown", and close transports.
func (*Drain) Run ¶
Run executes the ordered shutdown sequence:
- Mark Health not ready (/readyz returns 503).
- Put each transport into draining mode (refuse new handshakes with netplay.RejectMaintenance, reason "draining", and remaining RetryAfter).
- Call Notice with the remaining time until Deadline (skipped if ctx is already canceled).
- Wait until every room in Rooms is empty or RoomEnded, until Deadline elapses, or until ctx is canceled (for example by a second SIGTERM).
- Call cancelRunner; wrap Runner cancellation with waiting for Runner.Run to return so pending async jobs and OnStop run before peers are kicked.
- Kick every remaining connected peer on each transport with reason "shutdown" (ignoring netplay.ErrUnknownPeer if a peer already left).
- Close every transport.
Steps 5 through 7 always run even when step 4 hits Deadline or ctx is canceled, so OnStop flushes state and transports do not leak. Run returns the joined errors from every step, including context.DeadlineExceeded when rooms remained at the deadline and context.Canceled when ctx short-circuited the wait.
type DrainStep ¶
type DrainStep uint8
DrainStep names one stage of Drain.Run, in execution order.
const ( // DrainStepNotReady marks Health as draining so /readyz returns 503. DrainStepNotReady DrainStep = iota + 1 // DrainStepRefuseSessions puts every transport into draining mode so new // handshakes are refused with netplay.RejectMaintenance and reason "draining". DrainStepRefuseSessions // DrainStepNotice runs Drain.Notice to warn connected peers of the restart. DrainStepNotice // DrainStepWaitRooms waits until every room in Drain.Rooms has ended or is // empty, or until the drain deadline or ctx ends. DrainStepWaitRooms // DrainStepCancelRunner calls cancelRunner so the Runner stops ticking, // drains pending async jobs, and runs every match's OnStop. DrainStepCancelRunner // DrainStepKickPeers kicks every remaining connected peer on every transport // with reason "shutdown". DrainStepKickPeers // DrainStepCloseTransports closes every transport in Drain.Transports. DrainStepCloseTransports )
type DrainTransport ¶
type DrainTransport interface {
SetDraining(reason string, retryAfter time.Duration)
Peers() []netplay.PeerID
Kick(peer netplay.PeerID, reason string) error
Close() error
}
DrainTransport is a server transport that Drain can put into draining mode, kick remaining peers from, and close. Both *netplay.WebSocketServer and *netplay.UDPServer implement it.
type Group ¶
type Group struct {
// contains filtered or unexported fields
}
Group is an ordered set of peers for a room, team or spectator list.
func (*Group) Broadcast ¶
func (g *Group) Broadcast(tx netplay.Transport, ch netplay.Channel, payload []byte, except ...netplay.PeerID) []netplay.PeerID
Broadcast sends payload to every member except the peers in except and returns the members whose send failed, in join order.
type Guard ¶
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.
Example ¶
A Guard limits how much each peer may send: packets over the size limit are refused, and bursts beyond the rate are throttled.
package main
import (
"fmt"
"time"
"github.com/nsgo-dev/game/pkg/online/gameserver"
"github.com/nsgo-dev/game/pkg/online/netplay"
)
func main() {
now := time.Unix(0, 0)
g := gameserver.NewGuard(gameserver.Limits{PacketsPerSecond: 2, BurstPackets: 2, MaxMessageSize: 64}, gameserver.LimitThrottle)
g.Now = func() time.Time { return now }
names := map[gameserver.GuardAction]string{gameserver.GuardAllow: "allow", gameserver.GuardThrottle: "throttle", gameserver.GuardDisconnect: "disconnect"}
small := netplay.Packet{Payload: make([]byte, 10)}
for range 3 {
action, err := g.Check(7, small)
fmt.Println(names[action], err)
}
_, err := g.Check(8, netplay.Packet{Payload: make([]byte, 100)})
fmt.Println(err)
}
Output: allow <nil> allow <nil> throttle gameserver: packet rate limited gameserver: message too large
func NewGuard ¶
func NewGuard(limits Limits, policy LimitPolicy) *Guard
NewGuard returns a guard with limits and a policy.
func (*Guard) Check ¶
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 (*Guard) ReleaseReliable ¶
ReleaseReliable returns n reserved reliable bytes for peer.
func (*Guard) ReserveReliable ¶
ReserveReliable reserves n reliable bytes for peer, refusing past MaxPendingReliable.
func (*Guard) Reset ¶
Reset forgets a peer's buckets and counters, for a reconnecting peer. The peer's counters stay in Totals.
func (*Guard) Totals ¶
Totals returns the guard's counters summed across every peer it has seen, including the peers Reset forgot; PendingBytes covers only the peers still tracked.
func (*Guard) WrapTransport ¶
WrapTransport returns a netplay.Transport that filters every incoming packet from inner through g.Check before handing it to callers such as netplay.ServerWorld. Packets that do not pass GuardAllow are dropped.
type GuardAction ¶
type GuardAction uint8
GuardAction is the result of Guard.Check.
const ( GuardAllow GuardAction = iota GuardThrottle GuardDisconnect )
type Handoff ¶
type Handoff struct {
// Listeners maps logical names (such as "ws" or "health") to open
// listeners passed to the replacement process. Each listener must implement
// File() (*os.File, error), as *net.TCPListener and *net.UnixListener do.
// Names must be non-empty and must not contain ',', ':', '=', '\r', or '\n'.
Listeners map[string]net.Listener
// Ready reports whether the current process is ready to serve traffic.
// SignalReady waits for Ready (when non-nil) to return true before
// notifying the parent process.
Ready func() bool
// Executable, when non-empty, overrides os.Executable() as the binary
// executed by Upgrade.
Executable string
// Args, when non-nil, overrides os.Args[1:] passed to the replacement
// process.
Args []string
// Env, when non-nil, overrides os.Environ() as the base environment passed
// to the replacement process. Handoff protocol variables are always set by
// Upgrade, replacing any inherited values.
Env []string
// Dir, when non-empty, sets the working directory of the replacement
// process.
Dir string
// contains filtered or unexported fields
}
Handoff coordinates zero-downtime dedicated server restarts on Unix by passing open TCP or Unix listeners to a newly started replacement process and waiting until that child reports ready.
At startup a server calls Inherited(name) for each listener before falling back to net.Listen, starts accepting traffic, and calls SignalReady so its parent knows it may stop accepting and drain its active rooms. On SIGUSR2 (or another operator trigger) the parent calls Upgrade; if the replacement exits early or fails to signal ready before ctx ends, Upgrade returns an error and leaves the parent's listeners untouched and serving.
UDP sockets are not handed off: two processes reading one datagram socket split packets at random. For UDP restarts, start the replacement on a fresh port and send new rooms there.
func (*Handoff) SignalReady ¶
SignalReady waits for h.Ready (when non-nil) to report true, closes any unclaimed inherited listener descriptors so they do not leak, and notifies the parent process over the handoff ready pipe that this process is serving.
On a cold start, under systemd socket activation, or on repeated calls, SignalReady returns nil after waiting for h.Ready and closing unclaimed descriptors.
func (*Handoff) Upgrade ¶
Upgrade starts a replacement process inheriting the file descriptors of h.Listeners and waits until the child signals ready via SignalReady.
If the child exits before signaling ready or ctx expires first, Upgrade cleans up the failed child and returns an error while leaving all listeners in h.Listeners open and serving in the parent process.
type Health ¶
type Health struct {
Ready func() bool
Metrics func() Metrics
// Now is the clock used for readiness hysteresis; nil uses time.Now.
Now func() time.Time
// 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 NewHealthWith ¶
func NewHealthWith(ready func() bool, metrics func() Metrics, opts ...HealthOption) *Health
NewHealthWith returns deployment endpoints configured with opts.
func (*Health) AddCollector ¶
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 (*Health) ObserveMatchTick ¶
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 (*Health) ObserveTick ¶
ObserveTick records the duration of the last server tick for metrics.
func (*Health) OnOverrun ¶
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 (*Health) ServeHTTP ¶
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.
func (*Health) SetBusyReadiness ¶
SetBusyReadiness ANDs !busy() into /readyz with hysteresis (see WithBusyReadiness). Safe to call while Health is serving.
func (*Health) SetDraining ¶
SetDraining overrides the /readyz probe: while draining is true, /readyz returns 503 even when Ready is nil or returns true, while /healthz continues to return 200 so the process is not restarted mid-drain.
type HealthConfig ¶
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 HealthOption ¶
type HealthOption func(*Health)
HealthOption configures optional Health behavior when passed to NewHealthWith.
func WithBusyReadiness ¶
func WithBusyReadiness(busy func() bool, hold time.Duration) HealthOption
WithBusyReadiness ANDs !busy() into /readyz with hysteresis so a host shedding load stops receiving new traffic from load balancers without flapping. Once busy reports true, /readyz returns 503 immediately while /healthz stays 200; /readyz returns to 200 only after busy has reported false continuously for hold (DefaultReadyHold, 5s, when hold == 0; negative disables extra hold beyond busy itself). A nil busy disables busy shedding.
func WithLoadReadiness ¶
func WithLoadReadiness(load func() Load, hold time.Duration) HealthOption
WithLoadReadiness wires a Runner.Load callback into both /readyz (with hold hysteresis, like WithBusyReadiness) and /metrics (via LoadCollector).
type Host ¶
type Host struct {
// Transport is the server transport to drive, such as a *netplay.WebSocketServer or *netplay.UDPServer.
Transport Transport
// Guard enforces per-peer limits before a packet reaches a room; nil accepts everything.
Guard *Guard
// Rooms owns membership and room lifecycle.
Rooms *Rooms
// Runner steps the matches the rooms start.
Runner *Runner
// NewMatch builds the match a room runs when it enters RoomRunning. Returning nil leaves the room running without a simulation; nil starts no match at all.
NewMatch func(room *Room) *Match
// IdleTimeout stops a room's match once the room has held no members for this long; 0 uses DefaultIdleTimeout.
IdleTimeout time.Duration
// Route, when set, decides where an accepted packet goes: a nil return drops it. When nil, the packet is delivered into the room its sender is in.
Route func(room *Room, packet netplay.Packet) *Room
// OnEvent, when set, is called for every peer event drained from Transport.NextEvent.
// For PeerLeft and PeerDropped, Host removes the peer from its rooms and resets Guard before calling OnEvent.
OnEvent func(netplay.PeerEvent)
// Now is the clock for idle timeouts; nil uses time.Now.
Now func() time.Time
// Step is how often Run drains the transport and checks room lifecycles; 0 uses 5ms.
Step time.Duration
// contains filtered or unexported fields
}
Host runs one server: it drains peer events and packets in the order the server needs, enforces per-peer limits, routes accepted packets within rooms, and runs one match per room that is running. It is the single entry point a room-based game needs instead of ordering NextEvent, Recv, Guard.Check, Room.Deliver and Runner.Start itself.
type HostPolicy ¶
type HostPolicy uint8
HostPolicy decides who a room's host is when no peer was named at creation.
const ( // HostOldest makes the earliest-joined member the host, so a transfer after the host leaves is deterministic rather than map-order dependent. HostOldest HostPolicy = iota // HostServer leaves the host to the server, so no player may change settings or start the room; StartBy(0) does. HostServer )
type InspectMatch ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
NewInspector 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 ¶
func NewOperatorInspector(a admin.Authorizer) *Inspector
NewOperatorInspector 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 (*Inspector) ServeHTTP ¶
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 ¶
Join reports a peer's admission and, for a running match, the full snapshot it must apply before accepting deltas.
type LeaveReason ¶
type LeaveReason uint8
LeaveReason 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 (LeaveReason) String ¶
func (r LeaveReason) String() string
String returns the reason's name in lowercase, such as "quit" or "kicked".
type LimitPolicy ¶
type LimitPolicy uint8
LimitPolicy 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 ¶
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
// OwnerUpdatesPerSecond bounds replication owner-update packets
// (ClientWorld.Publish) from one peer; BurstOwnerUpdates allows a short
// burst on top, defaulting to one second's rate. Other replication packets
// such as acknowledgments do not consume this bucket.
OwnerUpdatesPerSecond float64
BurstOwnerUpdates 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 ¶
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 ¶
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 Load ¶
type Load struct {
// Window is the sliding window the percentiles and ratios cover.
Window time.Duration
// Ticks is the total ticks completed across all matches inside Window.
Ticks int
// Overruns is the total overrunning ticks across all matches inside Window.
Overruns int
// OverrunRatio is Overruns / Ticks across all matches inside Window (0 when Ticks is 0).
OverrunRatio float64
// P50 is the 50th percentile tick duration across all matches inside Window.
P50 time.Duration
// P99 is the 99th percentile tick duration across all matches inside Window.
P99 time.Duration
// MailboxWarning is true when any running match's mailbox is past its warning threshold.
MailboxWarning bool
// Busy is true when the runner is shedding load: the overrun share in
// Window passed OverrunRatio, a match mailbox is in backlog warning, or
// recovery hysteresis has not finished clearing.
Busy bool
// Matches holds per-match load snapshots ordered by Name.
Matches []MatchLoad
}
Load is a point-in-time snapshot of a Runner's tick and mailbox load over Window, with its hysteresis-filtered Busy state.
type LoadPolicy ¶
type LoadPolicy struct {
// OverrunRatio is the share of ticks in Window that overran at which
// Runner.Load becomes Busy (for example 0.05 for 5%). Zero uses
// DefaultLoadOverrunRatio; a negative value disables overrun-based busy
// detection while keeping mailbox warnings active.
OverrunRatio float64
// ClearRatio is the overrun share at or below which a busy runner may
// clear Busy (ratio hysteresis). When zero or >= OverrunRatio, half of
// OverrunRatio is used.
ClearRatio float64
// Window is the sliding window over which tick p50/p99 and the overrun
// ratio are computed. DefaultLoadWindow (10s) when zero or negative.
Window time.Duration
// Cooldown is the minimum time the runner must remain healthy (overrun
// ratio at or below ClearRatio and no match mailbox in backlog warning)
// before Busy clears. Zero uses Window / 2; a negative value disables
// time cooldown while keeping ClearRatio and mailbox hysteresis.
Cooldown time.Duration
}
LoadPolicy configures how Runner.Load measures tick health and decides when the server sheds load. Zero values select sensible defaults.
type LobbyEvent ¶
type LobbyEvent struct {
Kind LobbyEventKind
Room uint64
Peer netplay.PeerID
Ready bool
Host netplay.PeerID
}
LobbyEvent is one lobby change a game may broadcast; Rooms drains them with LobbyEvents.
type LobbyEventKind ¶
type LobbyEventKind uint8
LobbyEventKind is what changed in a room's lobby.
const ( // LobbyReadyChanged reports one member's ready flag. LobbyReadyChanged LobbyEventKind = iota + 1 // LobbyHostChanged reports a room's host after a transfer. LobbyHostChanged )
type Match ¶
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
// MailboxWarning is the queued callback count at which MailboxBacklog
// reports a backlog warning (and Runner.Load marks the runner busy).
// Zero defaults to three-quarters of Mailbox capacity (768 for 1024);
// a negative value disables the warning for this match.
MailboxWarning 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 (*Match) Call ¶
Call 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 (*Match) MailboxBacklog ¶
MailboxBacklog reports whether the match's mailbox has crossed its warning threshold (MailboxWarning, defaulting to three-quarters of capacity) and has not yet drained to half of that threshold.
func (*Match) MailboxLen ¶
MailboxLen reports how many queued callbacks have not run yet.
type MatchConfig ¶
type MatchConfig struct {
Rate int `yaml:"rate,omitempty"`
}
MatchConfig is how often the server steps its matches, in steps per second.
type MatchHandler ¶
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 MatchLoad ¶
type MatchLoad struct {
// Name is the match's name.
Name string
// Ticks is the number of ticks completed inside Window.
Ticks int
// Overruns is the number of ticks inside Window that finished past the
// next tick's deadline.
Overruns int
// OverrunRatio is Overruns / Ticks (0 when Ticks is 0).
OverrunRatio float64
// P50 is the 50th percentile tick duration inside Window.
P50 time.Duration
// P99 is the 99th percentile tick duration inside Window.
P99 time.Duration
// MailboxLen is the number of callbacks currently queued in the match's mailbox.
MailboxLen int
// MailboxCap is the match's mailbox capacity.
MailboxCap int
// MailboxWarning is true when the match's mailbox is in backlog warning.
MailboxWarning bool
}
MatchLoad is one match's tick and mailbox health over Load.Window.
type Matchmaker ¶
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.
Example ¶
A Matchmaker groups waiting tickets of the same mode and region into rooms of players with close ratings; the accepted rating gap widens the longer a ticket waits.
package main
import (
"fmt"
"time"
"github.com/nsgo-dev/game/pkg/online/gameserver"
)
func main() {
now := time.Unix(0, 0)
mm := gameserver.NewMatchmaker(2)
mm.BaseWindow, mm.WindowGrowthPerSecond, mm.MaxWindow = 50, 10, 500
mm.Now = func() time.Time { return now }
mm.Enqueue(gameserver.Ticket{ID: 1, Mode: "duel", Region: "eu", Rating: 1500, Party: []string{"ada"}})
mm.Enqueue(gameserver.Ticket{ID: 2, Mode: "duel", Region: "eu", Rating: 1620, Party: []string{"bo"}})
fmt.Println(len(mm.Match()), mm.Len())
now = now.Add(10 * time.Second)
for _, m := range mm.Match() {
fmt.Println(m.Mode, m.Region, m.Players)
}
fmt.Println(mm.Len())
}
Output: 0 2 duel eu [ada bo] 0
func NewMatchmaker ¶
func NewMatchmaker(roomSize int) *Matchmaker
NewMatchmaker returns a matchmaker for rooms of roomSize players.
func (*Matchmaker) Cancel ¶
func (m *Matchmaker) Cancel(id uint64) bool
Cancel removes ticket id and reports whether it was waiting.
func (*Matchmaker) Enqueue ¶
func (m *Matchmaker) Enqueue(t Ticket) error
Enqueue adds a ticket, defaulting its EnqueuedAt to the matchmaker's clock.
func (*Matchmaker) Expire ¶
func (m *Matchmaker) Expire() []Ticket
Expire removes and returns expired tickets in deadline, enqueue time and ID order.
func (*Matchmaker) Match ¶
func (m *Matchmaker) Match() []Matchup
Match 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 (*Matchmaker) Waiting ¶
func (m *Matchmaker) Waiting() []Ticket
Waiting returns copies of the queued tickets, oldest first.
type Matchup ¶
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 ¶
MemoryDirectory is a deterministic in-process Directory for tests and one-process deployments.
func (*MemoryDirectory) Heartbeat ¶
func (d *MemoryDirectory) Heartbeat(address string, seenAt time.Time) error
Heartbeat marks the registered server at address as seen at seenAt, keeping it in the directory for another TTL.
func (*MemoryDirectory) List ¶
func (d *MemoryDirectory) List(region string) []ServerInfo
List 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 (*MemoryDirectory) Place ¶
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 (*MemoryDirectory) Register ¶
func (d *MemoryDirectory) Register(info ServerInfo) error
Register 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 (*MemoryDirectory) Remove ¶
func (d *MemoryDirectory) Remove(address string)
Remove drops the server at address from the directory.
type ModeConfig ¶
type ModeConfig struct {
// Capacity is the seats a room of this mode opens with; 0 uses four.
Capacity int
// AllowLateJoin lets QuickJoin place a peer in a room whose match is already running; the peer receives the room's Snapshot. Zero value false only offers rooms that have not started.
AllowLateJoin bool
}
ModeConfig is what QuickJoin knows about one room mode.
type NumericRange ¶
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 ¶
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 (Panic) Report ¶
func (p Panic) Report() crashreport.CrashReport
Report 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 ¶
type PanicAction uint8
PanicAction 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 ¶
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 (*PanicError) Error ¶
func (e *PanicError) Error() string
Error returns the panic value as an asynchronous job error.
type PeerKicker ¶
PeerKicker is the part of a server transport needed by the built-in kick command. *netplay.WebSocketServer and *netplay.UDPServer both implement it.
type PeerStats ¶
type PeerStats struct {
Packets uint64
Bytes uint64
Dropped uint64
Violations uint64
PendingBytes int
}
PeerStats counts one peer's traffic and refusals.
type Policy ¶
type Policy string
Policy 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 (Policy) GuardPolicy ¶
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 ¶
type Query []Term
Query 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 ¶
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.
type RecordGrant ¶
RecordGrant replaces the record at Key with Value. Version must equal the stored record's version, else the commit is a conflict.
type Reservation ¶
Reservation is an opaque seat claim for one account until Expires.
type ResultCommit ¶
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 ¶
ResultReceipt identifies a committed result and repeats its match metadata. Applied is false for an identical retry of a result already committed.
type ResultsBackend ¶
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 ¶
func NewResultsBackend() *ResultsBackend
NewResultsBackend returns an empty backend.
func (*ResultsBackend) Balance ¶
func (b *ResultsBackend) Balance(account, currency string) int64
Balance returns the accumulated wallet amount for account and currency.
func (*ResultsBackend) BestScore ¶
func (b *ResultsBackend) BestScore(board, account string) (int64, bool)
BestScore returns the highest score committed for board and account.
func (*ResultsBackend) Commit ¶
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 (*ResultsBackend) DeliverScores ¶
func (b *ResultsBackend) DeliverScores(ctx context.Context, sink ScoreSink) error
DeliverScores drains the score outbox in order. A failed delivery leaves the failed grant and all following grants queued for a later retry.
func (*ResultsBackend) Has ¶
func (b *ResultsBackend) Has(matchID string) bool
Has reports whether a result for matchID has been committed.
func (*ResultsBackend) PendingScores ¶
func (b *ResultsBackend) PendingScores() []ScoreGrant
PendingScores returns a copy of score grants waiting for delivery.
func (*ResultsBackend) Record ¶
func (b *ResultsBackend) Record(key string) (RecordGrant, bool)
Record returns the current grant for key, if one has been committed.
type Room ¶
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 (*Room) Advance ¶
func (r *Room) Advance()
Advance increments the room's tick while a match runs.
func (*Room) AllReady ¶
AllReady reports whether the room can start: it needs at least two members and every member except the host ready, since the host starts the match. A HostServer room needs both members ready.
func (*Room) Broadcast ¶
func (r *Room) Broadcast(tx netplay.Transport, ch netplay.Channel, payload []byte, except ...netplay.PeerID) []netplay.PeerID
Broadcast 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 (*Room) Deliver ¶
Deliver 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 (*Room) Drain ¶
Drain 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 (*Room) End ¶
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 (*Room) HasPassword ¶
HasPassword reports whether the room needs a password to join.
func (*Room) Host ¶
Host returns the room's host: the peer named at creation while it is the host, otherwise the earliest-joined member, or 0 for a room under HostServer or with no members.
func (*Room) InboxStats ¶
func (r *Room) InboxStats() RoomInboxStats
InboxStats reads the room's inbox counters.
func (*Room) MatchData ¶
MatchData returns the current epoch and its pinned data together. The snapshot stays available after End until the next Start.
func (*Room) Members ¶
Members returns the current peers in join order. A peer that leaves and joins again moves to the end.
func (*Room) Recv ¶
Recv pops the next packet delivered by peer. Non-members and empty inboxes report false. To read every member fairly, use Drain.
func (*Room) SetHandler ¶
func (r *Room) SetHandler(handler MatchHandler)
SetHandler attaches the lifecycle handler. It should be called before joins.
func (*Room) SetReady ¶
SetReady sets one member's ready flag and reports the change. A peer outside the room is ErrNotInRoom.
func (*Room) SetSetting ¶
SetSetting changes one lobby setting for the host and clears every ready flag so members ready again against the new rules. A peer other than the host is ErrNotHost; setting a value the room already holds changes nothing.
func (*Room) Signal ¶
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 (*Room) Start ¶
Start 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 (*Room) StartBy ¶
StartBy starts the room's match through its host once every other member is ready. A peer other than the host is ErrNotHost; a peer of a HostServer room passes 0. A lobby that is not all ready is ErrNotReady.
func (*Room) StartWithData ¶
StartWithData 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.
type RoomFilter ¶
type RoomFilter struct {
// Mode matches rooms whose "mode" setting equals it; empty matches every mode.
Mode string
// NotFull keeps rooms with a free seat.
NotFull bool
// Waiting keeps rooms whose match has not started.
Waiting bool
// IncludePrivate keeps private rooms in the result; they are left out otherwise.
IncludePrivate bool
}
RoomFilter narrows Find.
type RoomInboxStats ¶
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 ¶
type RoomInfo struct {
ID uint64
Capacity int
State RoomState
Epoch uint64
Tick uint64
Members int
Private bool
Label map[string]string
Name string
Host netplay.PeerID
Ready int
HasPassword bool
Settings map[string]string
}
RoomInfo is a snapshot of a room for listing.
type RoomLimits ¶
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 RoomOptions ¶
type RoomOptions struct {
// Capacity is the most peers; 0 uses four.
Capacity int
// Private rooms are hidden from Find unless it asks for them, and get a join code.
Private bool
// Name is the display name a lobby shows.
Name string
// Password protects the room: it is stored as a salted scrypt hash and compared in constant time, never kept in plain text. Empty means no password.
Password string
// Settings are the initial lobby settings, such as a mode or a map; the room copies them.
Settings map[string]string
}
RoomOptions is what CreateWith opens a room with: its seats, privacy, display name, optional password and initial settings.
type Rooms ¶
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
// HostPolicy decides who a room's host is when no peer was named at creation; the zero value is HostOldest.
HostPolicy HostPolicy
// Modes are the modes QuickJoin may place peers in, keyed by the mode name a room carries in its "mode" setting.
Modes map[string]ModeConfig
// contains filtered or unexported fields
}
Rooms manages the rooms of one server process.
Example ¶
Rooms hosts matches: players join by ID or by a private room's code, and Start begins a match epoch that late joiners catch up to.
package main
import (
"fmt"
"github.com/nsgo-dev/game/pkg/online/gameserver"
)
func main() {
rooms := gameserver.NewRooms()
rooms.CodeGenerator = func() string { return "KX7Q" }
room, err := rooms.Create(4, true)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(room.Code(), room.State())
rooms.JoinCode("KX7Q", 1)
rooms.Join(room.ID(), 2)
room.Start()
room.Advance()
j, err := rooms.Join(room.ID(), 3)
// Members lists peers in join order.
fmt.Println(err, room.Members(), room.State(), j.Epoch, j.Tick)
}
Output: KX7Q waiting <nil> [1 2 3] running 1 1
func (*Rooms) Claim ¶
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 (*Rooms) Create ¶
Create opens a room. capacity <= 0 uses four players. A private room gets a code that JoinCode accepts.
func (*Rooms) CreateWith ¶
CreateWith opens a room with a lobby, naming host as its host. A host of 0 leaves the host to the Rooms.HostPolicy, which is the earliest-joined member by default.
func (*Rooms) Find ¶
func (rs *Rooms) Find(f RoomFilter) []RoomInfo
Find returns the open rooms matching f, in ID order. Private rooms are included only when f asks for them.
func (*Rooms) Get ¶
Get returns the open room with id, or false once it is closed or was never opened.
func (*Rooms) Join ¶
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 (*Rooms) JoinOrCreate ¶
JoinOrCreate admits peer to the lowest-numbered public waiting room without a password that has a free seat, or creates a new public room with capacity seats. It retries when a separate direct Join fills or closes the selected room between the selection and admission. A non-positive capacity uses the default room capacity.
func (*Rooms) JoinPassword ¶
JoinPassword admits peer to room id after checking its password. A room without a password ignores the password and admits as Join does; a wrong password is ErrWrongPassword.
func (*Rooms) JoinPasswordWithMeta ¶
func (rs *Rooms) JoinPasswordWithMeta(id uint64, peer netplay.PeerID, password, account string, meta []byte) (Join, error)
JoinPasswordWithMeta is JoinPassword passing the account and metadata the match handler sees, like JoinWithMeta.
func (*Rooms) JoinWithMeta ¶
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 (*Rooms) Leave ¶
Leave removes peer from room id and reports whether it was a member. The room closes after EmptyTimeout once its last member leaves.
func (*Rooms) LeaveWithReason ¶
LeaveWithReason removes a peer and notifies the match handler.
func (*Rooms) LobbyEvents ¶
func (rs *Rooms) LobbyEvents() []LobbyEvent
LobbyEvents returns the lobby changes since the last call, in the order they happened, and clears the queue.
func (*Rooms) MemberCount ¶
MemberCount returns the number of members across all open rooms, the count MaxMembers caps.
func (*Rooms) QuickJoin ¶
QuickJoin places peer in the fullest public room of mode with a free seat, or opens one when every room is full. Rooms fill before new ones open: the fullest room wins and the lowest ID breaks ties, so the placement is deterministic. Concurrent QuickJoin calls are serialized, so a burst of players fills existing rooms instead of opening one room each. A mode the server does not configure is ErrUnknownMode; a server at Rooms.Capacity.MaxRooms with no free seat is ErrNoCapacity.
func (*Rooms) SetCapacity ¶
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 (*Rooms) SetLimits ¶
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 (*Rooms) SetLoad ¶
SetLoad sets the process-wide admission limits and a Runner.Load callback. While load reports Busy, MailboxWarning, or an OverrunRatio past c.OverrunRatio (when positive), Create and the join of a new member return ErrServerBusy; members already in a room keep resuming and leaving. load runs without any Rooms or Room lock held; a nil load checks only room and member caps.
type RoomsConfig ¶
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 ¶
Rule 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 ¶
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
// LoadPolicy configures the sliding window, overrun ratio threshold, and
// recovery hysteresis used by Load and Busy. Zero values select defaults
// (10s window, 0.05 overrun ratio, 0.025 clear ratio, 5s cooldown).
LoadPolicy LoadPolicy
// Now is the clock used by Load for sliding-window expiration and
// recovery cooldowns; nil uses time.Now.
Now func() time.Time
// contains filtered or unexported fields
}
Runner steps the matches in Matches concurrently, each at its own rate, until its context is canceled.
Example ¶
A Runner steps each match at its own fixed rate until its context is canceled, then calls the match's OnStop. Here the match ends itself after three ticks by canceling the context.
package main
import (
"context"
"fmt"
"time"
"github.com/nsgo-dev/game/pkg/online/gameserver"
)
func main() {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
ticks := 0
r := &gameserver.Runner{Matches: []*gameserver.Match{{
Name: "arena-1",
Rate: 1000,
Update: func(dt time.Duration) {
ticks++
fmt.Println("tick", ticks, dt)
if ticks == 3 {
cancel()
}
},
OnStop: func() { fmt.Println("stopped after", ticks, "ticks") },
}}}
fmt.Println(r.Run(ctx))
}
Output: tick 1 1ms tick 2 1ms tick 3 1ms stopped after 3 ticks <nil>
func (*Runner) Busy ¶
Busy reports whether the runner is currently shedding load. It is shorthand for r.Load().Busy and plugs directly into Rooms.SetCapacity, RefuseWhenBusy, and Health.SetBusyReadiness.
func (*Runner) Load ¶
Load returns a snapshot of the runner's per-match tick p50/p99 durations, overrun ratio over LoadPolicy.Window, mailbox warnings, and hysteresis-filtered Busy flag. Safe to call concurrently with Run and from HTTP handlers.
func (*Runner) Run ¶
Run 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 or appears twice in Matches.
func (*Runner) Start ¶
Start runs m in an already running Runner and returns a stop function that ends it and waits for its current tick to finish. After Run returns, or before it starts, Start returns a no-op stop and runs nothing. A match runs once: start a new Match to run it again. A nil Update makes Start a no-op. Do not call the returned stop from m.Update or a callback it queued, which would wait for itself.
type RuntimeInfo ¶
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 ¶
ScoreGrant records Score for Account on Board, keeping the account's best score.
type ScoreSink ¶
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 ¶
ServerInfo describes a game-server process in a directory.
type SignedReservation ¶
type SignedReservation struct {
Reservation Reservation `json:"reservation"`
Signature []byte `json:"signature"`
}
SignedReservation is a portable, signed seat claim for a room.
func SignReservation ¶
func SignReservation(res Reservation, key ed25519.PrivateKey) (SignedReservation, error)
SignReservation encodes and signs a reservation with Ed25519.
type Store ¶
type Store interface {
// Write stores data under key, honoring ctx when possible.
Write(ctx context.Context, key string, data []byte) error
// Read loads the stored snapshot for key, or an error wrapping os.ErrNotExist when absent.
Read(ctx context.Context, key string) ([]byte, error)
}
Store persists named world snapshots for Autosave.
func FileStore ¶
FileStore returns a Store that writes each key as a plain-text YAML or JSON file in dir using the same atomic staging, backup (.bak), directory sync, and stale temporary-file cleanup mechanics as pkg/save.
Write refuses empty, binary, or syntactically invalid YAML/JSON snapshots without touching existing files. Read falls back to <key>.bak when the primary file is absent, unreadable, or corrupt.
type TLSConfig ¶
TLSConfig names the certificate and key files for the WebSocket listener; both are required together.
type Term ¶
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 ¶
type TermKind uint8
TermKind is how a Term affects a match: Must and MustNot filter candidates, Should ranks them.
type Ticket ¶
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.
type Transport ¶
type Transport interface {
netplay.Transport
NextEvent() (netplay.PeerEvent, bool)
Kick(netplay.PeerID, string) error
}
Transport is one netplay server transport a Host drives: the messaging interface plus the peer lifecycle events and the Kick that ends one session.
type UDPListen ¶
type UDPListen struct {
Addr string `yaml:"addr,omitempty"`
}
UDPListen is the plain UDP listener's host:port.
type WalletGrant ¶
WalletGrant changes Account's balance of Currency by Amount.
type WebSocketListen ¶
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.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package loadtest is experimental: its API and documented formats may change in a minor release; see https://nsgo.games/docs/stability/.
|
Package loadtest is experimental: its API and documented formats may change in a minor release; see https://nsgo.games/docs/stability/. |