Documentation
¶
Overview ¶
Package server runs one or more matches of a game at fixed tick rates in a plain Go process, without an NSGo app, window or core.Scope.
The Update function a game gives game.Loop runs unchanged here: each match steps it with the same fixed dt, so dedicated-server code and client-side prediction share one simulation.
Index ¶
- Variables
- type Guard
- func (g *Guard) Check(peer netpkg.PeerID, packet netpkg.Packet) (GuardAction, error)
- func (g *Guard) ReleaseReliable(peer netpkg.PeerID, n int)
- func (g *Guard) ReserveReliable(peer netpkg.PeerID, n int) error
- func (g *Guard) Reset(peer netpkg.PeerID)
- func (g *Guard) Stats(peer netpkg.PeerID) PeerStats
- type GuardAction
- type Health
- type Join
- type LimitPolicy
- type Limits
- type Match
- type Matchmaker
- type Matchup
- type Metrics
- type PeerStats
- type Room
- func (r *Room) Advance()
- func (r *Room) Capacity() int
- func (r *Room) Code() string
- func (r *Room) Deliver(from netpkg.PeerID, p netpkg.Packet) error
- func (r *Room) End()
- func (r *Room) Epoch() uint64
- func (r *Room) ID() uint64
- func (r *Room) Members() []netpkg.PeerID
- func (r *Room) Recv(peer netpkg.PeerID) (netpkg.Packet, bool)
- func (r *Room) Start() error
- func (r *Room) State() RoomState
- func (r *Room) Tick() uint64
- type RoomInfo
- type RoomState
- type Rooms
- func (rs *Rooms) Create(capacity int, private bool) (*Room, error)
- func (rs *Rooms) Join(id uint64, peer netpkg.PeerID) (Join, error)
- func (rs *Rooms) JoinCode(code string, peer netpkg.PeerID) (Join, error)
- func (rs *Rooms) Leave(id uint64, peer netpkg.PeerID) bool
- func (rs *Rooms) List() []RoomInfo
- func (rs *Rooms) Tick() []uint64
- type Rule
- type Runner
- type Ticket
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var ( // ErrMessageTooLarge reports a packet larger than Limits.MaxMessageSize. ErrMessageTooLarge = errors.New("server: message too large") // ErrPendingLimit reports reliable bytes past Limits.MaxPendingReliable. ErrPendingLimit = errors.New("server: pending reliable data limit") // ErrInvalidInput reports input refused by Guard.Validate. ErrInvalidInput = errors.New("server: invalid input") // ErrPeerDisconnected reports a peer the guard has disconnected. ErrPeerDisconnected = errors.New("server: peer disconnected") )
var ( // ErrInvalidTicket reports a ticket with no player or a non-positive room size. ErrInvalidTicket = errors.New("server: invalid matchmaking ticket") // ErrDuplicateTicket reports a ticket ID already waiting in the queue. ErrDuplicateTicket = errors.New("server: duplicate matchmaking ticket") )
var ( // ErrRoomNotFound reports a room ID or code that names no open room. ErrRoomNotFound = errors.New("server: room not found") // ErrRoomFull reports a join to a room already at capacity. ErrRoomFull = errors.New("server: room full") // ErrRoomEnded reports an action on a room whose match has ended. ErrRoomEnded = errors.New("server: room match ended") // ErrNotInRoom reports a packet from a peer that is not a room member. ErrNotInRoom = errors.New("server: peer is not in this room") )
Functions ¶
This section is empty.
Types ¶
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(netpkg.PeerID, netpkg.Packet) error
// Now is the token-bucket clock; nil uses time.Now.
Now func() time.Time
// contains filtered or unexported fields
}
Guard enforces per-peer limits and validates inputs before a simulation sees them. It is safe on the server's packet loop and independent per peer.
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"
gamenet "github.com/nsgo-dev/game/pkg/net"
"github.com/nsgo-dev/game/pkg/server"
)
func main() {
now := time.Unix(0, 0)
g := server.NewGuard(server.Limits{PacketsPerSecond: 2, BurstPackets: 2, MaxMessageSize: 64}, server.LimitThrottle)
g.Now = func() time.Time { return now }
names := map[server.GuardAction]string{server.GuardAllow: "allow", server.GuardThrottle: "throttle", server.GuardDisconnect: "disconnect"}
small := gamenet.Packet{Payload: make([]byte, 10)}
for range 3 {
action, err := g.Check(7, small)
fmt.Println(names[action], err)
}
_, err := g.Check(8, gamenet.Packet{Payload: make([]byte, 100)})
fmt.Println(err)
}
Output: allow <nil> allow <nil> throttle server: packet rate limited server: 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.
type GuardAction ¶
type GuardAction uint8
GuardAction is the result of Guard.Check.
const ( GuardAllow GuardAction = iota GuardThrottle GuardDisconnect )
type Health ¶
type Health struct {
Ready func() bool
Metrics func() Metrics
// contains filtered or unexported fields
}
Health serves a game server's deployment endpoints:
GET /healthz 200 while the process is alive GET /readyz 200 when Ready reports true, else 503 GET /metrics Prometheus text metrics from Metrics
Ready and Metrics are optional; a nil Ready is always ready and a nil Metrics reports zeros.
func (*Health) ObserveTick ¶
ObserveTick records the duration of the last server tick for metrics.
type Join ¶
Join reports a peer's admission and, for a running match, the full snapshot it must apply before accepting deltas.
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. 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
// 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 ¶
type Match struct {
// Name identifies the match in overrun reports; optional.
Name string
// Rate is how many updates run a second, 60 when 0 or negative.
Rate int
// Update moves the match on by dt, always 1/Rate seconds. It runs on the
// runner's goroutine and must return promptly.
Update func(dt time.Duration)
// OnStop runs once after the match's final tick when the context ends,
// for notifying peers or flushing state. Optional.
OnStop func()
}
Match is one game simulation stepped at Rate ticks per second.
type Matchmaker ¶
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.
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/server"
)
func main() {
now := time.Unix(0, 0)
mm := server.NewMatchmaker(2)
mm.BaseWindow, mm.WindowGrowthPerSecond, mm.MaxWindow = 50, 10, 500
mm.Now = func() time.Time { return now }
mm.Enqueue(server.Ticket{ID: 1, Mode: "duel", Region: "eu", Rating: 1500, Party: []string{"ada"}})
mm.Enqueue(server.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) 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.
func (*Matchmaker) Waiting ¶
func (m *Matchmaker) Waiting() []Ticket
Waiting returns copies of the queued tickets, oldest first.
type PeerStats ¶
type PeerStats struct {
Packets uint64
Bytes uint64
Dropped uint64
Violations uint64
PendingBytes int
}
PeerStats counts one peer's traffic and refusals.
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.
func (*Room) Advance ¶
func (r *Room) Advance()
Advance increments the room's tick while a match runs.
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.
func (*Room) End ¶
func (r *Room) End()
End ends the running match. The room stays open so its peers can see the result; a later Start begins the next epoch.
func (*Room) Recv ¶
Recv pops the next packet delivered by peer. Non-members and empty inboxes report false.
type RoomInfo ¶
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 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
// 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"
"slices"
"github.com/nsgo-dev/game/pkg/server"
)
func main() {
rooms := server.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 does not keep admission order, so sort it before printing.
members := room.Members()
slices.Sort(members)
fmt.Println(err, members, room.State(), j.Epoch, j.Tick)
}
Output: KX7Q waiting <nil> [1 2 3] running 1 1
func (*Rooms) Create ¶
Create opens a room. capacity <= 0 uses four players. A private room gets a code that JoinCode accepts.
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.
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
// OnOverrun, when set, reports a tick whose Update ran longer than its
// interval. lag is the time past the interval and missed is how many whole
// intervals that covers. The runner does not catch up the missed ticks: the
// next tick is scheduled from now, so a slow update slows the match instead
// of running a burst.
OnOverrun func(m *Match, lag time.Duration, missed int)
}
Runner steps the matches in Matches concurrently, each at its own rate, until its context is canceled.
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/server"
)
func main() {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
ticks := 0
r := &server.Runner{Matches: []*server.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>
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
}
Ticket is one matchmaking request. A party stays together in a room.
Directories
¶
| Path | Synopsis |
|---|---|
|
cmd
|
|
|
dedicatedserver
command
Command dedicatedserver runs one fixed-step match in a plain Go process.
|
Command dedicatedserver runs one fixed-step match in a plain Go process. |