netplay

package
v0.4.0-rc.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 4, 2026 License: Apache-2.0 Imports: 43 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package netplay is experimental: its API and documented formats may change in a minor release; see https://nsgo.games/docs/stability/.

Package netplay provides cross-target multiplayer primitives for NSGo games:

  • Transport abstraction with deterministic in-memory loopback, pure-Go RFC 6455 WebSocket (native + browser WebAssembly), HTTP/3 QUIC WebTransport (native + browser WebAssembly), and native UDP transports.
  • Server-authoritative state replication with bitmask delta compression, snapshot interpolation, and client-side prediction/reconciliation.
  • Deterministic lockstep and GGPO-style rollback netcode with periodic checksum verification and desync detection.
  • A Relay that forwards peer-to-peer sessions between RelayTransports over WebSocket, WebTransport, or UDP for players who cannot reach each other directly.

Index

Examples

Constants

View Source
const (
	// DefaultOutboxFrames is the most frames a WebSocketServer or WebTransportServer holds for one client when OutboxLimits.Frames is zero, as many as a Relay holds for one member.
	DefaultOutboxFrames = 256
	// DefaultOutboxBytes is the most bytes of frames a WebSocketServer or WebTransportServer holds for one client when OutboxLimits.Bytes is zero.
	DefaultOutboxBytes = 4 << 20
)
View Source
const (
	// DefaultRPCTimeout is the deadline applied by Call when CallOptions.Timeout is zero.
	DefaultRPCTimeout = 5 * time.Second
	// DefaultRPCCacheSize is the default number of recent RPC responses retained per peer for deduplication.
	DefaultRPCCacheSize = 64
	// MaxStatusMessageBytes caps the UTF-8 byte length of Status.Message on the wire.
	MaxStatusMessageBytes = 1024
)
View Source
const (
	// ChannelReliableOrdered guarantees delivery in send order. A transport that cannot provide that guarantee refuses it with ErrUnsupportedChannel rather than silently dropping packets; UDPServer and UDPClient implement end-to-end reliability with selective acknowledgements, while raw peer-to-peer UDPTransport still refuses reliable channels.
	ChannelReliableOrdered Channel = 0
	// ChannelUnreliable delivers best-effort packets that may be dropped or reordered.
	ChannelUnreliable Channel = 1
	// ChannelUnreliableSequenced delivers best-effort packets at most once and drops any packet older than the newest already delivered from that peer on this channel. Over ordered stream transports such as WebSocket it delivers in send order like a reliable channel while remaining droppable under inbox or outbox pressure.
	ChannelUnreliableSequenced Channel = 2

	// FirstReliableLane is the first Channel value reserved for extra independent reliable ordered lanes configured via ChannelConfig.Lanes.
	FirstReliableLane Channel = 3
	// MaxReliableLanes is the maximum number of extra independent reliable ordered lanes ChannelConfig.Lanes accepts.
	MaxReliableLanes = 64

	// DefaultMTU is the default UDP datagram size ceiling in bytes (including headers and AEAD tag) above which UDPServer and UDPClient split payloads into numbered fragments. 1200 bytes fits below the 1280-byte IPv6 minimum path MTU after IP and UDP headers.
	DefaultMTU = 1200
	// MinMTU is the smallest UDP datagram MTU ChannelConfig.MTU accepts.
	MinMTU = 256
	// DefaultMaxReassemblyBytes is the default per-peer limit on payload bytes held in incomplete fragmented messages (1 MiB).
	DefaultMaxReassemblyBytes = 1 << 20
)
View Source
const (
	// DefaultUnreliableInbox is the most ChannelUnreliable packets a transport's inbox holds from one peer when InboxLimits.Unreliable is zero.
	DefaultUnreliableInbox = 4096
	// DefaultReliableInbox is the most ChannelReliableOrdered packets a WebSocketServer's, WebTransportServer's, or RelayTransport's inbox holds from one peer when InboxLimits.Reliable is zero.
	DefaultReliableInbox = 16384
	// DefaultReliableInboxWarning is the ChannelReliableOrdered backlog that raises a warning when InboxLimits.ReliableWarning is zero.
	DefaultReliableInboxWarning = 4096
)
View Source
const AckHeaderSize = 12

AckHeaderSize is the encoded size of an AckHeader: a 4-byte Next and an 8-byte Mask, both big-endian.

View Source
const CaptureVersion = 1

CaptureVersion is the version of the JSON Lines packet capture format written by NewCaptureTransport and read by ReadCapture.

View Source
const DatagramFrameOverhead = 2

DatagramFrameOverhead is the length prefix Poll writes before each message in a datagram.

View Source
const (
	// DefaultCompressionMinSize is the minimum payload size in bytes that transports compress when CompressionConfig.Enabled is true and MinSize is zero.
	DefaultCompressionMinSize = 256
)
View Source
const (
	// DefaultMaxSnapshotSize is the largest snapshot payload a ServerWorld passes to Transport.Send unless SetMaxSnapshotSize changes it. It fits every transport in this package: UDP datagrams (65000 bytes), relay messages (MaxRelayPayload) and WebSocket frames.
	DefaultMaxSnapshotSize = 60000
)
View Source
const LayoutVersion = 1

LayoutVersion is the version of the external entity layout schema.

View Source
const MaxEntitiesPerSnapshot = 1 << 16

MaxEntitiesPerSnapshot bounds a full snapshot's entity count. The map is allocated before each entity is read, so a corrupt 3.8MB packet claiming a million entities would reserve hundreds of megabytes before failing (#546).

View Source
const MaxJoinStateSize = 16 << 20

MaxJoinStateSize is the largest snapshot, as returned by SimState.Save, that a host sends a joining peer. AddPeer refuses a peer with ErrPayloadTooLarge while the state is larger, and a join whose state has grown past it by the join tick is turned into a leave at that tick.

View Source
const (

	// MaxRelayPayload is the largest payload RelayTransport.Send accepts: what fits in one UDP datagram after the relay's and the transport's headers.
	MaxRelayPayload = 64000
)

Relay wire format, version 1. Every relay frame travels as one ChannelUnreliable packet of the inner client or server transport, because reliability is end to end between the two RelayTransports, not per hop:

client to relay: version(1) to(4) body
relay to client: version(1) from(4) body

A frame from the relay itself has from 0 and carries a control message:

members: version(1) 0(4) relayCtlMembers(1) epoch(4) count(2) peer(4)...

The epoch counts the session's membership changes. The relay sends the membership again every second with the same epoch, and a client compares epochs as serial numbers, so the counter may wrap.

A body between two peers is one of:

unreliable: relayBodyUnreliable(1) seq(4) payload
reliable:   relayBodyReliable(1) seq(4) payload
ack:        relayBodyAck(1) next(4) mask(8)

An ack says every reliable seq below next arrived, and bit i of mask says next+1+i arrived too, so the sender retransmits only what is missing.

View Source
const MaxTokenSize = 4096

MaxTokenSize is the largest credential a client may present in the handshake.

View Source
const ReplicationConfigVersion = 1

ReplicationConfigVersion is the version of the world replication configuration YAML format (net/replication.yaml).

View Source
const ReplicationSchemaComment = "# yaml-language-server: $schema=" + ReplicationSchemaURL

ReplicationSchemaComment is the yaml-language-server header line EncodeReplicationYAML writes at the top of a replication configuration file.

View Source
const ReplicationSchemaURL = "https://nsgo.games/schemas/replication.v1.json"

ReplicationSchemaURL is where the JSON Schema of version 1 world replication configuration files (net/replication.yaml) is published.

View Source
const ReplicationVersion = 3

ReplicationVersion is the version of the replication wire protocol that ServerWorld and ClientWorld speak. Version 2 added the replication epoch; version 3 widened the entity mask to 16 bits, added EntityState.Owner, and added client-to-server OwnerUpdate messages. Peers of other versions cannot exchange snapshots and are refused with ErrReplicationVersion.

Variables

View Source
var (

	// ErrMalformedDatagram is returned by SplitDatagram for a datagram whose length prefixes do not describe its bytes exactly.
	ErrMalformedDatagram = errors.New("net: malformed paced datagram")
	// ErrCongestionBudget is returned when UnreliableRefuse is configured and an unreliable send exceeds the peer's pacing budget.
	ErrCongestionBudget = errors.New("net: send budget exceeded")
)
View Source
var (
	// ErrNotHost is returned by AddPeer and RemovePeer on a peer that is not the match's host: only the host changes who takes part.
	ErrNotHost = errors.New("net: only the match's host changes its peers")
	// ErrHostLeave is returned by RemovePeer for the host itself. The host cannot leave a running match; end the match instead.
	ErrHostLeave = errors.New("net: the host cannot leave the match")
	// ErrPeerRejoin is returned by AddPeer for a peer that has left the match, however long ago: a peer that comes back joins under a new ID, as a relay or server assigns one.
	ErrPeerRejoin = errors.New("net: a peer that left cannot rejoin under the same ID")
	// ErrSessionBacklog is returned once per peer, wrapped with the peer's ID, by the next LockstepSession.SubmitInput or RollbackSession.Step or Poll after more messages wait for that remote peer than a session keeps for a peer the transport cannot reach (4096). Messages to that peer are dropped from then on, so it has missed part of the match and cannot go on in it: the host removes it, or the match ends.
	ErrSessionBacklog = errors.New("net: too many messages wait for an unreachable peer")
)
View Source
var (
	// ErrInvalidMessageID is returned when sending with MessageID 0.
	ErrInvalidMessageID = errors.New("net: invalid message ID")
	// ErrUnknownMessageID is returned by Router.Dispatch when a packet's MessageID has no registered handler or Sub view.
	ErrUnknownMessageID = errors.New("net: unknown message ID")
)
View Source
var (
	// ErrRejected matches (with errors.Is) the *RejectError a client gets when the server refuses its handshake.
	ErrRejected = errors.New("net: connection rejected")
	// ErrDisconnected is returned when sending on a client whose connection dropped, or to a server peer inside its grace period.
	ErrDisconnected = errors.New("net: peer disconnected")
	// ErrTokenTooLarge is returned when a token exceeds MaxTokenSize.
	ErrTokenTooLarge = errors.New("net: token too large")
	// ErrInvalidKey is returned when a Noise X25519 key is missing or uses another curve, or when AddPeerKey receives an all-zero key.
	ErrInvalidKey = errors.New("net: invalid key")
	// ErrSequenceExhausted is returned when a UDP session or keyed peer reaches the end of its 32-bit sequence space and cannot send without reusing an AEAD nonce. Call Reconnect (or re-register the peer with a new key) to rekey.
	ErrSequenceExhausted = errors.New("net: session sequence exhausted")
	// ErrKicked matches (with errors.Is) the *KickError a client gets when the server ends its session with WebSocketServer.Kick or UDPServer.Kick.
	ErrKicked = errors.New("net: kicked by server")
)
View Source
var (
	// ErrClosed is returned when operating on a closed transport.
	ErrClosed = errors.New("net: transport closed")
	// ErrUnknownPeer is returned when sending to a peer that is not connected.
	ErrUnknownPeer = errors.New("net: unknown peer")
	// ErrInvalidPacket is returned when a wire frame is malformed or truncated.
	ErrInvalidPacket = wsproto.ErrInvalidPacket
	// ErrPayloadTooLarge is returned when a payload exceeds transport limits.
	ErrPayloadTooLarge = wsproto.ErrPayloadTooLarge
	// ErrUnsupportedChannel is returned when a transport cannot provide the delivery guarantees the requested channel asks for.
	ErrUnsupportedChannel = errors.New("net: channel not supported by transport")
	// ErrReliableBacklog is returned when a peer has too many unacknowledged reliable segments in flight on a channel, so Send stops instead of buffering without bound.
	ErrReliableBacklog = errors.New("net: reliable backlog full")
	// ErrReceiveFailed is returned, wrapping the socket's error, by a transport whose socket failed so that it can no longer receive.
	ErrReceiveFailed = errors.New("net: receive failed")
)
View Source
var DefaultCongestionConfig = CongestionConfig{RateMin: 32 << 10, RateMax: 8 << 20, InitialRate: 256 << 10, MTU: 1200}

DefaultCongestionConfig starts at 256 KiB/s (about 2 Mbit/s), stays between 32 KiB/s and 8 MiB/s, and returns datagrams of at most 1200 bytes.

View Source
var ErrDecompressionLimit = errors.New("netplay: inflated payload exceeds cap")

ErrDecompressionLimit is returned when an inflated payload exceeds its configured maximum size.

View Source
var ErrInvalidResumeToken = errors.New("net: invalid resume token")

ErrInvalidResumeToken reports a resume token that is not one ResumeToken returned: malformed, truncated or from an incompatible build.

View Source
var ErrReconnectNil = errors.New("netplay: nil reconnect function")

ErrReconnectNil reports a supervisor run without a connection function.

View Source
var ErrRelayBacklog = errors.New("net: relay backlog full")

ErrRelayBacklog is returned by RelayTransport.Send when a peer has not acknowledged the last 1024 reliable messages sent to it, so the sender stops instead of buffering without bound.

View Source
var ErrReplicationVersion = errors.New("net: unsupported replication protocol version")

ErrReplicationVersion reports a replication message from a peer that speaks another version of the replication wire protocol than ReplicationVersion, such as a client or server built with an older release of this package. ClientWorld.Err and ServerWorld.PeerErr return it wrapped, with both versions.

View Source
var ErrRollbackStalled = fmt.Errorf("%w: waiting for remote input", ErrRollbackWindowExceeded)

ErrRollbackStalled is returned by RollbackSession.Step, which then simulates no tick, while the oldest tick still waiting for a remote peer's input is MaxRollback ticks back: simulating further would put that tick beyond the snapshots kept, where its input could no longer be rolled back to. It matches ErrRollbackWindowExceeded with errors.Is. Unlike a late input beyond the window, it is temporary: Step advances again once the input arrives or the host removes the peer. Step names each peer it waits for, as Waiting returns them; a host removes one that keeps the match stalled, since a stalled session sends that peer nothing more and so never reports it with ErrSessionBacklog.

View Source
var ErrRollbackWindowExceeded = errors.New("net: rollback window exceeded")

ErrRollbackWindowExceeded is returned when a late remote input arrives for a tick older than the retained MaxRollback snapshot window. RollbackSession.Step also returns it, as ErrRollbackStalled, while a remote peer's inputs are MaxRollback ticks behind.

View Source
var ErrWebTransportUnavailable = errors.New("net: browser WebTransport API unavailable")

ErrWebTransportUnavailable is returned by DialWebTransport in browsers that do not expose the WebTransport API.

Functions

func AppendEnvelope

func AppendEnvelope(dst []byte, id MessageID, payload []byte) []byte

AppendEnvelope appends the uvarint MessageID followed by payload to dst without allocating when dst has sufficient capacity.

func AppendRPCRequest

func AppendRPCRequest(dst []byte, method MessageID, requestID uint64, body []byte) []byte

AppendRPCRequest appends the binary RPC request payload (methodID, requestID, body) to dst without the leading KindRPCRequest router envelope.

func AppendRPCResponse

func AppendRPCResponse(dst []byte, requestID uint64, code Code, message string, body []byte) []byte

AppendRPCResponse appends the binary RPC response payload (requestID, code, length-prefixed UTF-8 message truncated to MaxStatusMessageBytes, and body) to dst without the leading KindRPCResponse router envelope.

func Call

func Call[Req any, Res any, PReq interface {
	*Req
	WireEncoder
}, PRes interface {
	*Res
	WireDecoder
}](r *Router, to PeerID, method MessageID, req PReq, opts CallOptions, done func(res PRes, err error))

Call sends a typed RPC request for method (>= 16) to peer on ChannelReliableOrdered. PReq must be a pointer to Req implementing WireEncoder, and PRes must be a pointer to Res implementing WireDecoder (such as types generated by game wire).

Call never blocks; done always runs from Router.Poll on a later tick. On success, done receives a freshly decoded *Res and a nil error. On server error, timeout, or transport failure, done receives nil and a *Status error. If the client's session resumes within the server's grace period while the call is pending, Router.Poll automatically resends the request with its original request ID.

func ChecksumBytes

func ChecksumBytes(data []byte) uint64

ChecksumBytes computes a deterministic 64-bit FNV-1a checksum over data.

Example

ChecksumBytes hashes a saved state so peers can compare their simulations cheaply.

package main

import (
	"fmt"

	"github.com/nsgo-dev/game/pkg/online/netplay"
)

func main() {
	a := netplay.ChecksumBytes([]byte("state at tick 120"))
	b := netplay.ChecksumBytes([]byte("state at tick 120"))
	c := netplay.ChecksumBytes([]byte("state at tick 121"))
	fmt.Println(a == b, a == c)
}
Output:
true false

func CompressPayload

func CompressPayload(c CompressionConfig, p []byte) ([]byte, bool, error)

CompressPayload compresses payload when it meets MinSize, returning the payload (compressed only when deflate strictly reduces its size) and whether compression was applied.

func DecompressPayload

func DecompressPayload(p []byte, max int) ([]byte, error)

DecompressPayload inflates a raw deflate payload with an output cap of max bytes (0 means unbounded). It stops reading as soon as output reaches max+1 bytes so a decompression bomb cannot allocate unbounded memory.

func EncodeCaptureRecord

func EncodeCaptureRecord(r CaptureRecord) ([]byte, error)

EncodeCaptureRecord validates and encodes one CaptureRecord as a single compact JSON line (without a trailing newline). If r.Version is 0, CaptureVersion is written automatically.

func EncodeLayoutYAML

func EncodeLayoutYAML(doc *LayoutDocument) ([]byte, error)

EncodeLayoutYAML validates doc and writes it as YAML with two-space indentation, fields in declaration order.

func EncodeReplicationYAML

func EncodeReplicationYAML(doc *ReplicationDocument) ([]byte, error)

EncodeReplicationYAML validates doc and writes deterministic two-space YAML with the schema comment header, prefabs sorted by ascending kind, and components sorted by ascending name.

func ErrInvalidEntitySpawn

func ErrInvalidEntitySpawn(reason string) error

ErrInvalidEntitySpawn returns an error describing an invalid spawn request.

func Handle

func Handle[T any, PT interface {
	*T
	WireDecoder
}](r *Router, id MessageID, fn func(from PeerID, m PT) error)

Handle registers a typed handler for application message id (>= 16) on r. PT must be a pointer to T implementing WireDecoder (such as message types generated by game wire).

The router allocates one reusable value of T at registration time and decodes each arriving packet into it before calling fn, so steady-state dispatch makes zero heap allocations. Access to the reusable value is serialized per message ID so concurrent Dispatch calls remain race-free; because the *T passed to fn is reused on the next packet of the same ID, fn must copy any slice or data it retains past its return.

Handle panics if r or fn is nil, if id is 0 or in the reserved range 1..15, or if id is already registered.

func IsOwnerUpdatePacket

func IsOwnerUpdatePacket(payload []byte) bool

IsOwnerUpdatePacket reports whether payload is a client-to-server replication owner-update message, either raw or wrapped in a Router KindReplication envelope.

func LossFraction

func LossFraction(sent, received uint64) float64

LossFraction computes packet loss from sent and received counts.

func PrefabTableHash

func PrefabTableHash(prefabs map[uint16]string) uint64

PrefabTableHash computes a deterministic 64-bit SHA-256-derived fingerprint of a kind-to-prefab-name table. Server and client compare this hash to report prefab table drift instead of spawning the wrong prefab.

func Send

func Send[T any, PT interface {
	*T
	WireEncoder
}](r *Router, to PeerID, ch Channel, id MessageID, msg PT) error

Send frames and transmits msg with envelope id to peer on channel ch through r. Steady-state sends reuse the router's internal framing buffer and make zero heap allocations on the framing path.

func Serve

func Serve[Req any, Res any, PReq interface {
	*Req
	WireDecoder
}, PRes interface {
	*Res
	WireEncoder
}](r *Router, method MessageID, fn func(from PeerID, req PReq) (PRes, error))

Serve registers a typed request/response RPC handler for method (>= 16) on r. PReq must be a pointer to Req implementing WireDecoder, and PRes must be a pointer to Res implementing WireEncoder (such as types generated by game wire).

The handler runs from Router.Poll on the match tick. Access to the reusable decoded request value is serialized per method ID so concurrent Dispatch calls remain race-free; fn must copy any request slice it retains past its return.

Returning a *Status sends its Code and Message to the caller; any other non-nil error maps to CodeInternal with an empty message so server internals never leak. Results are cached per peer by request ID so retries after resume return the cached response without executing fn again.

Serve panics if r or fn is nil, if method is 0 or <= ReservedMessageIDMax, or if method is already registered for RPC on r.

func SplitDatagram

func SplitDatagram(datagram []byte) ([][]byte, error)

SplitDatagram returns the messages of a datagram Poll produced, as subslices of datagram. It returns ErrMalformedDatagram for an empty datagram, an empty message, or a length prefix that runs past the end.

func WebTransportSupported

func WebTransportSupported() bool

WebTransportSupported reports whether WebTransport is available in the current runtime. On native targets it always returns true.

Types

type AckHeader

type AckHeader struct {
	Next uint32
	Mask uint64
}

AckHeader carries the next reliable sequence the receiver is missing and a selective mask of later arrivals: bit i set means sequence Next+1+i arrived.

func DecodeAckHeader

func DecodeAckHeader(src []byte) (AckHeader, bool)

DecodeAckHeader reads an AckHeader from the first AckHeaderSize bytes of src and reports whether src was long enough.

func (AckHeader) Encode

func (h AckHeader) Encode(dst []byte) bool

Encode writes h into the first AckHeaderSize bytes of dst and reports whether dst was long enough.

type AckTracker

type AckTracker struct {
	// contains filtered or unexported fields
}

AckTracker tracks received reliable sequence numbers, starting at 0, and produces a compact piggyback header. Sequences do not wrap: a transport using it must end the session before sequence 2^32. Arrivals more than 64 past Next are not recorded; the sender retransmits them.

func (AckTracker) Header

func (a AckTracker) Header() AckHeader

Header returns the acknowledgement state to piggyback on the next outgoing datagram.

func (*AckTracker) Receive

func (a *AckTracker) Receive(seq uint32)

Receive records the arrival of seq. Duplicates and sequences before Next are ignored.

type Auth

type Auth struct {
	// Verify checks the credential a client presented and the ID the server is about to assign it. A non-nil error rejects the client: it never reaches Recv, Peers or NextEvent, and the error's text is sent back as the reason. Nil accepts every client. VerifyHello takes precedence when both are set. Setting Verify alongside Identify is an error.
	//
	// The WebSocket server calls Verify on the client's own goroutine. The UDP server calls it on its receive goroutine, so a slow Verify delays every UDP peer's packets; check a signed token locally rather than calling a remote service there. The UDP server runs it only for a client that echoed the cookie sent to its address, so datagrams with spoofed source addresses never reach it.
	Verify func(peer PeerID, token []byte) error
	// VerifyHello is Verify with the client's build string, so a server can refuse an outdated build or answer with a code. It runs wherever Verify does. Return a *RejectError to choose the code and retry hint the client sees; any other error is reported as RejectInvalidToken. Setting VerifyHello alongside Identify is an error.
	VerifyHello func(Hello) error
	// Identify checks the credential a client presented and returns the account it stands for; "" means anonymous (never deduplicated). It runs off-lock wherever Verify does. Return a *RejectError to choose the reject code and retry hint; any other error is reported as RejectInvalidToken. Setting Identify alongside Verify or VerifyHello makes the server constructor return an error.
	Identify func(peer PeerID, token []byte) (account string, err error)
	// DuplicateLogin decides what happens when Identify returns an account that already has a session, connected or inside its grace period: ReplaceOld (default) or RejectNew. A resume with a valid secret is the same session, never a duplicate.
	DuplicateLogin DuplicatePolicy
	// MinClientVersion is the oldest client build the server admits, as dotted numbers such as "1.4.0": a hello that reports a lower version, or one with no parsable version, is refused with RejectUpdateRequired. A MinClientVersion that is not dotted numbers leaves the gate off rather than refusing every client.
	MinClientVersion string
	// GracePeriod is how long a dropped peer keeps its ID and session. A client that reconnects within it resumes with the same ID and NextEvent reports PeerResumed; once it passes, NextEvent reports PeerLeft. Zero reports PeerLeft as soon as the connection drops.
	GracePeriod time.Duration
	// MaxGracePeriod caps what ExtendGrace grants one peer; zero means no cap. It applies only to ExtendGrace, so a value below GracePeriod leaves every peer the default and makes extensions a no-op rather than shortening their window.
	MaxGracePeriod time.Duration
	// IdleTimeout is how long a peer may stay silent before the server counts it as dropped; 10 seconds when zero, and a value below 3 seconds is raised to 3 seconds. UDP clients ping every second while idle, so a gap of up to 2 seconds is normal. A WebSocket server pings each client every third of IdleTimeout and drops one that sends no frame, not even the pong, for IdleTimeout, so a client whose network vanished without closing the TCP connection does not keep its session forever. The WebSocket timeout runs on the wall clock, not on Now.
	IdleTimeout time.Duration
	// MaxPeers is the most sessions the server holds at once, counting peers inside their grace period and handshakes waiting on Verify; 1024 when zero. A client past it is rejected with the reason "server full", so a flood of handshakes cannot grow the server without bound.
	MaxPeers int
	// Now is the clock for grace periods and idle timeouts; nil uses time.Now.
	Now func() time.Time
	// StaticKey is the server's static X25519 private key for ListenUDPServer's Noise NK handshake. When nil, ListenUDPServer generates a fresh X25519 key pair (available via UDPServer.PublicKey); set a persistent key when clients know it from configuration rather than a matchmaking ticket, or must reconnect across server restarts. A non-X25519 key makes ListenUDPServer return ErrInvalidKey. Ignored by WebSocket servers, which use TLS.
	StaticKey *ecdh.PrivateKey
	// Channels declares extra independent reliable ordered lanes and below-MTU fragmentation limits for the server transport. Zero uses the defaults (no extra lanes, 1200-byte MTU, 1 MiB per-peer reassembly cap).
	Channels ChannelConfig
	// Compression configures optional payload compression for the server transport: RFC 7692 permessage-deflate negotiation on WebSocketServer, and opt-in per-packet deflate compression on UDPServer. Off by default (Enabled: false); UDPServer still inflates compressed packets from peers that enable compression.
	Compression CompressionConfig
	// Congestion configures per-peer send-rate control, pacing, coalescing, and over-budget unreliable policy on UDPServer. Zero uses DefaultCongestionConfig (with MTU defaulting to Channels.mtu()).
	Congestion CongestionConfig
}

Auth configures the connection handshake that ListenWebSocket, ListenWebTransport, and ListenUDPServer run before a peer may send or receive game packets.

The zero value accepts every client, assigns its ID and treats a dropped connection as a leave. A server reachable from the internet should set Verify, VerifyHello or Identify: without one anyone may join, up to MaxPeers.

type Authority

type Authority struct {
	Peer   uint64
	Server bool
}

Authority identifies the peer allowed to publish client-owned state.

func PeerAuthority

func PeerAuthority(peer uint64) Authority

PeerAuthority returns authority owned by peer.

func ServerAuthority

func ServerAuthority() Authority

ServerAuthority returns authority owned by the server.

func (Authority) Allows

func (a Authority) Allows(peer uint64) bool

Allows reports whether peer may publish state under a.

type CallOptions

type CallOptions struct {
	// Timeout bounds how long Call waits for a response on the Router's clock.
	// Zero uses DefaultRPCTimeout (5s); a negative value disables the deadline.
	Timeout time.Duration
}

CallOptions configures one outgoing RPC call.

type CaptureDirection

type CaptureDirection string

CaptureDirection identifies whether a captured packet was sent or received by the wrapped Transport.

const (
	// CaptureSend marks a packet passed to Transport.Send.
	CaptureSend CaptureDirection = "send"
	// CaptureRecv marks a packet returned by Transport.Recv.
	CaptureRecv CaptureDirection = "recv"
)

type CaptureOptions

type CaptureOptions struct {
	// Channels, when non-empty, restricts capture to packets on one of the listed channels.
	Channels []Channel
	// Peers, when non-empty, restricts capture to packets sent to or received from one of the listed peers.
	Peers []PeerID
	// SampleEvery records one out of every N matching packets (0 or 1 records every matching packet).
	SampleEvery int
	// SampleRate, when in (0, 1) and SampleEvery <= 1, probabilistically records each matching packet using SampleSeed.
	SampleRate float64
	// SampleSeed seeds the deterministic PRNG used with SampleRate.
	SampleSeed int64
	// Now returns the clock used to stamp elapsed nanoseconds T since NewCaptureTransport was called; time.Now when nil.
	Now func() time.Time
	// OnError, when non-nil, is called if encoding or writing a capture line fails. Capture write errors never fail Send or Recv.
	OnError func(error)
}

CaptureOptions configures filtering, sampling, timing, and error reporting for NewCaptureTransport.

type CaptureRecord

type CaptureRecord struct {
	// Version is the capture format version; it must equal CaptureVersion (1).
	Version int `json:"version"`
	// T is the monotonic elapsed time in nanoseconds since NewCaptureTransport started capturing.
	T int64 `json:"t"`
	// Dir is "send" for outbound Transport.Send calls or "recv" for inbound Transport.Recv packets.
	Dir CaptureDirection `json:"dir"`
	// Peer is the destination peer ID (or PeerBroadcast) on send, or Packet.From on recv.
	Peer PeerID `json:"peer"`
	// Ch is the transport delivery channel (ChannelReliableOrdered or ChannelUnreliable).
	Ch Channel `json:"ch"`
	// Seq is the transport packet sequence number.
	Seq uint32 `json:"seq"`
	// Payload is the raw plaintext transport payload bytes, encoded as standard base64 in JSON.
	Payload []byte `json:"payload"`
}

CaptureRecord is one line of a version 1 packet capture JSONL stream.

Each line is a self-contained UTF-8 JSON object:

{"version":1,"t":0,"dir":"send","peer":2,"ch":0,"seq":1,"payload":"AQID"}

Warning: captured payloads contain plaintext player inputs, entity coordinates, and game state. Treat capture files like player telemetry and never ship or publish them without consent.

func ParseCaptureRecord

func ParseCaptureRecord(line []byte) (CaptureRecord, error)

ParseCaptureRecord strictly decodes and validates one JSON line into a CaptureRecord, refusing unknown fields, trailing data, missing or unsupported versions, invalid directions or channels, negative timestamps, and missing or null payloads.

func ReadCapture

func ReadCapture(r io.Reader) ([]CaptureRecord, error)

ReadCapture reads every non-empty JSONL line from r and returns the parsed CaptureRecords in order.

type Channel

type Channel uint8

Channel selects delivery semantics for a packet.

func ReliableLane

func ReliableLane(index int) Channel

ReliableLane returns the Channel for the zero-based extra reliable ordered lane index (FirstReliableLane + index). Callers declare how many extra lanes a transport accepts with ChannelConfig{Lanes: n}.

func (Channel) String

func (c Channel) String() string

String returns a human-readable channel name.

type ChannelConfig

type ChannelConfig struct {
	// Lanes is the number of extra independent reliable ordered channels beyond ChannelReliableOrdered (0), numbered FirstReliableLane (3) through FirstReliableLane+Channel(Lanes-1) up to MaxReliableLanes (64). Each lane orders and retransmits independently so a burst or lost packet on one lane never delays another.
	Lanes int
	// MTU is the maximum UDP datagram size in bytes (including the 26-byte AEAD header and tag) before UDPServer and UDPClient fragment payloads. Zero uses DefaultMTU (1200); values below MinMTU (256) are raised to MinMTU.
	MTU int
	// MaxReassemblyBytes caps the total payload bytes held in incomplete fragmented messages from one peer. Zero uses DefaultMaxReassemblyBytes (1 MiB); a negative value removes the cap.
	MaxReassemblyBytes int
}

ChannelConfig declares extra independent reliable ordered lanes and below-MTU fragmentation limits for a transport.

type ClientWorld

type ClientWorld struct {

	// OnSpawn is invoked when a new entity first appears in an authoritative snapshot.
	OnSpawn func(EntityState)
	// OnDespawn is invoked when an entity disappears from an authoritative snapshot.
	OnDespawn func(EntityID)
	// OnOwnerChanged is invoked when an existing entity's Owner changes between
	// authoritative snapshots, in deterministic EntityID order.
	OnOwnerChanged func(id EntityID, prev, next PeerID)
	// contains filtered or unexported fields
}

ClientWorld receives authoritative snapshots from a ServerWorld, maintains a timed snapshot ring buffer for smooth interpolation, fires spawn/despawn hooks, and supports client-side prediction with automatic server reconciliation.

A ClientWorld follows the server's replication epoch. A complete full snapshot of a new epoch means the server restarted: the client forgets every snapshot and prediction of the old epoch as Reset does, reporting each entity it knew through OnDespawn, and continues from the new one without the game calling Reset. A delta of a new epoch only makes the client ask for a full snapshot of it. Late snapshots of an epoch the client has left are ignored, unless that epoch sends 32 snapshots in a row with none of the current epoch between them: then it is the live one, and the client follows it again.

func NewClientWorld

func NewClientWorld(transport Transport, serverID PeerID) *ClientWorld

NewClientWorld creates a replication client connected to serverID via transport.

func (*ClientWorld) Entity

func (c *ClientWorld) Entity(id EntityID) (EntityState, bool)

Entity returns the latest state of id: for an entity this client owns and has published locally, it returns the locally authored state merged with any server updates or corrections; otherwise it returns the latest authoritative snapshot state.

func (*ClientWorld) Epoch

func (c *ClientWorld) Epoch() (uint32, bool)

Epoch returns the server's replication epoch the client's snapshots belong to, and false before the first snapshot and after Reset.

func (*ClientWorld) Err

func (c *ClientWorld) Err() error

Err returns why the server's last replication message could not be used, an error wrapping ErrReplicationVersion when the server speaks another version of the replication protocol, or nil. A game can show it and stop waiting for a world that will never arrive. It clears when a snapshot applies and on Reset.

func (*ClientWorld) Interpolate

func (c *ClientWorld) Interpolate(renderTick float64) []EntityState

Interpolate returns a sorted slice of entities interpolated at renderTick across the buffered authoritative snapshots (smoothly lerping X, Y, VX, VY, and shortest-arc Rotation).

renderTick is read relative to the latest snapshot's tick, modulo 2^32, so a render time computed from uint32 ticks keeps working across a tick counter wraparound.

func (*ClientWorld) LastReconcileError

func (c *ClientWorld) LastReconcileError() float32

LastReconcileError returns the Euclidean position delta between the predicted state and reconciled state from the most recent reconciliation.

func (*ClientWorld) LatestTick

func (c *ClientWorld) LatestTick() (uint32, bool)

LatestTick returns the highest authoritative snapshot tick received so far.

func (*ClientWorld) Owns

func (c *ClientWorld) Owns(id EntityID) bool

Owns reports whether this client is the current authoritative owner of id.

func (*ClientWorld) PendingPredictions

func (c *ClientWorld) PendingPredictions(id EntityID) int

PendingPredictions returns the number of unacknowledged predicted inputs buffered for id.

func (*ClientWorld) Poll

func (c *ClientWorld) Poll() int

Poll drains all pending snapshots from Transport, updates the ring buffer, triggers OnSpawn/OnOwnerChanged/OnDespawn callbacks, sends acknowledgments back to the server, and reconciles locally predicted entities. Returns the number of snapshots applied.

A complete full snapshot of a new epoch makes the client follow the server into it, reporting every entity of the old epoch through OnDespawn first; a delta of a new epoch makes it ask the server for a full snapshot. Snapshots of epochs the client has left are ignored, as described on ClientWorld. A message of another version of the replication protocol sets Err, and the next snapshot that applies clears it.

func (*ClientWorld) Predict

func (c *ClientWorld) Predict(localEntity EntityID, input any, apply func(*EntityState, any))

Predict applies a local input immediately to localEntity and buffers it for reconciliation when authoritative snapshots arrive.

Example

ClientWorld.Predict moves the local player at once and keeps the input until the server's snapshot of that tick arrives, then replays the inputs the server has not seen yet on top of it.

package main

import (
	"fmt"
	"time"

	"github.com/nsgo-dev/game/pkg/online/netplay"
)

func main() {
	hub := netplay.NewLoopbackHub(netplay.LoopbackConfig{Latency: 16 * time.Millisecond})
	srv := netplay.NewServerWorld(hub.AddPeer(1))
	cli := netplay.NewClientWorld(hub.AddPeer(2), 1)
	player := srv.Spawn(netplay.EntityState{})
	_ = srv.Step(1)
	hub.Advance(16 * time.Millisecond)
	cli.Poll()

	move := func(st *netplay.EntityState, in any) { st.X += in.(float32) }
	for range 3 {
		cli.Predict(player, float32(5), move)
	}
	p, _ := cli.PredictedState(player)
	fmt.Println("predicted x", p.X, "pending", cli.PendingPredictions(player))
}
Output:
predicted x 15 pending 3

func (*ClientWorld) PredictedState

func (c *ClientWorld) PredictedState(id EntityID) (EntityState, bool)

PredictedState returns the locally predicted state for id if active, falling back to the latest authoritative state.

func (*ClientWorld) Publish

func (c *ClientWorld) Publish(id EntityID, localState EntityState) bool

Publish sends localState for a client-owned entity to the server on ChannelUnreliable with the client's latest acknowledged tick and a monotonic sequence number (newest wins on the server). Returns false without sending if this client does not currently own id, has not received a snapshot yet, or the transport send fails.

func (*ClientWorld) Reconciliations

func (c *ClientWorld) Reconciliations() int

Reconciliations returns the total number of client-side prediction reconciliations performed.

func (*ClientWorld) RenderTick

func (c *ClientWorld) RenderTick(opts RenderTickOptions) float64

RenderTick returns a render tick for ClientWorld.Interpolate whose interpolation delay behind the snapshot stream adapts to measured arrival jitter and transport RTT variance, clamped between opts.MinDelay and opts.MaxDelay ticks. It returns 0 before the first snapshot arrives or after Reset.

func (*ClientWorld) Reset

func (c *ClientWorld) Reset()

Reset forgets every snapshot, partial snapshot and prediction and the server's epoch, as when the client joins a new match, and reports every entity the client knew through OnDespawn, in EntityID order. A restarted ServerWorld sends a new epoch, which the client follows without a Reset; a server that starts its tick count over in the same epoch, without SetEpoch, needs one, because snapshot ticks are compared in serial-number order and the client would drop every new snapshot as stale until the new ticks pass the old ones. The epochs the client has left stay ignored, as long as they send no more than a late burst. Reconciliations and LastReconcileError keep counting.

func (*ClientWorld) ServerTick

func (c *ClientWorld) ServerTick() float64

ServerTick estimates the server's current simulation tick from snapshot arrival times and transport RTT. It returns 0 before the first snapshot arrives or after Reset.

func (*ClientWorld) SetClock

func (c *ClientWorld) SetClock(now func() time.Time)

SetClock sets the clock used by ServerTick and RenderTick. Passing nil restores the transport's default clock (LoopbackHub.Now for LoopbackTransport, time.Now otherwise).

func (*ClientWorld) SetLayouts

func (c *ClientWorld) SetLayouts(doc *LayoutDocument) error

SetLayouts attaches a validated LayoutDocument so ClientWorld knows which ComponentState fields are client-owned when merging local published state with incoming server deltas. Passing nil clears the layouts.

func (*ClientWorld) SetTickRate

func (c *ClientWorld) SetTickRate(hz float64)

SetTickRate configures the expected server simulation tick rate in Hz used by ServerTick and RenderTick. Values <= 0, NaN, or Inf clear the fixed rate and return to estimating the rate from snapshot arrival intervals (defaulting to 60 Hz before enough snapshots arrive).

type Code

type Code uint16

Code identifies the outcome of a request/response RPC call. Built-in status codes occupy 0..999; games define application-specific codes starting at CodeCustomMin (1000).

const (
	// CodeOK indicates the RPC completed successfully.
	CodeOK Code = 0
	// CodeInvalidArgument indicates the caller passed invalid parameters or a malformed request payload.
	CodeInvalidArgument Code = 1
	// CodeNotFound indicates the requested method or resource was not found.
	CodeNotFound Code = 2
	// CodePermissionDenied indicates the caller does not have permission for the operation.
	CodePermissionDenied Code = 3
	// CodeRateLimited indicates the caller exceeded a rate limit and should back off.
	CodeRateLimited Code = 4
	// CodeUnavailable indicates the target peer, service, or session is currently unavailable.
	CodeUnavailable Code = 5
	// CodeDeadlineExceeded indicates the RPC deadline expired before a response arrived.
	CodeDeadlineExceeded Code = 6
	// CodeInternal indicates an unexpected server-side failure; internal details are never sent to the client.
	CodeInternal Code = 7

	// CodeCustomMin is the smallest status code reserved for game-specific RPC error codes.
	CodeCustomMin Code = 1000
)

func DecodeRPCResponse

func DecodeRPCResponse(src []byte) (requestID uint64, code Code, message string, body []byte, err error)

DecodeRPCResponse parses an RPC response payload (after stripping KindRPCResponse) and returns the request ID, status code, message, and a zero-copy view of body. It returns ErrInvalidPacket if any varint is invalid, requestID is 0, code exceeds uint16, or message length exceeds MaxStatusMessageBytes or the remaining payload.

func StatusCode

func StatusCode(err error) Code

StatusCode returns the RPC status code for err: CodeOK when err is nil, st.Code when err matches *Status via errors.As, and CodeInternal otherwise.

func (Code) String

func (c Code) String() string

String returns the status code's human-readable name.

type ComponentState

type ComponentState struct {
	Kind     uint16
	X        float32
	Y        float32
	VX       float32
	VY       float32
	Rotation float32
	Flags    uint32
	Props    []byte
}

ComponentState holds the replicated transform, velocity, flags, and custom properties of an entity.

func (ComponentState) Clone

func (c ComponentState) Clone() ComponentState

Clone returns a deep copy of ComponentState (duplicating Props).

type CompressionConfig

type CompressionConfig struct {
	// Enabled turns on outgoing compression on transports and RFC 7692 permessage-deflate negotiation on WebSocket transports.
	Enabled bool
	// MinSize is the smallest payload in bytes eligible for compression. On transports, zero defaults to DefaultCompressionMinSize (256) when Enabled is true.
	MinSize int
	// MaxInflated caps the uncompressed size in bytes accepted by a decoder to defend against decompression bombs. Zero uses the transport's own payload ceiling.
	MaxInflated int
	// Level is the compress/flate level from 1 (BestSpeed) to 9 (BestCompression); zero uses flate.DefaultCompression.
	Level int
}

CompressionConfig controls optional payload deflate compression.

On transports (Auth.Compression, DialOptions.Compression, RelayTransportConfig.Compression, and SetCompression), compression is opt-in: the zero value leaves outgoing compression disabled while UDP and relay receivers still inflate compressed packets sent by peers. Setting Enabled to true compresses outgoing messages of at least MinSize bytes (DefaultCompressionMinSize when zero) whenever deflate strictly reduces their size, and enables RFC 7692 permessage-deflate negotiation on WebSocket transports.

func (CompressionConfig) Validate

func (c CompressionConfig) Validate() error

Validate reports an error unless MinSize and MaxInflated are non-negative and Level is a deflate level from 0 to 9.

type CongestionConfig

type CongestionConfig struct {
	RateMin          int64
	RateMax          int64
	InitialRate      int64
	MTU              int
	UnreliablePolicy UnreliablePolicy
	// MaxUnreliableQueueBytes caps queued unreliable payload bytes per peer before UnreliablePolicy drops or refuses excess sends. Zero uses max(8*MTU, rate/10).
	MaxUnreliableQueueBytes int
}

CongestionConfig bounds a deterministic byte-rate controller. Rates are in bytes per second; MTU is the largest datagram Poll returns, framing included. A zero field takes its value from DefaultCongestionConfig.

type ConnState

type ConnState uint8

ConnState is a client transport's connection state.

const (
	// ConnConnecting is a client whose handshake has not finished.
	ConnConnecting ConnState = iota
	// ConnOpen is a client the server accepted.
	ConnOpen
	// ConnDisconnected is a client whose connection dropped or was rejected; Reconnect may resume it.
	ConnDisconnected
	// ConnClosed is a client closed with Close.
	ConnClosed
)

func (ConnState) String

func (s ConnState) String() string

String returns the state's name.

type DesyncEvent

type DesyncEvent struct {
	Tick           uint32
	LocalPeer      PeerID
	RemotePeer     PeerID
	LocalChecksum  uint64
	RemoteChecksum uint64
}

DesyncEvent describes a detected state checksum divergence between peers.

type DialOptions

type DialOptions struct {
	// Token is the credential Auth.Verify or Auth.VerifyHello checks.
	Token []byte
	// ClientVersion is the client's build, such as "1.4.2"; the server's Auth.MinClientVersion refuses an older one with RejectUpdateRequired and Auth.VerifyHello sees it.
	ClientVersion string
	// Resume is a ResumeToken from an earlier session, so a dial within the server's grace period resumes it instead of joining again. A malformed token returns ErrInvalidResumeToken without dialing.
	Resume string
	// Channels declares extra independent reliable ordered lanes and below-MTU fragmentation limits for the client transport. Zero uses the defaults (no extra lanes, 1200-byte MTU, 1 MiB per-peer reassembly cap).
	Channels ChannelConfig
	// Compression configures optional payload compression for the client transport: RFC 7692 permessage-deflate negotiation on native WebSocketTransport, and opt-in per-packet deflate compression on UDPClient. Off by default (Enabled: false); UDPClient still inflates compressed packets from servers that enable compression.
	Compression CompressionConfig
	// Congestion configures per-peer send-rate control, pacing, coalescing, and over-budget unreliable policy on UDPClient. Zero uses DefaultCongestionConfig (with MTU defaulting to Channels.mtu()).
	Congestion CongestionConfig
}

DialOptions is what a client presents in the connection handshake: its credential, the build string the server may gate on, an optional resume token, channel configuration, and optional compression configuration.

type DuplicatePolicy

type DuplicatePolicy uint8

DuplicatePolicy decides what a server transport does when Auth.Identify returns an account that already has a live session, connected or inside its grace period.

const (
	// ReplaceOld (the default) ends the existing session as a kick with reason "replaced" before admitting the new handshake, discarding its resume secret so it cannot come back.
	ReplaceOld DuplicatePolicy = iota
	// RejectNew refuses the new handshake with RejectAlreadySignedIn while leaving the existing session untouched.
	RejectNew
)

func (DuplicatePolicy) String

func (p DuplicatePolicy) String() string

String returns the policy's name.

type EntityID

type EntityID uint32

EntityID uniquely identifies a replicated entity in a ServerWorld / ClientWorld.

type EntityLayout

type EntityLayout struct {
	Kind   uint32        `yaml:"kind"`
	Name   string        `yaml:"name"`
	Fields []LayoutField `yaml:"fields"`
}

EntityLayout is the replicated fields of one kind of entity, by its non-zero kind number and its name.

func (EntityLayout) ClientOwnedFields

func (l EntityLayout) ClientOwnedFields() []string

ClientOwnedFields returns the names of fields marked owner: client in declaration order.

type EntitySpawn

type EntitySpawn struct {
	ID         uint64
	Kind       string
	Components map[string][]byte
}

EntitySpawn describes a replicated prefab spawn request. Kind selects a registered prefab and Components carries its initial component payloads.

func (EntitySpawn) Validate

func (s EntitySpawn) Validate(registered map[string]bool) error

Validate checks that the spawn has a stable ID and registered kind.

type EntityState

type EntityState struct {
	ID    EntityID
	Owner PeerID
	ComponentState
}

EntityState pairs an EntityID with its owner and replicated ComponentState. Owner is 0 (PeerBroadcast) when owned by the server, or a client PeerID when client-owned.

func (EntityState) Clone

func (e EntityState) Clone() EntityState

Clone returns a deep copy of EntityState.

type FieldLayout

type FieldLayout = LayoutField

FieldLayout is the public name used by generated layout metadata.

type FieldOwner

type FieldOwner = LayoutFieldOwner

FieldOwner is the short public name used by layout metadata.

type GridInterest

type GridInterest struct {
	CellSize float32
	Radius   int
	Focus    func(peer PeerID) (x, y float32, ok bool)
	Always   func(e EntityState) bool
	// contains filtered or unexported fields
}

GridInterest is a ready-made spatial interest filter backed by a uniform grid over EntityState.X and EntityState.Y. A peer sees entities within Radius grid cells of its Focus position (Chebyshev distance <= Radius, a (2*Radius+1)×(2*Radius+1) square of cells), plus any entity matched by Always.

Pass a *GridInterest to ServerWorld.SetInterestProvider to bucket entities once per Step in O(entities) time and query only nearby cells per peer. Visible is read-only and safe for concurrent calls; Prepare and Query reuse internal buffers, so a *GridInterest attached via SetInterestProvider must not be stepped concurrently across multiple ServerWorlds. Visible can also be used directly or composed inside ServerWorld.SetInterest.

func (*GridInterest) Prepare

func (g *GridInterest) Prepare(entities []EntityState)

Prepare buckets entities into uniform grid cells once per Step, reusing internal buffers across ticks to avoid steady-state allocations.

func (*GridInterest) Query

func (g *GridInterest) Query(peer PeerID, dst []EntityID) []EntityID

Query appends the EntityIDs visible to peer from the most recent Prepare call to dst and returns the extended slice. Always entities are included once and never duplicated with spatial cells.

func (*GridInterest) Visible

func (g *GridInterest) Visible(peer PeerID, e EntityState) bool

Visible reports whether e is visible to peer under g's grid settings. Entities matched by Always are visible regardless of Focus, Radius, or CellSize. If Focus is nil or returns ok == false, if CellSize is not finite and positive, if Radius is negative, or if either the focus or entity coordinates cannot be mapped to a finite grid cell, only Always entities are visible.

type Handler

type Handler func(id MessageID, pkt Packet) error

Handler processes one routed packet whose leading uvarint MessageID has been stripped from pkt.Payload.

type Hello

type Hello struct {
	Peer          PeerID
	Token         []byte
	ClientVersion string
}

Hello is the client's handshake as Auth.VerifyHello sees it: the ID the server is about to assign, the credential it presented and the build string it reported.

type InboxLimits

type InboxLimits struct {
	// Unreliable is the most ChannelUnreliable packets the inbox holds from one peer. Zero uses DefaultUnreliableInbox; a negative value removes the cap.
	Unreliable int
	// Reliable is the most ChannelReliableOrdered packets a WebSocketServer's or RelayTransport's inbox holds from one peer. Zero uses DefaultReliableInbox; a negative value removes the cap. The other transports ignore it.
	Reliable int
	// ReliableWarning is the ChannelReliableOrdered backlog, across all peers, that raises a warning: the warning counts once when the backlog grows past it, and counts again only after the backlog has fallen to half of it, so a queue hovering at the threshold does not raise one warning per packet. Zero uses DefaultReliableInboxWarning; a negative value turns the warning off.
	ReliableWarning int
}

InboxLimits bounds the packets a transport keeps until Recv takes them. Every transport in this package accepts it through SetInboxLimits, and LoopbackConfig and RelayTransportConfig carry it too.

The unreliable channel is capped per peer: when a ChannelUnreliable packet arrives from a peer that already has Unreliable packets queued, that peer's oldest queued unreliable packet is dropped to make room, so a consumer that falls behind keeps the newest state rather than the stalest, a peer that floods the inbox evicts only its own packets, and InboxStats.UnreliableDropped counts the loss.

The reliable channel is never trimmed, because dropping a packet would break ChannelReliableOrdered. A transport that receives reliable packets from peers it cannot trust caps them per peer at Reliable instead and refuses the packet that goes past it, counting it in InboxStats.ReliableRefused: WebSocketServer then ends that client's session, as if it had left, so the packets it did deliver stay in order, and RelayTransport leaves the message unacknowledged, so the sending peer resends it once Recv has made room. The other transports receive reliable packets only from their server or from the same process and keep them all. Every transport counts a warning in InboxStats.ReliableWarnings when its whole reliable backlog passes ReliableWarning.

type InboxReporter

type InboxReporter interface {
	SetInboxLimits(InboxLimits)
	InboxStats() InboxStats
}

InboxReporter is implemented by every transport in this package: LoopbackTransport, WebSocketTransport, WebSocketServer, WebTransportTransport, WebTransportServer, UDPTransport, UDPServer, UDPClient and RelayTransport. SetInboxLimits changes the inbox's limits at any time; lowering the unreliable cap below what a peer has queued drops that peer's oldest unreliable packets at once and counts them, and lowering the reliable cap refuses only the packets that arrive afterwards. InboxStats reads the inbox's counters.

type InboxStats

type InboxStats struct {
	// Unreliable is the number of ChannelUnreliable packets waiting for Recv.
	Unreliable int
	// Reliable is the number of ChannelReliableOrdered packets waiting for Recv.
	Reliable int
	// UnreliableDropped counts the unreliable packets dropped because their peer already had InboxLimits.Unreliable packets queued when a newer one arrived.
	UnreliableDropped uint64
	// ReliableRefused counts the reliable packets a WebSocketServer or RelayTransport refused because their peer already had InboxLimits.Reliable packets queued.
	ReliableRefused uint64
	// ReliableWarnings counts the times the reliable backlog grew past InboxLimits.ReliableWarning: once per crossing, not once per packet.
	ReliableWarnings uint64
	// ReliableBacklog is true from the moment the reliable backlog passes InboxLimits.ReliableWarning until it falls to half of it.
	ReliableBacklog bool
	// DecompressionRefused counts incoming compressed packets or WebSocket messages dropped because their deflate stream was malformed or their inflated size exceeded the configured decompression cap.
	DecompressionRefused uint64
}

InboxStats reports a transport's inbox: what is queued and what the limits did. The counters only grow, so a game or a debug overlay that polls InboxStats every frame reports a warning or a loss when a counter differs from the previous frame's.

Example

An inbox caps each peer's unreliable packets and keeps the newest when a game falls behind; reliable packets are never dropped, and a backlog past the warning threshold is counted once.

package main

import (
	"fmt"

	"github.com/nsgo-dev/game/pkg/online/netplay"
)

func main() {
	hub := netplay.NewLoopbackHub(netplay.LoopbackConfig{Inbox: netplay.InboxLimits{Unreliable: 2, ReliableWarning: 3}})
	server := hub.AddPeer(1)
	client := hub.AddPeer(2)

	for _, pos := range []string{"x=1", "x=2", "x=3"} {
		server.Send(2, netplay.ChannelUnreliable, []byte(pos))
	}
	for range 5 {
		server.Send(2, netplay.ChannelReliableOrdered, []byte("event"))
	}
	st := client.InboxStats()
	fmt.Println("queued:", st.Unreliable, st.Reliable, "dropped:", st.UnreliableDropped, "warnings:", st.ReliableWarnings)
	p, _ := client.Recv()
	fmt.Println("oldest kept:", string(p.Payload))
}
Output:
queued: 2 5 dropped: 1 warnings: 1
oldest kept: x=2

type InputFrame

type InputFrame struct {
	Tick uint32
	Peer PeerID
	Bits uint64
	Axes [2]int16
}

InputFrame is a deterministic per-tick player input sample.

type InterestProvider

type InterestProvider interface {
	// Prepare indexes the authoritative entities for the current Step.
	// Implementations must treat entities and each EntityState.Props slice as
	// read-only and must not retain entities past Prepare.
	Prepare(entities []EntityState)
	// Query appends the EntityIDs visible to peer from the most recent Prepare
	// call to dst and returns the extended slice.
	Query(peer PeerID, dst []EntityID) []EntityID
}

InterestProvider indexes authoritative entities once per ServerWorld.Step and queries the visible entity IDs for each peer, avoiding an O(peers × entities) scan when spatial partitioning is used. *GridInterest implements InterestProvider.

type InterpolationMode

type InterpolationMode = LayoutInterpolation

InterpolationMode is the short public name used by generated layout metadata.

type KickError

type KickError struct {
	Reason string
}

KickError is the reason a server gave for removing a client's session with WebSocketServer.Kick or UDPServer.Kick.

func (*KickError) Error

func (e *KickError) Error() string

Error returns the kick with its reason.

func (*KickError) Is

func (e *KickError) Is(target error) bool

Is reports whether target is ErrKicked.

type LayoutDocument

type LayoutDocument struct {
	Version int            `yaml:"version"`
	Layouts []EntityLayout `yaml:"layouts"`
}

LayoutDocument is an entity layout file: the layouts of a game's replicated entity kinds, at version LayoutVersion.

func ParseLayoutYAML

func ParseLayoutYAML(data []byte) (*LayoutDocument, error)

ParseLayoutYAML reads a layout document from YAML, refusing unknown fields and a second document, and validates it. Its errors are *loaderr.Error values with the line and field at fault.

func (*LayoutDocument) Layout

func (d *LayoutDocument) Layout(kind uint32) (EntityLayout, bool)

Layout returns the layout of entity kind, and false when the document has none.

func (*LayoutDocument) Validate

func (d *LayoutDocument) Validate() error

Validate reports an error unless the version is LayoutVersion and every layout has a unique non-zero kind and name and fields with unique names, a type, quantization bits from 1 to 32, and a known sync mode and interpolation. Its errors are *loaderr.Error values naming the field at fault.

type LayoutField

type LayoutField struct {
	Name        string              `yaml:"name"`
	Type        string              `yaml:"type"`
	Quant       *LayoutQuantization `yaml:"quant,omitempty"`
	Sync        LayoutSyncMode      `yaml:"sync,omitempty"`
	Interpolate LayoutInterpolation `yaml:"interpolate,omitempty"`
	Every       uint32              `yaml:"every,omitempty"`
	Owner       LayoutFieldOwner    `yaml:"owner,omitempty"`
}

LayoutField is one replicated field of an entity layout: its name and wire type, its quantization, when it is sent, how it is interpolated, the snapshot interval at which it is sent when Every is non-zero, and which side may author it (server by default, or client).

type LayoutFieldOwner

type LayoutFieldOwner string

LayoutFieldOwner specifies which side may author a layout field: the server (default) or the entity's owning client.

const (
	OwnerServer LayoutFieldOwner = "server"
	OwnerClient LayoutFieldOwner = "client"
)

type LayoutInterpolation

type LayoutInterpolation string

LayoutInterpolation is how a client blends a layout field between two snapshots.

const (
	InterpolateNone   LayoutInterpolation = "none"
	InterpolateLinear LayoutInterpolation = "linear"
	InterpolateSlerp  LayoutInterpolation = "slerp"
	InterpolateAngle  LayoutInterpolation = "angle"
	InterpolateStep   LayoutInterpolation = "step"
)

type LayoutQuantization

type LayoutQuantization struct {
	Min  *float64 `yaml:"min,omitempty"`
	Max  *float64 `yaml:"max,omitempty"`
	Bits int      `yaml:"bits,omitempty"`
}

LayoutQuantization packs a number field into Bits bits (1 to 32) over the range from Min to Max.

type LayoutSyncMode

type LayoutSyncMode string

LayoutSyncMode is when a layout field is sent: every snapshot, when it changes, only when the entity spawns, or never.

const (
	SyncAlways   LayoutSyncMode = "always"
	SyncOnChange LayoutSyncMode = "on_change"
	SyncSpawn    LayoutSyncMode = "spawn"
	SyncNever    LayoutSyncMode = "never"
)

type LinkReporter

type LinkReporter interface {
	LinkStats(peer PeerID) (LinkStats, bool)
}

LinkReporter is implemented by every transport in this package: LoopbackTransport, WebSocketTransport, WebSocketServer, WebTransportTransport, WebTransportServer, UDPTransport, UDPServer, UDPClient, RelayTransport, Router, and SubTransport.

LinkStats returns the latest per-peer RTT, RTT variance, sliding-window packet loss fraction in [0, 1], and cumulative byte/packet counters. It returns (LinkStats{}, false) when peer is unknown, disconnected, or the transport is closed.

type LinkStats

type LinkStats struct {
	RTT, RTTVar                                    time.Duration
	Loss                                           float64
	BytesSent, BytesRecv, PacketsSent, PacketsRecv uint64
	// SendRate is the current congestion-controlled send rate in bytes per second (zero if the transport does not pace).
	SendRate int64
	// QueuedBytes is the payload bytes waiting in the peer's outbound pacing queue.
	QueuedBytes int64
	// DrainTime is how long QueuedBytes will take to leave at SendRate.
	DrainTime time.Duration
}

LinkStats summarizes one peer's recent transport quality.

type ListenHost

type ListenHost struct {
	// contains filtered or unexported fields
}

ListenHost wraps a server Transport so the hosting player participates in the session in-process alongside remote clients without opening a local socket.

Server returns a Transport whose Peers include both the local player and every remote client connected to the wrapped server; pass it to NewServerWorld, NewRouter, NewLockstepSession, or NewRollbackSession. Local returns the matching client-side Transport for the hosting player; pass it to NewClientWorld or NewRouter using ServerID().

Closing the host, its Server transport, or its Local transport ends the match cleanly: the local peer emits PeerLeft on Server().NextEvent, connected remote clients are disconnected with the reason "host left" when the wrapped server supports Kick, and the wrapped server is closed.

func NewListenHost

func NewListenHost(server Transport) *ListenHost

NewListenHost wraps server with an in-process local player peer.

The local player receives a unique PeerID that does not collide with the server's LocalID or with remote peers admitted by UDPServer, WebSocketServer, or WebTransportServer. Server().NextEvent immediately queues a PeerJoined event for the local player.

Passing a nil server returns a closed ListenHost whose sends return ErrClosed.

func (*ListenHost) Close

func (h *ListenHost) Close() error

Close ends the listen host cleanly. It is safe to call more than once and from any goroutine. Connected remote clients are kicked with "host left" before the wrapped server closes so they observe the match ending without waiting for an idle timeout.

func (*ListenHost) Local

func (h *ListenHost) Local() *ListenLocalTransport

Local returns the client-side Transport for the hosting player.

func (*ListenHost) LocalID

func (h *ListenHost) LocalID() PeerID

LocalID returns the PeerID assigned to the hosting player's in-process peer.

func (*ListenHost) Server

func (h *ListenHost) Server() *ListenServerTransport

Server returns the server-side Transport whose Peers and Recv merge the local player with every remote client connected to the wrapped server.

func (*ListenHost) ServerID

func (h *ListenHost) ServerID() PeerID

ServerID returns the wrapped server's PeerID.

type ListenLocalTransport

type ListenLocalTransport struct {
	// contains filtered or unexported fields
}

ListenLocalTransport is the client-side Transport view for the hosting player of a ListenHost. It implements Transport and InboxReporter without opening a network socket.

func (*ListenLocalTransport) Close

func (l *ListenLocalTransport) Close() error

Close closes the local player and ends the listen host cleanly so remote clients see the match end immediately.

func (*ListenLocalTransport) Err

func (l *ListenLocalTransport) Err() error

Err returns why the local peer was disconnected (for example a *KickError after Kick), or nil while open or after a clean Close.

func (*ListenLocalTransport) InboxStats

func (l *ListenLocalTransport) InboxStats() InboxStats

InboxStats reports what the local player's inbox holds and what its limits dropped or warned about.

func (*ListenLocalTransport) LocalID

func (l *ListenLocalTransport) LocalID() PeerID

LocalID returns the local player's PeerID.

func (*ListenLocalTransport) Peers

func (l *ListenLocalTransport) Peers() []PeerID

Peers returns a slice containing the server's PeerID while connected, or nil once closed or disconnected.

func (*ListenLocalTransport) Recv

func (l *ListenLocalTransport) Recv() (Packet, bool)

Recv pops the next packet sent by the server to the local player without blocking.

func (*ListenLocalTransport) Send

func (l *ListenLocalTransport) Send(to PeerID, ch Channel, payload []byte) error

Send delivers payload in-process to the server on ch. Only ServerID() and PeerBroadcast are valid targets; any other target returns ErrUnknownPeer.

func (*ListenLocalTransport) SetInboxLimits

func (l *ListenLocalTransport) SetInboxLimits(lim InboxLimits)

SetInboxLimits bounds the packets queued for the local player until Recv takes them.

func (*ListenLocalTransport) State

func (l *ListenLocalTransport) State() ConnState

State returns the local player's connection state (ConnOpen while active, ConnDisconnected if kicked, or ConnClosed after Close).

type ListenServerTransport

type ListenServerTransport struct {
	// contains filtered or unexported fields
}

ListenServerTransport is the server-side Transport view of a ListenHost. It implements Transport, Multicaster, PeerEvents, and InboxReporter.

func (*ListenServerTransport) Close

func (s *ListenServerTransport) Close() error

Close ends the listen host, kicking connected remote peers and closing the wrapped server.

func (*ListenServerTransport) Err

func (s *ListenServerTransport) Err() error

Err returns the wrapped server's fatal receive error, if it reports one.

func (*ListenServerTransport) InboxStats

func (s *ListenServerTransport) InboxStats() InboxStats

InboxStats returns the combined server inbox statistics across the local player's queue and the wrapped server's inbox.

func (*ListenServerTransport) Kick

func (s *ListenServerTransport) Kick(peer PeerID, reason string) error

Kick disconnects peer with reason. Kicking the local player marks Local() disconnected with a KickError and emits PeerLeft on NextEvent; kicking a remote peer delegates to the wrapped server when it supports Kick.

func (*ListenServerTransport) LocalID

func (s *ListenServerTransport) LocalID() PeerID

LocalID returns the server's PeerID.

func (*ListenServerTransport) NextEvent

func (s *ListenServerTransport) NextEvent() (PeerEvent, bool)

NextEvent pops the next PeerEvent from the local player or the wrapped server without blocking.

func (*ListenServerTransport) Peers

func (s *ListenServerTransport) Peers() []PeerID

Peers returns the sorted list of connected peers, including the local player while open and every connected remote client on the wrapped server.

func (*ListenServerTransport) Recv

func (s *ListenServerTransport) Recv() (Packet, bool)

Recv pops the next packet from either the local player or a remote client without blocking, alternating priority so neither side can starve the other.

func (*ListenServerTransport) Send

func (s *ListenServerTransport) Send(to PeerID, ch Channel, payload []byte) error

Send delivers payload to the local player in-process when to matches LocalID, to a remote peer via the wrapped server, or to both when to is PeerBroadcast.

func (*ListenServerTransport) SendMany

func (s *ListenServerTransport) SendMany(peers []PeerID, ch Channel, payload []byte) (failed []PeerID, err error)

SendMany delivers one payload to each peer in peers in order, routing the local peer in-process and batching remote peers through the wrapped server.

func (*ListenServerTransport) SetChannelConfig

func (s *ListenServerTransport) SetChannelConfig(cfg ChannelConfig)

SetChannelConfig updates the accepted channel configuration on the listen host and on the wrapped server when it supports SetChannelConfig.

func (*ListenServerTransport) SetInboxLimits

func (s *ListenServerTransport) SetInboxLimits(l InboxLimits)

SetInboxLimits applies inbox limits to both the local player's server-side queue and the wrapped server when it implements InboxReporter.

type LockstepConfig

type LockstepConfig struct {
	Transport        Transport
	Sim              SimState
	Peers            []PeerID
	ChecksumInterval int
	OnDesync         func(DesyncEvent)
	// Host is the peer that admits and removes peers while the match runs, with AddPeer and RemovePeer. Zero means the lowest ID of Peers, leaving out the local peer when Join is set; a joining session that finds no other peer there, or that names itself, takes the lowest other ID the transport reports on each Poll until its join state arrives. Set it explicitly when joining over a relay, whose peer list may still be empty or include other newcomers. Every peer of a match must name the same host, and the host stays for the whole match.
	Host PeerID
	// Join starts the session as a peer joining a match already running. It takes no part until the host's join state arrives with the tick it joins at, the peers and the simulation's state, which it loads into Sim; until then Step does nothing and Active reports false. Peers then only serves to find the host when Host is zero.
	Join bool
}

LockstepConfig configures a strict deterministic LockstepSession.

type LockstepSession

type LockstepSession struct {
	// contains filtered or unexported fields
}

LockstepSession advances a deterministic simulation tick only once every participating peer's input for that tick has arrived, exchanging periodic state checksums to detect desyncs.

Peers may join and leave while the match runs: the host admits one with AddPeer and removes one with RemovePeer, and every peer applies the change at the same tick.

Example

A LockstepSession steps a deterministic simulation only once every peer's input for the tick has arrived, so all peers stay in the same state.

package main

import (
	"encoding/binary"
	"fmt"
	"time"

	"github.com/nsgo-dev/game/pkg/online/netplay"
)

// tally is a tiny deterministic simulation: each tick adds every player's input bits to a running total.
type tally struct{ total uint64 }

func (s *tally) Step(inputs []netplay.InputFrame) {
	for _, in := range inputs {
		s.total += in.Bits
	}
}

func (s *tally) Save() []byte { return binary.LittleEndian.AppendUint64(nil, s.total) }

func (s *tally) Load(b []byte) error {
	s.total = binary.LittleEndian.Uint64(b)
	return nil
}

func (s *tally) Checksum() uint64 { return s.total }

func main() {
	hub := netplay.NewLoopbackHub(netplay.LoopbackConfig{Latency: 30 * time.Millisecond})
	simA, simB := &tally{}, &tally{}
	a := netplay.NewLockstepSession(netplay.LockstepConfig{Transport: hub.AddPeer(1), Sim: simA, Peers: []netplay.PeerID{1, 2}})
	b := netplay.NewLockstepSession(netplay.LockstepConfig{Transport: hub.AddPeer(2), Sim: simB, Peers: []netplay.PeerID{1, 2}})

	for tick := range uint32(3) {
		a.SubmitInput(netplay.InputFrame{Tick: tick, Peer: 1, Bits: 1})
		b.SubmitInput(netplay.InputFrame{Tick: tick, Peer: 2, Bits: 10})
		stepped := a.Step()
		hub.Advance(30 * time.Millisecond)
		fmt.Println(tick, stepped, a.Step(), b.Step())
	}
	fmt.Println(simA.total, simB.total)
}
Output:
0 false true true
1 false true true
2 false true true
33 33

func NewLockstepSession

func NewLockstepSession(cfg LockstepConfig) *LockstepSession

NewLockstepSession creates a strict lockstep session.

func (*LockstepSession) Active

func (s *LockstepSession) Active() bool

Active reports whether the local peer takes part in the current tick: false while a joining peer waits for its join state, and from the tick the host removed the local peer at.

func (*LockstepSession) AddPeer

func (s *LockstepSession) AddPeer(id PeerID) (uint32, error)

AddPeer admits a peer to the running match and returns the tick it joins at. Only the host may call it, typically when its transport reports the peer (PeerJoined, or a new member in a RelayTransport's Peers). The tick is the host's next own input tick, so no peer has run it yet; the other peers learn of the change before the host's input for that tick, and inputs before it are not expected from the new peer. Once the host's simulation stands at the start of the join tick, Step sends the new peer the state, which must be no larger than MaxJoinStateSize, the tick and the peers.

Adding a peer that already takes part returns its join tick. It returns ErrNotHost on any other peer, ErrPeerRejoin for a peer that has left, ErrUnknownPeer for ID 0 and ErrPayloadTooLarge when the state is larger than MaxJoinStateSize.

Example

The host admits a peer to a running lockstep match: the newcomer loads the host's state at the join tick, and the others expect its inputs from that tick on. RemovePeer reverses it: from the leave tick nobody waits for the peer.

package main

import (
	"encoding/binary"
	"fmt"
	"time"

	"github.com/nsgo-dev/game/pkg/online/netplay"
)

// tally is a tiny deterministic simulation: each tick adds every player's input bits to a running total.
type tally struct{ total uint64 }

func (s *tally) Step(inputs []netplay.InputFrame) {
	for _, in := range inputs {
		s.total += in.Bits
	}
}

func (s *tally) Save() []byte { return binary.LittleEndian.AppendUint64(nil, s.total) }

func (s *tally) Load(b []byte) error {
	s.total = binary.LittleEndian.Uint64(b)
	return nil
}

func (s *tally) Checksum() uint64 { return s.total }

func main() {
	const latency = 10 * time.Millisecond
	hub := netplay.NewLoopbackHub(netplay.LoopbackConfig{Latency: latency})
	bits := map[netplay.PeerID]uint64{1: 1, 2: 10, 3: 100}
	sims := map[netplay.PeerID]*tally{1: {}, 2: {}, 3: {}}
	sessions := map[netplay.PeerID]*netplay.LockstepSession{}
	for _, id := range []netplay.PeerID{1, 2} {
		sessions[id] = netplay.NewLockstepSession(netplay.LockstepConfig{Transport: hub.AddPeer(id), Sim: sims[id], Peers: []netplay.PeerID{1, 2}})
	}
	host := sessions[1]
	play := func(ticks int) {
		for range ticks {
			for id, s := range sessions {
				s.SubmitInput(netplay.InputFrame{Tick: s.Tick(), Bits: bits[id]})
			}
			hub.Advance(latency)
			for _, s := range sessions {
				s.Step()
			}
		}
	}
	play(2)

	sessions[3] = netplay.NewLockstepSession(netplay.LockstepConfig{Transport: hub.AddPeer(3), Sim: sims[3], Host: 1, Join: true})
	join, _ := host.AddPeer(3)
	hub.Advance(latency)
	for _, s := range sessions {
		s.Poll()
	}
	fmt.Println("joined at", join, sessions[3].Active(), sims[3].total == sims[1].total)
	play(3)
	fmt.Println(host.Members(), sims[1].total, sims[3].total)

	leave, _ := host.RemovePeer(2)
	delete(sessions, 2)
	play(2)
	fmt.Println("left at", leave, host.Members(), sims[1].total, sims[3].total)
}
Output:
joined at 2 true true
[1 2 3] 355 355
left at 5 [1 3] 557 557

func (*LockstepSession) Desyncs

func (s *LockstepSession) Desyncs() []DesyncEvent

Desyncs returns a copy of the most recent DesyncEvents observed, up to maxDesyncHistory of them; OnDesync still sees every one.

func (*LockstepSession) Members

func (s *LockstepSession) Members() []PeerID

Members returns the sorted IDs of the peers taking part in the current tick; it is empty while a joining peer waits for its join state.

func (*LockstepSession) Poll

func (s *LockstepSession) Poll()

Poll drains all pending input, checksum and membership messages from the Transport, first sending again the messages kept for peers the transport could not reach.

func (*LockstepSession) RemovePeer

func (s *LockstepSession) RemovePeer(id PeerID) (uint32, error)

RemovePeer removes a peer from the running match and returns the tick from which no peer waits for it. Only the host may call it, typically once its transport reports the peer gone (PeerLeft, or a RelayTransport's Peers no longer listing it). The tick is the host's next own input tick or the peer's join tick, whichever is later. The change carries the inputs the host holds from the peer for the ticks before it and a zero input for each tick the host never received, so every peer runs those ticks alike; a peer still sending when removed may have reached another peer with an input the host never saw, so remove a peer after it has stopped sending.

Removing a peer that is already leaving, or that left, returns its leave tick. It returns ErrNotHost on any other peer, ErrHostLeave for the host and ErrUnknownPeer for a peer not in the match.

func (*LockstepSession) Step

func (s *LockstepSession) Step() bool

Step polls incoming packets and advances the simulation by one tick if every peer's input for the current tick is present. Returns true when a tick executed.

func (*LockstepSession) SubmitInput

func (s *LockstepSession) SubmitInput(in InputFrame) error

SubmitInput records the local peer's input for in.Tick and sends it to every other peer taking part in that tick. An input for a tick already run or more than 256 ticks ahead, or for a tick the local peer takes no part in, is ignored, as is any input once the host has removed the local peer: the host's leave change carries the inputs every peer uses. A send the transport cannot make right now, to a peer that is reconnecting or that a relay has not announced yet, is kept and retried by Poll; once too many wait for one peer, SubmitInput returns ErrSessionBacklog.

func (*LockstepSession) Tick

func (s *LockstepSession) Tick() uint32

Tick returns the number of ticks simulated so far (also the next tick to execute). A joining peer's count starts at its join tick.

type LoopbackConfig

type LoopbackConfig struct {
	// Latency is the base one-way packet transit delay.
	Latency time.Duration
	// Jitter adds a uniform random offset in [-Jitter, +Jitter] to Latency (clamped to >= 0).
	Jitter time.Duration
	// LossRate is the drop probability in [0, 1] applied to unreliable channels (ChannelUnreliable and ChannelUnreliableSequenced), and also to reliable channels when ImpairReliable is true.
	LossRate float64
	// DuplicateRate is the probability in [0, 1] of delivering a duplicate copy of an unreliable or unreliable-sequenced packet (or any channel when ImpairReliable is true) with an independently sampled delay.
	DuplicateRate float64
	// Bandwidth caps directional link serialization throughput in bytes per second. Zero or negative disables bandwidth limiting.
	Bandwidth int64
	// MaxQueueBytes caps the bottleneck queue depth in bytes when Bandwidth > 0. Excess packets are tail-dropped (reliable channels only when ImpairReliable is true). Zero or negative means unlimited.
	MaxQueueBytes int
	// MaxQueuePackets caps the bottleneck queue depth in packets when Bandwidth > 0. Excess packets are tail-dropped (reliable channels only when ImpairReliable is true). Zero or negative means unlimited.
	MaxQueuePackets int
	// ImpairReliable applies LossRate, DuplicateRate, Jitter reordering, and queue-overflow drops to reliable channels as well, for testing transports that implement reliability above LoopbackHub.
	ImpairReliable bool
	// Seed initializes the deterministic PRNG used for jitter, packet loss, and duplication.
	Seed int64
	// Inbox bounds the inbox of each peer AddPeer adds from then on (see InboxLimits); the zero value uses the defaults. SetConfig leaves it unchanged; LoopbackTransport.SetInboxLimits changes one peer's.
	Inbox InboxLimits
	// Channels declares extra independent reliable ordered lanes accepted by peers on the hub.
	Channels ChannelConfig
}

LoopbackConfig configures deterministic network simulation on a LoopbackHub.

type LoopbackHub

type LoopbackHub struct {
	// contains filtered or unexported fields
}

LoopbackHub simulates an in-memory packet network between LoopbackTransport peers driven by a manual virtual clock via Advance.

Example

A LoopbackHub connects transports in memory with simulated latency and loss, driven by its own clock, so networked code runs in tests without sockets.

package main

import (
	"fmt"
	"time"

	"github.com/nsgo-dev/game/pkg/online/netplay"
)

func main() {
	hub := netplay.NewLoopbackHub(netplay.LoopbackConfig{Latency: 50 * time.Millisecond, Seed: 1})
	server := hub.AddPeer(1)
	client := hub.AddPeer(2)

	client.Send(1, netplay.ChannelReliableOrdered, []byte("hello"))
	_, ok := server.Recv()
	fmt.Println("at 0ms:", ok)
	hub.Advance(50 * time.Millisecond)
	p, ok := server.Recv()
	fmt.Println("at 50ms:", ok, p.From, string(p.Payload))
}
Output:
at 0ms: false
at 50ms: true 2 hello

func NewLoopbackHub

func NewLoopbackHub(cfg LoopbackConfig) *LoopbackHub

NewLoopbackHub creates a new deterministic in-memory network hub.

func (*LoopbackHub) AddPeer

func (h *LoopbackHub) AddPeer(id PeerID) *LoopbackTransport

AddPeer registers a peer with the given ID and returns its Transport. If a peer with the same ID already exists, it is replaced.

func (*LoopbackHub) Advance

func (h *LoopbackHub) Advance(dt time.Duration)

Advance moves the virtual clock forward by dt and delivers all in-flight packets whose scheduled arrival time is <= Now().

func (*LoopbackHub) Config

func (h *LoopbackHub) Config() LoopbackConfig

Config returns the current network simulation configuration.

func (*LoopbackHub) InFlight

func (h *LoopbackHub) InFlight() int

InFlight returns the number of packets currently in transit.

func (*LoopbackHub) Now

func (h *LoopbackHub) Now() time.Duration

Now returns the hub's current virtual clock time.

func (*LoopbackHub) RemovePeer

func (h *LoopbackHub) RemovePeer(id PeerID)

RemovePeer disconnects a peer from the hub.

func (*LoopbackHub) SetChannelConfig

func (h *LoopbackHub) SetChannelConfig(cfg ChannelConfig)

SetChannelConfig updates the hub's accepted channel configuration.

func (*LoopbackHub) SetConfig

func (h *LoopbackHub) SetConfig(cfg LoopbackConfig)

SetConfig updates Latency, Jitter, LossRate, DuplicateRate, Bandwidth, MaxQueueBytes, MaxQueuePackets, and ImpairReliable at runtime without resetting the PRNG or clock.

type LoopbackTransport

type LoopbackTransport struct {
	// contains filtered or unexported fields
}

LoopbackTransport is an endpoint connected to a LoopbackHub.

func (*LoopbackTransport) Close

func (t *LoopbackTransport) Close() error

Close disconnects this endpoint from its LoopbackHub.

func (*LoopbackTransport) InboxStats

func (t *LoopbackTransport) InboxStats() InboxStats

InboxStats reports what the transport's inbox holds and what its limits dropped or warned about.

func (*LoopbackTransport) LinkStats

func (t *LoopbackTransport) LinkStats(peer PeerID) (LinkStats, bool)

LinkStats reports the simulated round-trip time, jitter, recent packet loss, and byte/packet counters for peer.

func (*LoopbackTransport) LocalID

func (t *LoopbackTransport) LocalID() PeerID

LocalID returns this endpoint's PeerID.

func (*LoopbackTransport) Peers

func (t *LoopbackTransport) Peers() []PeerID

Peers returns the sorted list of other connected peers on the hub.

func (*LoopbackTransport) Recv

func (t *LoopbackTransport) Recv() (Packet, bool)

Recv pops the next delivered packet without blocking.

func (*LoopbackTransport) Send

func (t *LoopbackTransport) Send(to PeerID, ch Channel, payload []byte) error

Send transmits payload to the target peer (or all other peers if to == PeerBroadcast).

func (*LoopbackTransport) SendMany

func (t *LoopbackTransport) SendMany(peers []PeerID, ch Channel, payload []byte) (failed []PeerID, err error)

SendMany queues one payload for each peer in the given order under a single hub lock, so no other send interleaves with the fan-out. It returns the peers whose send failed and the first error.

func (*LoopbackTransport) SetInboxLimits

func (t *LoopbackTransport) SetInboxLimits(l InboxLimits)

SetInboxLimits bounds the packets the transport keeps until Recv takes them (see InboxLimits).

type MessageID

type MessageID uint64

MessageID identifies a routed message type in a Router packet envelope.

Every packet sent through a Router begins with a uvarint-encoded MessageID followed immediately by the message payload. ID 0 is invalid. IDs 1 through ReservedMessageIDMax (15) are reserved for pkg/online/netplay's own consumers; application schemas declare explicit IDs >= 16 via module.base in *.wire.yaml.

const (
	// KindReplication is the reserved message ID for ServerWorld and ClientWorld replication traffic.
	KindReplication MessageID = 1
	// KindLockstep is the reserved message ID for LockstepSession traffic.
	KindLockstep MessageID = 2
	// KindRollback is the reserved message ID for RollbackSession traffic.
	KindRollback MessageID = 3
	// KindMembership is the reserved message ID for mid-match membership traffic.
	KindMembership MessageID = 4
	// KindRelay is the reserved message ID for Relay and RelayTransport traffic.
	KindRelay MessageID = 5
	// KindRPCRequest is the reserved message ID for request/response RPC requests.
	KindRPCRequest MessageID = 6
	// KindRPCResponse is the reserved message ID for request/response RPC responses.
	KindRPCResponse MessageID = 7
	// KindRoomState is the reserved message ID for roomstate.Server and roomstate.Client traffic.
	KindRoomState MessageID = 8

	// ReservedMessageIDMax is the highest message ID reserved for pkg/online/netplay's built-in consumers.
	// Application messages must use explicit IDs strictly greater than ReservedMessageIDMax (>= 16).
	ReservedMessageIDMax MessageID = 15
)

func DecodeEnvelope

func DecodeEnvelope(src []byte) (id MessageID, payload []byte, err error)

DecodeEnvelope parses the leading uvarint MessageID from src and returns a zero-copy slice view of the remaining payload. It returns ErrInvalidPacket when src is empty, the varint is truncated or overflows uint64, or the decoded ID is 0.

func DecodeRPCRequest

func DecodeRPCRequest(src []byte) (method MessageID, requestID uint64, body []byte, err error)

DecodeRPCRequest parses an RPC request payload (after stripping KindRPCRequest) and returns the method ID, monotonic request ID, and a zero-copy view of body. It returns ErrInvalidPacket if any varint is invalid, method is in the reserved range (<= ReservedMessageIDMax), or requestID is 0.

type Middleware

type Middleware func(next Handler) Handler

Middleware wraps a Handler to implement cross-cutting checks such as rate guards, authentication, authorization, and audit logging.

type Multicaster

type Multicaster interface {
	SendMany(peers []PeerID, ch Channel, payload []byte) (failed []PeerID, err error)
}

Multicaster sends one payload to an ordered peer set. Implementations may resolve sessions and queue frames under one transport lock. Callers should use SendMany for room or team fan-out and inspect failed for peers that were unavailable.

type Outbound

type Outbound struct {
	Payload  []byte
	Reliable bool
}

Outbound is one application message awaiting pacing. A reliable message may share a datagram with the reliable messages queued after it, up to the MTU; an unreliable message always travels alone.

type OutboxLimits

type OutboxLimits struct {
	// Frames is the most frames one client's outbox holds. Zero uses DefaultOutboxFrames; a negative value removes the cap.
	Frames int
	// Bytes is the most bytes of frames one client's outbox holds, counting each frame's payload and its 5-byte header. Zero uses DefaultOutboxBytes; a negative value removes the cap.
	Bytes int
}

OutboxLimits bounds the frames a WebSocketServer or WebTransportServer holds for one client before they are written to its connection.

Send never writes to a client's connection itself: it queues the frame in the client's outbox and returns, and a goroutine of the client's own writes the queue out, so a client that reads slowly, or stops reading, delays only its own frames and never the caller's tick or the other clients. A WebTransportServer gives each client a second outbox, with the same limits, for its ChannelUnreliable datagrams, which QUIC sends apart from the reliable stream. A frame that would take a client's outbox past Frames frames or Bytes bytes first makes room by dropping that client's oldest queued ChannelUnreliable frames. A ChannelUnreliable frame that still does not fit is dropped itself, and a ChannelReliableOrdered frame that does not fit ends the client's session: dropping it would break the channel's order, so NextEvent reports PeerLeft with the reason "outbox full" and Send returns ErrDisconnected for that client. A frame always fits an empty outbox, whatever its size.

Send therefore reports only what it knows when it queues: ErrDisconnected, ErrUnknownPeer, ErrPayloadTooLarge and ErrClosed. A write that fails, or that takes longer than the write timeout (10 seconds), closes the client's connection rather than leave part of a frame on the wire, and NextEvent reports PeerDropped as for any lost connection; the frames still queued for it are discarded.

WebSocketServer.Kick and Close let each client's writer flush the frames already queued for it before the close frame, for at most a second, and cut off the connection of a client that has not taken them by then.

type OutboxReporter

type OutboxReporter interface {
	SetOutboxLimits(OutboxLimits)
	OutboxStats() OutboxStats
}

OutboxReporter is implemented by the server transports that queue each client's outgoing frames: WebSocketServer and WebTransportServer. SetOutboxLimits changes the limits at any time; frames already queued stay, and the new limits apply to the frames Send queues afterwards. OutboxStats reads the outboxes' counters.

type OutboxStats

type OutboxStats struct {
	// Frames is the number of frames queued across every connected client's outbox.
	Frames int
	// Bytes is the number of bytes those frames hold.
	Bytes int
	// UnreliableDropped counts the ChannelUnreliable frames dropped because their client's outbox was full.
	UnreliableDropped uint64
	// Overflows counts the sessions ended because a ChannelReliableOrdered frame did not fit its client's outbox.
	Overflows uint64
}

OutboxStats reports what a server transport's outboxes hold and what their limits dropped.

type Pacer

type Pacer struct {
	// contains filtered or unexported fields
}

Pacer spreads datagrams over time at an AIMD-controlled byte rate and coalesces queued reliable messages under the MTU. It reads no clock and starts no goroutine: the caller passes its own (fixed-step) time to Poll. It is not safe for concurrent use.

func NewPacer

func NewPacer(cfg CongestionConfig) *Pacer

NewPacer returns a Pacer for cfg. Zero fields take DefaultCongestionConfig's values; RateMax is raised to RateMin, InitialRate is clamped into [RateMin, RateMax], and MTU is clamped to what a 2-byte length prefix can frame.

func (*Pacer) Acked

func (p *Pacer) Acked(bytes int64)

Acked applies additive increase of one eighth of the newly acknowledged bytes, bounded by RateMax, and ends a loss streak.

func (*Pacer) DrainTime

func (p *Pacer) DrainTime() time.Duration

DrainTime returns how long the queued bytes take to leave at the current rate.

func (*Pacer) Enqueue

func (p *Pacer) Enqueue(msg Outbound) error

Enqueue copies msg into the queue. It returns ErrPayloadTooLarge for a payload that does not fit one datagram with its length prefix.

func (*Pacer) LossStreak

func (p *Pacer) LossStreak() int

LossStreak returns how many Lost calls happened since the last Acked.

func (*Pacer) Lost

func (p *Pacer) Lost()

Lost applies multiplicative decrease to 70% of the current rate, bounded by RateMin.

func (*Pacer) Poll

func (p *Pacer) Poll(now time.Time) [][]byte

Poll returns the datagrams whose pacing deadlines have elapsed at now. Each datagram holds one or more messages, each prefixed with its length as a big-endian uint16; SplitDatagram reverses it. A pacer whose queue ran empty does not bank the idle time as a burst: its next datagram is due at the first Poll after new messages arrive.

func (*Pacer) QueueBytes

func (p *Pacer) QueueBytes() int64

QueueBytes returns the payload bytes waiting to be sent, framing excluded.

func (*Pacer) Rate

func (p *Pacer) Rate() int64

Rate returns the current send rate in bytes per second.

func (*Pacer) SetRate

func (p *Pacer) SetRate(rate int64)

SetRate sets the current rate, clamped into [RateMin, RateMax]. A non-positive rate is ignored.

type Packet

type Packet struct {
	From    PeerID
	Channel Channel
	Payload []byte
	Seq     uint32
}

Packet is a single datagram received from a remote peer.

type PeerEvent

type PeerEvent struct {
	Kind PeerEventKind
	Peer PeerID
	// Account is the account Auth.Identify bound to this session, empty for anonymous sessions or servers without Identify.
	Account string
	// Reason is why a server removed the peer: the reason given to WebSocketServer.Kick or UDPServer.Kick, "replaced" when a duplicate login ended the session under ReplaceOld, or "outbox full" when a WebSocketServer or WebTransportServer ended the session because the client's reliable frames no longer fit its outbox (see OutboxLimits). It is empty for every other event.
	Reason string
}

PeerEvent is one change to a peer's session, reported by a server's NextEvent.

type PeerEventKind

type PeerEventKind uint8

PeerEventKind is what happened to a peer's session.

const (
	// PeerJoined reports a client that passed the handshake and received a new ID.
	PeerJoined PeerEventKind = iota + 1
	// PeerDropped reports a connection that broke without a goodbye; the peer keeps its ID for Auth.GracePeriod.
	PeerDropped
	// PeerResumed reports a dropped peer that reconnected within the grace period with its old ID.
	PeerResumed
	// PeerLeft reports a peer that closed its connection, or whose grace period ran out. Its ID is gone.
	PeerLeft
)

func (PeerEventKind) String

func (k PeerEventKind) String() string

String returns the event kind's name.

type PeerEvents

type PeerEvents interface {
	NextEvent() (PeerEvent, bool)
}

PeerEvents is implemented by the server transports that run the connection handshake. NextEvent pops the next session change without blocking; grace periods and idle timeouts are checked when it is called, so a server polls it every tick alongside Recv.

type PeerID

type PeerID uint32

PeerID uniquely identifies a participant in a multiplayer session.

const PeerBroadcast PeerID = 0

PeerBroadcast targets all connected remote peers when passed to Transport.Send.

func SendMany

func SendMany(tx Transport, peers []PeerID, ch Channel, payload []byte) (failed []PeerID, err error)

SendMany uses a transport's batch path when available and otherwise sends to peers in the supplied order. It returns every peer whose send failed, in that order, and the first error; a nil transport fails every peer with ErrClosed.

type RPCStats

type RPCStats struct {
	// RequestsHandled counts fresh server-side RPC handler executions.
	RequestsHandled uint64
	// CacheHits counts duplicate requests answered from the per-peer deduplication cache without re-running the handler.
	CacheHits uint64
	// CacheEvictions counts cached per-peer results evicted to stay within the configured cache capacity.
	CacheEvictions uint64
	// CallsSent counts initial outgoing RPC requests transmitted.
	CallsSent uint64
	// CallsResent counts pending outgoing RPC requests retransmitted with their original IDs after a resume.
	CallsResent uint64
	// CallsTimedOut counts outgoing RPC calls expired by their deadline.
	CallsTimedOut uint64
	// PendingCalls is the number of outgoing RPC calls currently awaiting a response.
	PendingCalls int
	// CachedPeers is the number of remote peers with at least one entry in the server deduplication cache.
	CachedPeers int
	// CachedEntries is the total number of entries held across all per-peer deduplication caches.
	CachedEntries int
}

RPCStats reports RPC counters and cache occupancy for a Router.

type ReconnectState

type ReconnectState uint8

ReconnectState reports the supervisor's current connection phase.

const (
	// StateConnected reports that connect succeeded.
	StateConnected ReconnectState = iota
	// StateReconnecting reports that another attempt will follow a backoff.
	StateReconnecting
	// StateFailed reports that retries ended or the context was canceled.
	StateFailed
)

type ReconnectSupervisor

type ReconnectSupervisor struct {
	// MaxAttempts is the number of calls to connect, five when zero or negative.
	MaxAttempts int
	// BaseDelay is the initial backoff, 250 milliseconds when zero or negative.
	BaseDelay time.Duration
	// State is the latest connection phase.
	State ReconnectState
	// Attempts is the number of completed attempts.
	Attempts int
}

ReconnectSupervisor retries a connection function with bounded exponential backoff according to MaxAttempts and BaseDelay. Run blocks, so call it from its own goroutine to keep the game loop stepping; State and Attempts are written by Run without synchronization, so read them only after Run returns.

func (*ReconnectSupervisor) Run

func (s *ReconnectSupervisor) Run(ctx context.Context, connect func(context.Context) error) error

Run calls connect until it succeeds, the context ends or MaxAttempts calls have failed, waiting a capped exponential backoff with jitter between failures. Each Run counts attempts from zero. It returns nil after a successful connect, ctx.Err() when the context ends first, and the last connect error, wrapped, when every attempt failed.

type RejectCode

type RejectCode uint8

RejectCode is why a server refused a client's handshake, so a client can choose a screen or an action instead of matching reason text. A code is stable across releases; the reason beside it is for people.

const (
	// RejectUnspecified is a refusal with no particular cause.
	RejectUnspecified RejectCode = iota
	// RejectServerFull reports Auth.MaxPeers sessions already held.
	RejectServerFull
	// RejectMaintenance reports a server that is up but not taking new matches, such as during a deploy.
	RejectMaintenance
	// RejectUpdateRequired reports a client build below Auth.MinClientVersion or without a parsable version.
	RejectUpdateRequired
	// RejectBanned reports a client the server refuses by identity.
	RejectBanned
	// RejectInvalidToken reports a credential Auth.VerifyHello, Auth.Verify or Auth.Identify refused.
	RejectInvalidToken
	// RejectHandshakeVersion reports a client speaking another handshake version; the client should update.
	RejectHandshakeVersion
	// RejectAlreadySignedIn reports an account that already has a live session under Auth.DuplicateLogin == RejectNew.
	RejectAlreadySignedIn
)

func (RejectCode) String

func (c RejectCode) String() string

String returns the code's name.

type RejectError

type RejectError struct {
	Code       RejectCode
	Reason     string
	RetryAfter time.Duration
}

RejectError is the reason a server gave for refusing a client's handshake: a stable code a client may branch on, the human-readable reason beside it and, when the server knows, how long to wait before trying again.

func (*RejectError) Error

func (e *RejectError) Error() string

Error returns the rejection with its code and reason.

func (*RejectError) Is

func (e *RejectError) Is(target error) bool

Is reports whether target is ErrRejected.

type Relay

type Relay struct {
	// contains filtered or unexported fields
}

Relay forwards packets between the peers of a peer-to-peer session, so lockstep and rollback work for players who cannot reach each other directly: each player connects to the relay with a RelayTransport over WebSocket or UDP, and the relay passes each frame to the member it is addressed to.

The relay sits on a WebSocketServer or UDPServer, so every client passes that server's connection handshake first; Join then decides which session the client belongs to. A frame addressed outside the sender's session is dropped. The relay never reads the payloads, and reliability is end to end between RelayTransports, so the relay may drop a frame for a member that is reconnecting or too slow without breaking ChannelReliableOrdered.

func NewRelay

func NewRelay(cfg RelayConfig) (*Relay, error)

NewRelay returns a relay for cfg. It fails when cfg.Join is nil.

func (*Relay) Auth

func (r *Relay) Auth(base Auth) Auth

Auth returns base with Verify replaced by the relay's admission: base.Verify, when set, checks the token first, then Join picks the session and the relay refuses a full one. Pass the result to ListenWebSocket, ListenWebSocketTLS or ListenUDPServer, and serve that server with Serve.

func (*Relay) Serve

func (r *Relay) Serve(ctx context.Context, srv RelayServer) error

Serve forwards srv's packets until ctx ends, then stops the members' writers and returns ctx's error. srv must have been created with r.Auth. A relay serves one server for its lifetime: Serve may be called again on the same server after it returns, and the clients still connected keep their sessions, but a concurrent Serve or a Serve on another server returns an error. Serve does not close srv.

func (*Relay) Stats

func (r *Relay) Stats() RelayStats

Stats returns the relay's current counts.

type RelayConfig

type RelayConfig struct {
	// Join admits a client to a session: it checks the token the client presented in the connection handshake and returns the name of the session the client joins, or an error whose text is sent back as the rejection reason. Packets are forwarded only between members of the same session. Join is required. It runs where Auth.Verify runs: on the client's goroutine for WebSocket and on the receive goroutine for UDP, so check a signed token locally.
	Join func(peer PeerID, token []byte) (session string, err error)
	// MaxSessionPeers is the most members a session holds, counting members inside their grace period; 8 when zero. A client past it is rejected with the reason "session full".
	MaxSessionPeers int
	// QueueSize is how many frames the relay holds for one member that has not been written yet; 256 when zero. Frames past it are dropped, and the senders' RelayTransports resend the reliable ones.
	QueueSize int
}

RelayConfig configures a Relay.

type RelayServer

type RelayServer interface {
	Transport
	PeerEvents
}

RelayServer is a server transport a Relay serves: WebSocketServer, WebTransportServer, or UDPServer.

type RelayStats

type RelayStats struct {
	// Sessions is the number of sessions with at least one member.
	Sessions int
	// Peers is the number of members across all sessions, including members inside their grace period.
	Peers int
	// Forwarded counts frames queued for a member, including the relay's own membership updates.
	Forwarded uint64
	// Dropped counts frames refused: malformed, from a client in no session, addressed outside the sender's session, or past a member's queue.
	Dropped uint64
}

RelayStats counts a relay's sessions and traffic.

type RelayTransport

type RelayTransport struct {
	// contains filtered or unexported fields
}

RelayTransport is a peer-to-peer Transport whose packets travel through a Relay, so peers that cannot reach each other, behind NAT or in a browser, still exchange packets. It wraps a client transport connected to the relay: a WebSocketTransport (native or browser), a WebTransportTransport (native or browser), or a UDPClient.

Peers reports the other members of the relay session the client joined, and Send addresses them by the IDs the relay assigned. ChannelReliableOrdered is reliable and ordered end to end: the transport numbers each peer's messages, the receiver acknowledges them, and lost ones are sent again, so it works over UDP, which drops datagrams, and survives the relay dropping a packet for a peer that is reconnecting. ChannelUnreliable packets are sent once and may be lost.

Acknowledgements and retransmissions happen inside Recv, so a game polls Recv every tick, as LockstepSession and RollbackSession do.

func NewRelayTransport

func NewRelayTransport(inner Transport, cfg RelayTransportConfig) *RelayTransport

NewRelayTransport wraps inner, a client transport whose handshake with a Relay has succeeded. Closing the RelayTransport closes inner. To reconnect after a drop, call the inner transport's Reconnect: within the relay's grace period the client keeps its ID and its messages, and unacknowledged reliable ones are sent again.

func (*RelayTransport) Close

func (rt *RelayTransport) Close() error

Close closes the inner transport.

func (*RelayTransport) CongestionConfig

func (rt *RelayTransport) CongestionConfig() CongestionConfig

CongestionConfig returns the active congestion control configuration for RelayTransport.

func (*RelayTransport) InboxStats

func (rt *RelayTransport) InboxStats() InboxStats

InboxStats reports what the transport's inbox holds and what its limits dropped or warned about.

func (*RelayTransport) LinkStats

func (rt *RelayTransport) LinkStats(peer PeerID) (LinkStats, bool)

LinkStats reports the end-to-end RTT, RTT variance, sliding-window packet loss, and byte/packet counters for peer in the relay session.

func (*RelayTransport) LocalID

func (rt *RelayTransport) LocalID() PeerID

LocalID returns the ID the relay assigned this client.

func (*RelayTransport) Peers

func (rt *RelayTransport) Peers() []PeerID

Peers returns the sorted IDs of the other members of this client's relay session, including members inside the relay's grace period, as of the last membership update Recv processed.

func (*RelayTransport) Recv

func (rt *RelayTransport) Recv() (Packet, bool)

Recv pops the next packet from a session member without blocking. Each call first drains the inner transport, acknowledges reliable messages and resends the ones whose acknowledgement is overdue.

func (*RelayTransport) Send

func (rt *RelayTransport) Send(to PeerID, ch Channel, payload []byte) error

Send sends payload to a member of the session, or to every other member when to is PeerBroadcast. It returns ErrUnknownPeer for an ID outside the session, ErrPayloadTooLarge above MaxRelayPayload and ErrRelayBacklog when a peer has too many unacknowledged reliable messages. A reliable message the inner transport cannot send right now, because it is reconnecting, is kept and sent again; an unreliable one returns the inner transport's error.

func (*RelayTransport) SetCompression

func (rt *RelayTransport) SetCompression(cfg CompressionConfig) error

SetCompression updates opt-in per-packet deflate compression settings and the decompression cap for RelayTransport. Even when Enabled is false, RelayTransport still inflates compressed frames from peers up to MaxInflated (capped at MaxRelayPayload).

func (*RelayTransport) SetCongestionConfig

func (rt *RelayTransport) SetCongestionConfig(cfg CongestionConfig)

SetCongestionConfig enables or updates per-peer rate control, pacing, coalescing, and piggybacked acknowledgements on RelayTransport.

func (*RelayTransport) SetInboxLimits

func (rt *RelayTransport) SetInboxLimits(l InboxLimits)

SetInboxLimits bounds the packets the transport keeps until Recv takes them (see InboxLimits). A peer whose queued reliable messages reach InboxLimits.Reliable is not acknowledged further, so it resends them once Recv has made room.

type RelayTransportConfig

type RelayTransportConfig struct {
	// Now is the clock for retransmission timers; nil uses time.Now.
	Now func() time.Time
	// Inbox bounds the packets the RelayTransport keeps until Recv takes them (see InboxLimits); the zero value uses the defaults. The inner transport's inbox has its own limits, set on it directly; the relay carries reliable messages as unreliable frames, so a frame the inner inbox drops is sent again.
	Inbox InboxLimits
	// Compression configures opt-in per-packet deflate compression on end-to-end relay payloads. Off by default (Enabled: false); RelayTransport still inflates compressed frames from peers up to MaxInflated (capped at MaxRelayPayload).
	Compression CompressionConfig
	// Congestion configures per-peer send-rate pacing, coalescing, and piggybacked acknowledgements on RelayTransport. When non-zero, reliable and unreliable sends share the per-peer rate budget, small reliable messages coalesce up to MTU, and acknowledgements piggyback onto outgoing frames.
	Congestion CongestionConfig
}

RelayTransportConfig configures a RelayTransport.

type RenderTickOptions

type RenderTickOptions struct {
	// MinDelay is the minimum interpolation delay in ticks behind the snapshot stream (default 2 when <= 0).
	MinDelay float64
	// MaxDelay is the maximum interpolation delay in ticks (default 10 when <= 0; raised to at least MinDelay).
	MaxDelay float64
	// JitterMultiplier scales the measured arrival jitter (in ticks) added on top of MinDelay (default 2 when <= 0).
	JitterMultiplier float64
	// TickRate overrides the server tick rate in Hz used to convert RTT and jitter into ticks when > 0; zero uses ClientWorld's configured or estimated tick rate.
	TickRate float64
}

RenderTickOptions configures adaptive interpolation delay for ClientWorld.RenderTick.

type ReplicatedComponent

type ReplicatedComponent struct {
	// Name is the component's registered codec or type name (unique within the file).
	Name string `yaml:"name" schema:"required,minLength=1"`
	// Sync controls when the component is sent: always, on_change (default when empty), spawn, or never.
	Sync LayoutSyncMode `yaml:"sync,omitempty" schema:"enum=always|on_change|spawn|never"`
	// Interpolate controls how clients blend the component between snapshots: none, linear, slerp, angle, or step.
	Interpolate LayoutInterpolation `yaml:"interpolate,omitempty" schema:"enum=none|linear|slerp|angle|step"`
	// Every, when non-zero, limits updates of this component to at most once every N ticks.
	Every uint32 `yaml:"every,omitempty" schema:"minimum=0"`
	// Owner controls which side may author this component: server (default when empty) or client.
	Owner LayoutFieldOwner `yaml:"owner,omitempty" schema:"enum=server|client"`
}

ReplicatedComponent declares one ECS component type replicated for spawned entities, its sync cadence, optional interpolation, and per-component authority owner.

type ReplicatedPrefab

type ReplicatedPrefab struct {
	// Kind is the non-zero wire kind number that identifies this prefab in snapshots.
	Kind uint16 `yaml:"kind" schema:"required,minimum=1"`
	// Prefab is the non-empty prefab name registered on both server and clients.
	Prefab string `yaml:"prefab" schema:"required,minLength=1"`
}

ReplicatedPrefab maps a stable non-zero wire kind number to the name of the prefab spawned on server and clients.

type ReplicationDocument

type ReplicationDocument struct {
	// Version is the schema version; it must be ReplicationConfigVersion (1).
	Version int `yaml:"version" schema:"required"`
	// SpawnLimit caps the maximum number of live replicated entities the server may spawn; 0 means unlimited.
	SpawnLimit int `yaml:"spawnLimit,omitempty" schema:"minimum=0"`
	// Prefabs maps non-zero wire kind numbers to prefab names, sorted by kind when encoded.
	Prefabs []ReplicatedPrefab `yaml:"prefabs" schema:"required"`
	// Components lists the component types synced for replicated entities, sorted by name when encoded.
	Components []ReplicatedComponent `yaml:"components,omitempty"`
}

ReplicationDocument is a versioned world replication configuration file (net/replication.yaml) listing spawnable prefab kinds, the optional spawn limit, and synced components.

func ParseReplicationYAML

func ParseReplicationYAML(data []byte) (*ReplicationDocument, error)

ParseReplicationYAML reads a ReplicationDocument from YAML, refusing unknown fields and trailing documents, and validates it. Its errors are *loaderr.Error values carrying line and field location.

func (*ReplicationDocument) Component

func (d *ReplicationDocument) Component(name string) (ReplicatedComponent, bool)

Component returns the synced component rule for name and whether d declares one.

func (*ReplicationDocument) PrefabTableHash

func (d *ReplicationDocument) PrefabTableHash() uint64

PrefabTableHash returns a deterministic 64-bit fingerprint of d's sorted kind-to-prefab-name table, matching PrefabTableHash(d.ReplicatorConfig().Prefabs).

func (*ReplicationDocument) ReplicatorConfig

func (d *ReplicationDocument) ReplicatorConfig() ReplicatorConfig

ReplicatorConfig converts d into a ReplicatorConfig carrying its kind-to-prefab-name map and SpawnLimit.

func (*ReplicationDocument) Validate

func (d *ReplicationDocument) Validate() error

Validate checks that d uses ReplicationConfigVersion, has a non-negative SpawnLimit, has unique non-zero prefab kinds with valid names, and has uniquely named components with valid sync, interpolation, and owner rules. Errors are *loaderr.Error values naming the field at fault.

type ReplicationStats

type ReplicationStats struct {
	BytesSent          uint64
	PacketsSent        uint64
	SnapshotsSent      uint64
	FullSnapshotsSent  uint64
	DeltaSnapshotsSent uint64
	AvgBytesPerTick    float64
	// SnapshotsDeferred counts the times Step held a peer's snapshot back because the peer's budget (SetPeerBudget) could not cover it, and BytesDeferred their sizes. A snapshot held back on several ticks counts once per tick.
	SnapshotsDeferred uint64
	BytesDeferred     uint64
}

ReplicationStats reports cumulative bandwidth and snapshot metrics for ServerWorld.

type ReplicatorConfig

type ReplicatorConfig struct {
	Prefabs    map[uint16]string
	SpawnLimit int
}

ReplicatorConfig describes prefab kinds and spawn limits for world replication.

func (ReplicatorConfig) Validate

func (c ReplicatorConfig) Validate() error

Validate checks prefab mappings and limits.

type RollbackConfig

type RollbackConfig struct {
	Transport        Transport
	Sim              SimState
	Peers            []PeerID
	MaxRollback      int
	InputDelay       int
	ChecksumInterval int
	OnDesync         func(DesyncEvent)
	// Host is the peer that admits and removes peers while the match runs, with AddPeer and RemovePeer. Zero means the lowest ID of Peers, leaving out the local peer when Join is set; a joining session that finds no other peer there, or that names itself, takes the lowest other ID the transport reports on each Poll until its join state arrives. Set it explicitly when joining over a relay, whose peer list may still be empty or include other newcomers. Every peer of a match must name the same host, and the host stays for the whole match.
	Host PeerID
	// Join starts the session as a peer joining a match already running. It takes no part until the host's join state arrives with the tick it joins at, the peers and the simulation's state, which it loads into Sim; until then Step only polls and Active reports false. Peers then only serves to find the host when Host is zero.
	Join bool
}

RollbackConfig configures a GGPO-style RollbackSession.

type RollbackSession

type RollbackSession struct {
	// contains filtered or unexported fields
}

RollbackSession runs a GGPO-style optimistic deterministic simulation: missing remote inputs are predicted by repeating the last confirmed input, pre-step snapshots are kept in a ring window, late divergent inputs trigger rollback + deterministic re-simulation, and confirmed ticks exchange periodic state checksums for immediate desync detection.

Peers may join and leave while the match runs: the host admits one with AddPeer and removes one with RemovePeer, and every peer applies the change at the same tick, rolling back when it has already simulated past it.

Example

A RollbackSession steps at once with a prediction of each remote input (the peer's last one) and, when the real input arrives and differs, rolls back and re-simulates, so peers end in the same state without waiting on the network.

package main

import (
	"encoding/binary"
	"fmt"
	"time"

	"github.com/nsgo-dev/game/pkg/online/netplay"
)

// tally is a tiny deterministic simulation: each tick adds every player's input bits to a running total.
type tally struct{ total uint64 }

func (s *tally) Step(inputs []netplay.InputFrame) {
	for _, in := range inputs {
		s.total += in.Bits
	}
}

func (s *tally) Save() []byte { return binary.LittleEndian.AppendUint64(nil, s.total) }

func (s *tally) Load(b []byte) error {
	s.total = binary.LittleEndian.Uint64(b)
	return nil
}

func (s *tally) Checksum() uint64 { return s.total }

func main() {
	hub := netplay.NewLoopbackHub(netplay.LoopbackConfig{Latency: 30 * time.Millisecond})
	simA, simB := &tally{}, &tally{}
	peers := []netplay.PeerID{1, 2}
	a := netplay.NewRollbackSession(netplay.RollbackConfig{Transport: hub.AddPeer(1), Sim: simA, Peers: peers, MaxRollback: 8})
	b := netplay.NewRollbackSession(netplay.RollbackConfig{Transport: hub.AddPeer(2), Sim: simB, Peers: peers, MaxRollback: 8})

	// Peer 2 presses 10 for two ticks, then changes to 20, which peer 1 has predicted wrongly by the time it arrives.
	bBits := []uint64{10, 10, 20, 20, 20, 20}
	for tick, bits := range bBits {
		_ = a.Step(netplay.InputFrame{Tick: uint32(tick), Peer: 1, Bits: 1})
		_ = b.Step(netplay.InputFrame{Tick: uint32(tick), Peer: 2, Bits: bits})
		hub.Advance(16 * time.Millisecond)
	}
	hub.Advance(100 * time.Millisecond)
	_ = a.Poll()
	_ = b.Poll()

	stats := a.Stats()
	fmt.Println(a.Tick(), simA.total, simB.total)
	fmt.Println(stats.Rollbacks > 0, stats.Mispredictions > 0, len(a.Desyncs()))
}
Output:
6 106 106
true true 0
Example (Physics)

A RollbackSession can keep a deterministic 2D physics.RigidWorld inside SimState: Save/Restore captures all rigid-body and joint solver state as JSON, and Checksum verifies peers remain bit-identical across rollbacks and re-simulations.

package main

import (
	"encoding/json"
	"fmt"
	"time"

	"github.com/nsgo-dev/game/pkg/online/netplay"
	"github.com/nsgo-dev/game/pkg/physics"
	"github.com/nsgo-dev/nsgo/core"
)

const (
	inputLeft  uint64 = 1 << 0
	inputRight uint64 = 1 << 1
	inputJump  uint64 = 1 << 2
)

// physics2DSim wraps a 2D physics.RigidWorld as a deterministic netplay.SimState.
type physics2DSim struct {
	world   *physics.RigidWorld
	players map[netplay.PeerID]*physics.RigidBody
}

func newPhysics2DSim() *physics2DSim {
	rw := &physics.RigidWorld{
		GravityY:         500,
		SolverIterations: 10,
	}
	floor := physics.NewStaticRigidBox(200, 300, 420, 20)
	floor.ID = 1
	leftWall := physics.NewStaticRigidBox(0, 150, 20, 320)
	leftWall.ID = 2
	rightWall := physics.NewStaticRigidBox(400, 150, 20, 320)
	rightWall.ID = 3

	p1 := physics.NewRigidBox(120, 240, 24, 24, 1.5)
	p1.ID = 101
	p1.Friction = 0.4
	p1.Restitution = 0.2

	p2 := physics.NewRigidBox(280, 240, 24, 24, 1.5)
	p2.ID = 102
	p2.Friction = 0.4
	p2.Restitution = 0.2

	crate := physics.NewRigidBox(200, 220, 28, 28, 1.0)
	crate.ID = 103
	crate.Restitution = 0.3

	pivot := physics.NewStaticRigidBox(200, 90, 8, 8)
	pivot.ID = 4
	ball := physics.NewRigidCircle(235, 130, 12, 1.0)
	ball.ID = 104

	rw.AddBody(floor, leftWall, rightWall, pivot, p1, p2, crate, ball)
	rw.AddJoint(physics.NewDistanceJoint(pivot, ball, core.Point{}, core.Point{}, 65))
	rw.AddTrigger(&physics.Trigger{
		ID:    1,
		Shape: physics.BoxShape(physics.Box{X: 150, Y: 220, W: 100, H: 70}),
		Area: physics.AreaSettings{
			FluidLinearDrag: 1.5,
		},
	})

	return &physics2DSim{
		world: rw,
		players: map[netplay.PeerID]*physics.RigidBody{
			1: p1,
			2: p2,
		},
	}
}

func (s *physics2DSim) Step(inputs []netplay.InputFrame) {
	const dt = time.Second / 60
	for _, in := range inputs {
		b := s.players[in.Peer]
		if b == nil {
			continue
		}
		if in.Bits&inputLeft != 0 {
			b.ApplyForce(-700, 0)
		}
		if in.Bits&inputRight != 0 {
			b.ApplyForce(700, 0)
		}
		if in.Bits&inputJump != 0 && b.Y > 250 {
			b.ApplyImpulse(0, -260)
		}
	}
	s.world.Step(dt)
}

func (s *physics2DSim) Save() []byte {
	data, err := json.Marshal(s.world.Save())
	if err != nil {
		panic(err)
	}
	return data
}

func (s *physics2DSim) Load(snapshot []byte) error {
	var snap physics.RigidWorldSnapshot
	if err := json.Unmarshal(snapshot, &snap); err != nil {
		return err
	}
	return s.world.Restore(snap)
}

func (s *physics2DSim) Checksum() uint64 {
	return s.world.Checksum()
}

func main() {
	hub := netplay.NewLoopbackHub(netplay.LoopbackConfig{Latency: 32 * time.Millisecond, Seed: 7})
	simA, simB := newPhysics2DSim(), newPhysics2DSim()
	peers := []netplay.PeerID{1, 2}

	sessA := netplay.NewRollbackSession(netplay.RollbackConfig{
		Transport:        hub.AddPeer(1),
		Sim:              simA,
		Peers:            peers,
		MaxRollback:      16,
		ChecksumInterval: 10,
	})
	sessB := netplay.NewRollbackSession(netplay.RollbackConfig{
		Transport:        hub.AddPeer(2),
		Sim:              simB,
		Peers:            peers,
		MaxRollback:      16,
		ChecksumInterval: 10,
	})

	for tick := uint32(0); tick < 60; tick++ {
		var bitsA, bitsB uint64
		if tick%20 < 10 {
			bitsA = inputRight
		} else {
			bitsA = inputLeft | inputJump
		}
		if tick%15 < 8 {
			bitsB = inputLeft
		} else {
			bitsB = inputRight | inputJump
		}
		_ = sessA.Step(netplay.InputFrame{Bits: bitsA})
		_ = sessB.Step(netplay.InputFrame{Bits: bitsB})
		hub.Advance(time.Second / 60)
	}
	hub.Advance(200 * time.Millisecond)
	_ = sessA.Poll()
	_ = sessB.Poll()

	fmt.Println(
		sessA.Tick(),
		simA.Checksum() == simB.Checksum(),
		sessA.Stats().Rollbacks > 0,
		len(sessA.Desyncs()),
		len(sessB.Desyncs()),
	)
}
Output:
60 true true 0 0

func NewRollbackSession

func NewRollbackSession(cfg RollbackConfig) *RollbackSession

NewRollbackSession creates a GGPO-style rollback session.

func (*RollbackSession) Active

func (s *RollbackSession) Active() bool

Active reports whether the local peer takes part in the current tick: false while a joining peer waits for its join state, and from the tick the host removed the local peer at.

func (*RollbackSession) AddPeer

func (s *RollbackSession) AddPeer(id PeerID) (uint32, error)

AddPeer admits a peer to the running match and returns the tick it joins at. Only the host may call it, typically when its transport reports the peer (PeerJoined, or a new member in a RelayTransport's Peers). The tick is the one the host's next local input applies to (Tick plus InputDelay), so no peer has confirmed it yet; a peer that has already simulated past it rolls back. The new peer's inputs for its first InputDelay ticks are zero on every peer. Once the host has confirmed every tick before the join tick, it sends the new peer the state at the start of that tick, which must be no larger than MaxJoinStateSize, the tick and the peers.

Adding a peer that already takes part returns its join tick. It returns ErrNotHost on any other peer, ErrPeerRejoin for a peer that has left, ErrUnknownPeer for ID 0 and ErrPayloadTooLarge when the state is larger than MaxJoinStateSize.

func (*RollbackSession) ConfirmedTick

func (s *RollbackSession) ConfirmedTick() int64

ConfirmedTick returns the highest tick for which all peers' inputs are confirmed, or -1 if no tick is fully confirmed yet.

func (*RollbackSession) Desyncs

func (s *RollbackSession) Desyncs() []DesyncEvent

Desyncs returns a copy of the most recent DesyncEvents detected, up to maxDesyncHistory of them; OnDesync and Stats().Desyncs still count every one.

func (*RollbackSession) Members

func (s *RollbackSession) Members() []PeerID

Members returns the sorted IDs of the peers taking part in the current tick; it is empty while a joining peer waits for its join state.

func (*RollbackSession) Poll

func (s *RollbackSession) Poll() error

Poll drains incoming remote inputs, checksums and membership messages from the Transport, rolling back and re-simulating if any late remote input or membership change diverges from what was previously simulated. It first sends again the messages kept for peers the transport could not reach, and returns ErrSessionBacklog once for a peer that more such messages wait for than a session keeps: that peer misses the messages sent to it from then on.

func (*RollbackSession) RemovePeer

func (s *RollbackSession) RemovePeer(id PeerID) (uint32, error)

RemovePeer removes a peer from the running match and returns the tick from which no peer waits for or predicts it. Only the host may call it, typically once its transport reports the peer gone (PeerLeft, or a RelayTransport's Peers no longer listing it). The tick is the one the host's next local input applies to, or the peer's join tick, whichever is later. The change carries the inputs the host holds from the peer and a zero input for each unconfirmed tick the host never received, so every peer confirms those ticks alike, rolling back where it predicted otherwise; a peer still sending when removed may have reached another peer with an input the host never saw, so remove a peer after it has stopped sending.

Removing a peer that is already leaving, or that left, returns its leave tick. It returns ErrNotHost on any other peer, ErrHostLeave for the host, ErrUnknownPeer for a peer not in the match, and ErrRollbackWindowExceeded when the host would have to roll back further than MaxRollback or the change would carry more inputs than fit one message.

func (*RollbackSession) Stats

func (s *RollbackSession) Stats() RollbackStats

Stats returns a snapshot of the rollback session's metrics.

func (*RollbackSession) Step

func (s *RollbackSession) Step(localInput InputFrame) error

Step submits the local input (applied at currentTick + InputDelay), drains incoming packets (executing any needed rollbacks), simulates the next tick, and exchanges checksums for newly confirmed ticks. While the local peer takes no part (see Active) it only polls. While the oldest unconfirmed tick is MaxRollback ticks back it only polls too, ignoring localInput, and returns ErrRollbackStalled, naming each peer the tick waits for (see Waiting), until the missing inputs arrive or the host removes those peers. It returns ErrSessionBacklog, after simulating the tick or instead of ErrRollbackStalled, when a remote peer has become unreachable for too long (see Poll).

func (*RollbackSession) SuggestedWait

func (s *RollbackSession) SuggestedWait() int

SuggestedWait returns the number of simulation ticks the local peer is estimated to be running ahead of the slowest active remote peer, based on frame advantages exchanged alongside inputs. Zero means the local peer is synchronized or behind and should step normally; a positive value means the local peer should slow down (for example with Loop.SetTimeScale) or skip a step while continuing to Poll until SuggestedWait returns 0.

func (*RollbackSession) Tick

func (s *RollbackSession) Tick() uint32

Tick returns the current simulation tick (number of ticks executed so far). A joining peer's count starts at its join tick.

func (*RollbackSession) Waiting

func (s *RollbackSession) Waiting() []PeerID

Waiting returns the sorted IDs of the remote peers whose input the oldest unconfirmed tick still waits for. While Step returns ErrRollbackStalled these are the peers holding the match; one that stays there, having stopped sending or become unreachable, is for the host to remove with RemovePeer.

type RollbackStats

type RollbackStats struct {
	Rollbacks         int
	MaxRollbackDepth  int
	ResimulatedFrames int
	Predictions       int
	Mispredictions    int
	Desyncs           int
}

RollbackStats tracks runtime rollback and prediction metrics.

type Router

type Router struct {
	// contains filtered or unexported fields
}

Router owns a Transport, drains its incoming packets in arrival order during Poll, and demultiplexes them by a leading uvarint MessageID to per-consumer Sub views and typed application handlers through an optional middleware chain.

Once a Transport is wrapped by NewRouter, callers should not call tx.Recv directly; call Router.Poll once per tick instead.

func NewRouter

func NewRouter(tx Transport) *Router

NewRouter creates a Router that owns tx and demultiplexes packets on it. When tx is a *LoopbackTransport, the router's clock defaults to its LoopbackHub's deterministic virtual clock; otherwise it defaults to time.Now.

func (*Router) CallRaw

func (r *Router) CallRaw(to PeerID, method MessageID, body []byte, opts CallOptions, done func(body []byte, err error))

CallRaw sends a raw RPC request for method (>= 16) to peer on ChannelReliableOrdered. It never blocks; done runs from Router.Poll on a later tick with either the response payload and nil error, or nil payload and a *Status error.

func (*Router) Close

func (r *Router) Close() error

Close closes every Sub view created from r and closes the underlying transport.

func (*Router) Dispatch

func (r *Router) Dispatch(pkt Packet) error

Dispatch decodes the envelope of a single already-received packet and dispatches it through r's middleware to its registered handler or Sub view. It returns ErrClosed when r is nil or closed, ErrInvalidPacket for malformed envelopes, ErrUnknownMessageID when no route is registered for the decoded ID, or the error returned by middleware/handler.

func (*Router) HandlePeerEvent

func (r *Router) HandlePeerEvent(ev PeerEvent)

HandlePeerEvent updates r's RPC state for a peer lifecycle event. On PeerLeft, it clears the peer's server deduplication cache and queues CodeUnavailable for any pending outgoing calls to that peer (delivered on the next Poll). On PeerResumed, it resends pending outgoing calls to that peer (or all peers when ev.Peer is PeerBroadcast) with their original request IDs.

Callers that drain PeerEvents via Router.NextEvent get this automatically; callers that drain NextEvent on the underlying transport directly (or tests using LoopbackHub) call HandlePeerEvent for each lifecycle event.

func (*Router) HandleRaw

func (r *Router) HandleRaw(id MessageID, fn Handler)

HandleRaw registers a raw payload handler for application message id (>= 16). It panics if id is 0, in the reserved range 1..15, already registered, or if fn is nil.

func (*Router) LinkStats

func (r *Router) LinkStats(peer PeerID) (LinkStats, bool)

LinkStats forwards per-peer link quality metrics from the underlying transport when it implements LinkReporter.

func (*Router) LocalID

func (r *Router) LocalID() PeerID

LocalID returns the local peer's ID from the underlying transport, or 0 when nil.

func (*Router) NextEvent

func (r *Router) NextEvent() (PeerEvent, bool)

NextEvent drains the next peer lifecycle event from the underlying transport when it implements PeerEvents, applies RPC lifecycle hooks (clearing a peer's dedup cache on PeerLeft and resending pending calls on PeerResumed), and returns the event to the caller without consuming it.

func (*Router) Now

func (r *Router) Now() time.Time

Now returns the router's current clock time.

func (*Router) Peers

func (r *Router) Peers() []PeerID

Peers returns the connected remote peers from the underlying transport.

func (*Router) Poll

func (r *Router) Poll() int

Poll drains every waiting packet from the underlying transport in arrival order and dispatches each packet through middleware to its registered handler or Sub view. Unknown IDs and malformed envelopes are counted and dropped without stopping the drain. When RPC is active on r, Poll also detects client session resumes to resend pending requests with their original IDs and expires calls past their deadline on r's clock. Returns the number of matched packets dispatched.

func (*Router) RPCStats

func (r *Router) RPCStats() RPCStats

RPCStats returns a snapshot of RPC counters and cache occupancy for r.

func (*Router) SendManyRaw

func (r *Router) SendManyRaw(peers []PeerID, ch Channel, id MessageID, payload []byte) (failed []PeerID, err error)

SendManyRaw frames payload once with envelope id and fans it out via SendMany on the underlying transport.

func (*Router) SendRaw

func (r *Router) SendRaw(to PeerID, ch Channel, id MessageID, payload []byte) error

SendRaw frames payload with envelope id and sends it on the underlying transport.

func (*Router) ServeRaw

func (r *Router) ServeRaw(method MessageID, fn func(from PeerID, body []byte) ([]byte, error))

ServeRaw registers a raw byte-slice RPC handler for method (>= 16) on r. The handler runs from Router.Poll on the match tick.

Returning a *Status sends its Code and Message back to the caller; returning any other non-nil error sends CodeInternal with an empty message so server internals never leak (while reporting the error to Router.SetOnError). Results are cached per peer (up to SetRPCCacheSize, default 64) keyed by request ID so retries after resume return the cached response without running fn again.

ServeRaw panics if r or fn is nil, if method is 0 or <= ReservedMessageIDMax, or if method is already registered for RPC on r.

func (*Router) SetClock

func (r *Router) SetClock(now func() time.Time)

SetClock sets the clock used for RPC deadlines on r. Passing nil restores the transport's default clock (LoopbackHub.Now for *LoopbackTransport, time.Now otherwise).

func (*Router) SetOnError

func (r *Router) SetOnError(fn func(id MessageID, pkt Packet, err error))

SetOnError sets an optional observer invoked whenever a matched handler or middleware returns a non-nil error during Poll or Dispatch.

func (*Router) SetRPCCacheSize

func (r *Router) SetRPCCacheSize(n int)

SetRPCCacheSize sets the maximum number of recent RPC results cached per peer for request deduplication on r. Zero uses DefaultRPCCacheSize (64); a negative value disables caching. Lowering the limit evicts each peer's oldest cached entries immediately.

func (*Router) Stats

func (r *Router) Stats() RouterStats

Stats returns a snapshot of the router's packet counters.

func (*Router) Sub

func (r *Router) Sub(id MessageID) *SubTransport

Sub registers and returns a per-consumer Transport view bound to id. Outgoing packets sent on the view are framed with uvarint(id); incoming packets arriving with id pass through r's middleware and are queued into the view's inbox with the envelope stripped.

Sub accepts reserved built-in IDs (KindReplication..KindRelay, 1..15) as well as explicit application IDs (>= 16). It panics if id is 0 or already registered.

func (*Router) Transport

func (r *Router) Transport() Transport

Transport returns the underlying Transport owned by r. Callers must not invoke Recv on it while r is active.

func (*Router) Use

func (r *Router) Use(mw ...Middleware)

Use appends middleware to r's dispatch chain. Middleware runs outer-to-inner in the order registered (the first Use wraps the second, which wraps the route handler) and applies to all registered handlers and Sub views regardless of registration order. Passing a nil middleware panics.

type RouterStats

type RouterStats struct {
	// Dispatched counts packets matched to a registered handler or Sub view.
	Dispatched uint64
	// UnknownIDs counts packets with a valid envelope whose MessageID had no
	// registered handler or open Sub view; these packets are dropped and never
	// passed to any handler.
	UnknownIDs uint64
	// Malformed counts packets whose envelope varint was missing, truncated,
	// overflowed uint64, or decoded to 0.
	Malformed uint64
	// HandlerErrors counts dispatches whose handler or middleware returned a non-nil error.
	HandlerErrors uint64
}

RouterStats reports monotonically increasing packet routing counters for a Router.

type ServerWorld

type ServerWorld struct {

	// OnOwnerUpdate validates an incoming state update from the current owner of id.
	// next starts as the server's current state with only the client-owned fields
	// replaced from the owner's packet (server-only fields stay untouched). Returning
	// true accepts next (including any clamping OnOwnerUpdate applied to next);
	// returning false rejects the update so the server's copy wins and the owning
	// client is corrected in the next snapshot. A nil callback accepts every
	// update from the current owner.
	OnOwnerUpdate func(peer PeerID, id EntityID, next *EntityState) bool
	// contains filtered or unexported fields
}

ServerWorld owns authoritative entity state and replicates compact full and bitmask-delta snapshots to connected peers over a Transport.

Entities may be server-owned (Owner == 0, the default) or owned by a connected client (Spawn with Owner(peer), or SetOwner). The owning client publishes unreliable updates via ClientWorld.Publish, which ServerWorld validates with OnOwnerUpdate before applying and replicating to other peers.

Every snapshot carries the server's replication epoch, a number NewServerWorld picks at random, so a ClientWorld notices that a restarted server's snapshots come from a new run and starts over on its own.

Example

A ServerWorld owns the authoritative entities and sends each client a full snapshot, then bitmask deltas once the client acknowledges; a ClientWorld applies them, calls OnSpawn and OnDespawn, and interpolates between snapshots for drawing.

package main

import (
	"fmt"
	"time"

	"github.com/nsgo-dev/game/pkg/online/netplay"
)

func main() {
	hub := netplay.NewLoopbackHub(netplay.LoopbackConfig{Latency: 16 * time.Millisecond})
	srv := netplay.NewServerWorld(hub.AddPeer(1))
	cli := netplay.NewClientWorld(hub.AddPeer(2), 1)
	cli.OnSpawn = func(e netplay.EntityState) { fmt.Printf("spawn %d %q\n", e.ID, e.Props) }
	cli.OnDespawn = func(id netplay.EntityID) { fmt.Println("despawn", id) }

	hero := srv.Spawn(netplay.EntityState{ComponentState: netplay.ComponentState{Kind: 1, Props: []byte("hero")}})
	coin := srv.Spawn(netplay.EntityState{ComponentState: netplay.ComponentState{Kind: 2, X: 100}})
	for tick := uint32(1); tick <= 3; tick++ {
		srv.Update(hero, netplay.EntityState{ComponentState: netplay.ComponentState{Kind: 1, X: float32(tick * 10), Props: []byte("hero")}})
		if tick == 3 {
			srv.Despawn(coin)
		}
		_ = srv.Step(tick)
		hub.Advance(16 * time.Millisecond)
		cli.Poll()
		hub.Advance(16 * time.Millisecond) // the acknowledgment reaches the server
	}

	e, _ := cli.Entity(hero)
	latest, _ := cli.LatestTick()
	fmt.Println("tick", latest, "hero x", e.X)
	for _, s := range cli.Interpolate(2.5) {
		fmt.Println("at tick 2.5:", s.ID, s.X)
	}
	stats := srv.Stats()
	fmt.Println(stats.FullSnapshotsSent >= 1, stats.DeltaSnapshotsSent >= 1)
}
Output:
spawn 1 "hero"
spawn 2 ""
despawn 2
tick 3 hero x 30
at tick 2.5: 1 25
true true

func NewServerWorld

func NewServerWorld(transport Transport) *ServerWorld

NewServerWorld creates a new authoritative replication world backed by transport, with a random replication epoch. Two runs pick the same epoch with a chance of one in 2^32; SetEpoch takes a number the game chooses instead.

func (*ServerWorld) Despawn

func (w *ServerWorld) Despawn(id EntityID) bool

Despawn removes an entity from the authoritative world. Returns false if id does not exist.

func (*ServerWorld) Entities

func (w *ServerWorld) Entities() []EntityState

Entities returns all active entities sorted by EntityID.

func (*ServerWorld) Entity

func (w *ServerWorld) Entity(id EntityID) (EntityState, bool)

Entity returns a copy of the authoritative state for id.

func (*ServerWorld) Epoch

func (w *ServerWorld) Epoch() uint32

Epoch returns the replication epoch every snapshot of this world carries.

func (*ServerWorld) PeerBudget

func (w *ServerWorld) PeerBudget() (bytesPerSecond, ticksPerSecond int)

PeerBudget returns the per-peer byte rate and tick rate SetPeerBudget configured, with the default tick rate when SetPeerBudget was given 0 or less. A zero byte rate means replication is unlimited.

func (*ServerWorld) PeerErr

func (w *ServerWorld) PeerErr(peer PeerID) error

PeerErr returns why the last replication message from peer could not be used, an error wrapping ErrReplicationVersion when the peer speaks another version of the replication protocol, or nil. A server can drop such a peer with a message to update the game. It clears when the peer sends a message of ReplicationVersion, and is forgotten when the peer disconnects.

func (*ServerWorld) SetEpoch

func (w *ServerWorld) SetEpoch(epoch uint32)

SetEpoch replaces the replication epoch, for a server that keeps its own run counter or starts a new match with its tick count back at zero. Clients drop every snapshot and prediction of the old epoch and resync from a full snapshot of the new one, which SetEpoch makes the next Step send to every peer by forgetting the snapshot history and acknowledgments. A client ignores late snapshots of the epochs it has left, so an epoch must not repeat: setting one a client has already left makes that client ignore the server. Setting the current epoch does nothing.

func (*ServerWorld) SetInterest

func (w *ServerWorld) SetInterest(visible func(peer PeerID, e EntityState) bool)

SetInterest filters which entities each peer receives in Step. Passing nil (the default) restores unfiltered replication where every peer sees every entity and full snapshots are encoded once per Step and shared across peers.

When a filter is active, each peer's delta baseline is the authoritative snapshot at its acknowledged tick restricted to the entity IDs sent to that peer on that tick: entities leaving a peer's interest become despawns for that peer only, and entities entering or re-entering arrive with full state. Setting a predicate clears any provider attached via SetInterestProvider.

func (*ServerWorld) SetInterestProvider

func (w *ServerWorld) SetInterestProvider(p InterestProvider)

SetInterestProvider attaches a spatial or indexed InterestProvider (such as *GridInterest) so Step prepares the index once per tick and queries only each peer's visible entities instead of scanning every entity per peer. Passing nil removes the provider and restores the default unfiltered behavior. Setting a provider clears any predicate attached via SetInterest.

func (*ServerWorld) SetLayouts

func (w *ServerWorld) SetLayouts(doc *LayoutDocument) error

SetLayouts attaches a validated LayoutDocument whose per-field owner settings ("client" vs "server") govern which ComponentState fields a client-owned entity's owner may update; all other fields stay server-only and are never accepted from a client. Passing nil clears the layouts so all mutable ComponentState fields (except Kind and Owner) may be updated by the owner.

func (*ServerWorld) SetMaxSnapshotSize

func (w *ServerWorld) SetMaxSnapshotSize(n int)

SetMaxSnapshotSize sets the largest payload Step passes to Transport.Send. A full snapshot larger than n is split into parts of at most n bytes, which ClientWorld reassembles before applying, and a delta larger than n is replaced by a full snapshot split the same way. Without the split, a world that outgrew the transport's packet limit could never reach a new peer again (#546). Zero restores DefaultMaxSnapshotSize, and a value below 256 is raised to 256.

func (*ServerWorld) SetOwner

func (w *ServerWorld) SetOwner(id EntityID, owner PeerID) bool

SetOwner transfers authority over id to owner (PeerID(0) returns authority to the server). The new owner is replicated on the next Step, immediately stops accepting updates from the previous owner, and resets sequence tracking for the new owner. Returns false if id does not exist.

func (*ServerWorld) SetPeerBudget

func (w *ServerWorld) SetPeerBudget(bytesPerSecond, ticksPerSecond int)

SetPeerBudget limits the replication bytes Step sends each peer to bytesPerSecond on average, for a server that calls Step ticksPerSecond times a second (60 when ticksPerSecond is 0 or less). Each peer has a token bucket that fills by bytesPerSecond/ticksPerSecond every Step and holds at most one second's worth; a peer's snapshot is sent whole when the bucket covers it and held back otherwise, so the next Step sends a newer one. A snapshot larger than a second's worth is sent once the bucket is full and leaves it in debt, so no peer is starved however large the world grows. A new peer starts with a full bucket and gets its first snapshot at once. Held-back snapshots are counted in Stats().SnapshotsDeferred and BytesDeferred. A bytesPerSecond of 0 or less removes the limit.

func (*ServerWorld) Spawn

func (w *ServerWorld) Spawn(state EntityState, opts ...SpawnOption) EntityID

Spawn creates a new entity with the given initial state and optional SpawnOptions (such as Owner(peer)) and returns its assigned EntityID. By default the server owns the entity (Owner == 0).

func (*ServerWorld) Stats

func (w *ServerWorld) Stats() ReplicationStats

Stats returns cumulative replication bandwidth and snapshot statistics.

func (*ServerWorld) Step

func (w *ServerWorld) Step(tick uint32) error

Step processes disconnected peers (returning their client-owned entities to the server), incoming client acknowledgments and validated owner updates, records the world snapshot for tick, and transmits either a full snapshot (for new or resyncing peers) or a bitmask delta snapshot (for acknowledged peers, skipping echoed client-owned fields unless corrected) over the Transport.

func (*ServerWorld) Update

func (w *ServerWorld) Update(id EntityID, state EntityState) bool

Update replaces the ComponentState of an existing entity while preserving its Owner (use SetOwner to transfer authority). If the entity is client-owned and Update modifies any client-owned field, the owning client is sent the authoritative state on the next Step. Returns false if id does not exist.

type SimState

type SimState interface {
	// Step advances the simulation by one fixed tick using inputs sorted by PeerID.
	Step(inputs []InputFrame)
	// Save serializes the complete deterministic simulation state.
	Save() []byte
	// Load restores the complete simulation state from a snapshot returned by Save.
	Load(snapshot []byte) error
	// Checksum returns a deterministic 64-bit hash of the current simulation state.
	Checksum() uint64
}

SimState is the deterministic simulation interface driven by LockstepSession and RollbackSession.

type SpawnOption

type SpawnOption func(*EntityState)

SpawnOption configures an entity created by ServerWorld.Spawn.

func Owner

func Owner(peer PeerID) SpawnOption

Owner assigns initial client authority for an entity spawned with ServerWorld.Spawn. PeerID(0) (the default) leaves authority with the server.

type Status

type Status struct {
	Code    Code
	Message string
}

Status is a structured RPC error carrying a stable status Code and an optional human-readable Message. Returning a *Status from a Serve handler transmits its code and message to the caller; any other non-nil error maps to CodeInternal with an empty message so server internals never leak.

func StatusError

func StatusError(code Code, message string) *Status

StatusError constructs a *Status error carrying code and message.

func (*Status) Error

func (s *Status) Error() string

Error implements error.

func (*Status) Is

func (s *Status) Is(target error) bool

Is matches context.DeadlineExceeded when s.Code == CodeDeadlineExceeded, and matches a target *Status with the same Code (and matching Message when target.Message is non-empty).

type SubTransport

type SubTransport struct {
	// contains filtered or unexported fields
}

SubTransport is a per-consumer Transport view backed by a Router. It implements Transport, Multicaster, and InboxReporter.

func (*SubTransport) Close

func (s *SubTransport) Close() error

Close closes only this SubTransport view without closing the Router or its underlying transport. Future packets arriving for this view's ID are dropped as unknown IDs.

func (*SubTransport) ID

func (s *SubTransport) ID() MessageID

ID returns the MessageID bound to this SubTransport view.

func (*SubTransport) InboxStats

func (s *SubTransport) InboxStats() InboxStats

InboxStats reports what this view's inbox holds and what its limits dropped or warned about.

func (*SubTransport) LinkStats

func (s *SubTransport) LinkStats(peer PeerID) (LinkStats, bool)

LinkStats forwards per-peer link quality metrics from the router's underlying transport.

func (*SubTransport) LocalID

func (s *SubTransport) LocalID() PeerID

LocalID returns the local peer ID from the underlying transport.

func (*SubTransport) Peers

func (s *SubTransport) Peers() []PeerID

Peers returns the connected remote peers from the underlying transport, or nil when closed.

func (*SubTransport) Recv

func (s *SubTransport) Recv() (Packet, bool)

Recv pops the next packet routed to this view without blocking. The returned packet's Payload has the router envelope ID stripped.

func (*SubTransport) Send

func (s *SubTransport) Send(to PeerID, ch Channel, payload []byte) error

Send frames payload with s.ID() and transmits it on the router's underlying transport.

func (*SubTransport) SendMany

func (s *SubTransport) SendMany(peers []PeerID, ch Channel, payload []byte) (failed []PeerID, err error)

SendMany frames payload once with s.ID() and fans it out to peers on the underlying transport.

func (*SubTransport) SetInboxLimits

func (s *SubTransport) SetInboxLimits(l InboxLimits)

SetInboxLimits bounds the packets buffered in this view's inbox until Recv takes them.

type SyncMode

type SyncMode = LayoutSyncMode

SyncMode is the short public name used by generated layout metadata.

type Transport

type Transport interface {
	Send(to PeerID, ch Channel, payload []byte) error
	Recv() (Packet, bool)
	LocalID() PeerID
	Peers() []PeerID
	Close() error
}

Transport is the cross-target messaging interface consumed by replication and lockstep/rollback sessions.

Recv is strictly non-blocking so games can drain incoming packets directly inside a fixed-step game.Loop Update callback without stalling a frame.

A transport has a single consumer. Recv hands each packet to exactly one caller, and the consumers in this package (ServerWorld, ClientWorld, LockstepSession, RollbackSession, Relay and RelayTransport) drain every packet waiting on the transport and discard the ones that are not theirs. Two of them reading the same transport therefore steal each other's packets. To share one transport across multiple consumers and application messages, wrap it in NewRouter and pass r.Sub(KindReplication), r.Sub(KindRollback), and so on to each consumer.

Every transport in this package bounds its inbox and reports on it through InboxReporter: a peer's unreliable packets past a cap are dropped oldest first, a WebSocketServer ends the session of a client whose reliable packets pass a cap, and a reliable backlog past a threshold is counted as a warning (see InboxLimits).

func DialWebTransportWithFallback

func DialWebTransportWithFallback(wtURL, wsURL string, token []byte, opts WebTransportOptions) (Transport, error)

DialWebTransportWithFallback dials rawURL over WebTransport and falls back to DialWebSocket(wsURL, token) when WebTransport cannot connect. Handshake rejections (ErrRejected) and ErrTokenTooLarge are returned directly without falling back.

func NewCaptureTransport

func NewCaptureTransport(inner Transport, w io.Writer, opts CaptureOptions) Transport

NewCaptureTransport wraps inner and writes one JSON Lines CaptureRecord to w for every successful Send and every packet returned by Recv that matches opts.

Because it sits at the Transport boundary, wrapping UDPClient or UDPServer captures plaintext packets above authentication and encryption, so captures never need session keys.

The returned Transport also implements InboxReporter by forwarding SetInboxLimits and InboxStats to inner when inner implements InboxReporter.

Warning: captures contain raw player inputs and game state.

Example

NewCaptureTransport wraps any Transport and records each Send and Recv as one versioned JSON line for offline inspection with `game net decode`.

package main

import (
	"bytes"
	"fmt"
	"time"

	"github.com/nsgo-dev/game/pkg/online/netplay"
)

func main() {
	hub := netplay.NewLoopbackHub(netplay.LoopbackConfig{})
	p1 := hub.AddPeer(1)
	p2 := hub.AddPeer(2)

	now := time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC)
	var capture bytes.Buffer
	wrapped := netplay.NewCaptureTransport(p1, &capture, netplay.CaptureOptions{
		Now: func() time.Time { return now },
	})

	_ = wrapped.Send(2, netplay.ChannelReliableOrdered, []byte("ping"))
	now = now.Add(16 * time.Millisecond)
	_ = p2.Send(1, netplay.ChannelUnreliable, []byte("pong"))
	hub.Advance(time.Millisecond)
	_, _ = wrapped.Recv()

	records, err := netplay.ReadCapture(&capture)
	if err != nil {
		panic(err)
	}
	for _, r := range records {
		fmt.Printf("v=%d t=%dms dir=%s peer=%d ch=%s payload=%s\n", r.Version, r.T/1e6, r.Dir, r.Peer, r.Ch, string(r.Payload))
	}
}
Output:
v=1 t=0ms dir=send peer=2 ch=reliable-ordered payload=ping
v=1 t=16ms dir=recv peer=2 ch=unreliable payload=pong

type UDPClient

type UDPClient struct {
	// contains filtered or unexported fields
}

UDPClient is a native UDP Transport connected to a UDPServer. DialUDP authenticates the server and derives directional ChaCha20-Poly1305 session keys using a Noise NK handshake against the server's static X25519 public key. It supports ChannelReliableOrdered (plus extra reliable lanes via DialOptions.Channels or SetChannelConfig), ChannelUnreliable, and ChannelUnreliableSequenced, fragmenting payloads above ChannelConfig.MTU (default 1200 bytes) into numbered datagrams. The client pings the server while idle and reports itself disconnected when the server stays silent for 10 seconds; Reconnect runs a fresh Noise NK handshake to rekey the session and resume with the same ID within the server's grace period. DialUDPResume does the same from a stored ResumeToken after the client object is gone.

func DialUDP

func DialUDP(addr string, serverKey *ecdh.PublicKey, token []byte) (*UDPClient, error)

DialUDP connects to the UDPServer at addr, authenticates it with its static X25519 public key serverKey using Noise NK, presents token encrypted in the handshake, and returns once the server accepts it. The server assigns the client's ID, which LocalID reports. A missing or non-X25519 serverKey returns ErrInvalidKey; a refusal returns a *RejectError that matches ErrRejected.

func DialUDPResume

func DialUDPResume(addr string, serverKey *ecdh.PublicKey, token []byte, resume string) (*UDPClient, error)

DialUDPResume is DialUDP for a client that stored a ResumeToken, for example across an app restart. Within the server's grace period it resumes the session, keeping the peer ID, and Resumed reports true. Past it, or when the server replaced the token's secret, the handshake is a fresh join that Auth.Verify checks as usual. A malformed token returns ErrInvalidResumeToken without dialing.

func DialUDPWith

func DialUDPWith(addr string, serverKey *ecdh.PublicKey, o DialOptions) (*UDPClient, error)

DialUDPWith is DialUDP taking the client's options, so it can report its build string and resume a session with a resume token.

func (*UDPClient) ChannelConfig

func (c *UDPClient) ChannelConfig() ChannelConfig

ChannelConfig returns the client's active channel and fragmentation configuration.

func (*UDPClient) Close

func (c *UDPClient) Close() error

Close sends the server an authenticated goodbye, so it reports PeerLeft at once rather than holding the session for a reconnect, and closes the socket.

func (*UDPClient) CongestionConfig

func (c *UDPClient) CongestionConfig() CongestionConfig

CongestionConfig returns the client's active congestion control configuration.

func (*UDPClient) Err

func (c *UDPClient) Err() error

Err returns why the client is disconnected: a *RejectError, a handshake timeout, or ErrDisconnected wrapping the cause. It is nil while the connection is open.

func (*UDPClient) InboxStats

func (c *UDPClient) InboxStats() InboxStats

InboxStats reports what the client's inbox holds and what its limits dropped or warned about.

func (*UDPClient) LinkStats

func (c *UDPClient) LinkStats(peer PeerID) (LinkStats, bool)

LinkStats reports the client's measured RTT, RTT variance, sequence-gap packet loss, and byte/packet counters to the server.

func (*UDPClient) LocalID

func (c *UDPClient) LocalID() PeerID

LocalID returns the PeerID the server assigned this client.

func (*UDPClient) Peers

func (c *UDPClient) Peers() []PeerID

Peers returns the server's PeerID, or nil while disconnected or closed.

func (*UDPClient) Reconnect

func (c *UDPClient) Reconnect() error

Reconnect drops the current socket without a goodbye, opens a new one and runs a fresh Noise NK handshake to rekey the session and reset sequence numbers: within the server's grace period the client keeps its ID, and Resumed reports true. Past it, the server admits the client as a new peer when its token is still valid, and LocalID changes.

func (*UDPClient) Recv

func (c *UDPClient) Recv() (Packet, bool)

Recv pops the next authenticated and decrypted packet from the server without blocking.

func (*UDPClient) ResumeToken

func (c *UDPClient) ResumeToken() string

ResumeToken returns an opaque credential for the current session, empty before the first welcome on a fresh join. A client created with DialUDPResume reports the stored token until the first welcome replaces it. Store it after every handshake, because each one replaces the secret it carries, treat it like a password, and clear it after Close. DialUDPResume presents it.

func (*UDPClient) Resumed

func (c *UDPClient) Resumed() bool

Resumed reports whether the last handshake resumed an existing session, keeping the client's ID.

func (*UDPClient) Send

func (c *UDPClient) Send(to PeerID, ch Channel, payload []byte) error

Send encrypts and authenticates payload with the client-to-server ChaCha20-Poly1305 key and sends it to the server. It supports ChannelReliableOrdered (and extra reliable lanes configured via DialOptions.Channels or SetChannelConfig), ChannelUnreliable, and ChannelUnreliableSequenced, splitting payloads above ChannelConfig.MTU into numbered fragments. It returns ErrInvalidPacket for an undeclared channel, ErrPayloadTooLarge above maxUDPPayloadSize, ErrReliableBacklog when the channel's reliable window is full, ErrDisconnected while the connection is down, and ErrSequenceExhausted once the 32-bit sequence counter would wrap (call Reconnect to rekey).

func (*UDPClient) SetChannelConfig

func (c *UDPClient) SetChannelConfig(cfg ChannelConfig)

SetChannelConfig updates the client's reliable lane count, UDP MTU, and per-peer reassembly cap.

func (*UDPClient) SetCompression

func (c *UDPClient) SetCompression(cfg CompressionConfig) error

SetCompression updates the client's opt-in per-packet deflate compression settings and decompression cap. Even when Enabled is false, UDPClient still inflates compressed packets from the server up to MaxInflated (capped at maxUDPPayloadSize).

func (*UDPClient) SetCongestionConfig

func (c *UDPClient) SetCongestionConfig(cfg CongestionConfig)

SetCongestionConfig updates the client's send-rate bounds, initial rate, MTU, and over-budget unreliable policy.

func (*UDPClient) SetInboxLimits

func (c *UDPClient) SetInboxLimits(l InboxLimits)

SetInboxLimits bounds the packets the client keeps until Recv takes them (see InboxLimits).

func (*UDPClient) State

func (c *UDPClient) State() ConnState

State returns the connection state.

type UDPServer

type UDPServer struct {
	// contains filtered or unexported fields
}

UDPServer is a native UDP Transport for a server whose clients connect with DialUDP. Each client first echoes a stateless cookie the server sent to its address, proving it receives there, and then runs a Noise NK key exchange (handshake version 3) against the server's static X25519 key before its packets reach Recv; a hello without a valid cookie gets only the cookie, smaller than the hello, and takes no session slot and no Auth.Verify call. Then the token and resume secret travel encrypted, Auth.Verify checks the token, and the server assigns the client's ID in an encrypted welcome.

After the handshake every datagram is encrypted and authenticated with ChaCha20-Poly1305 using directional keys from the Noise split, a 10-byte cleartext header authenticated as associated data, an implicit direction||peer||seq nonce, and a 64-entry replay window that also refuses wrapped sequence numbers. A datagram from another address, with a bad tag, reflected from the opposite direction, or replayed is dropped.

UDPServer supports ChannelReliableOrdered (plus extra independent reliable lanes declared via Auth.Channels or SetChannelConfig), ChannelUnreliable, and ChannelUnreliableSequenced, automatically fragmenting payloads above ChannelConfig.MTU (default 1200 bytes) into numbered datagrams.

UDP has no connection, so a client that stays silent for Auth.IdleTimeout counts as dropped; DialUDP clients ping every second while idle.

func ListenUDPServer

func ListenUDPServer(addr string, serverID PeerID, auth Auth) (*UDPServer, error)

ListenUDPServer binds a UDP socket on addr for a server with ID serverID (1 when zero) and starts accepting DialUDP clients under auth. If auth.StaticKey is nil, ListenUDPServer generates a fresh X25519 key pair whose public key clients obtain from PublicKey; otherwise auth.StaticKey must use X25519 or ListenUDPServer returns ErrInvalidKey.

Example

ListenUDPServer and DialUDP establish an encrypted UDP session with a Noise NK key exchange against the server's static X25519 key, then encrypt and authenticate every datagram with ChaCha20-Poly1305.

package main

import (
	"crypto/ecdh"
	"crypto/rand"
	"fmt"
	"runtime"

	"github.com/nsgo-dev/game/pkg/online/netplay"
)

func main() {
	serverKey, _ := ecdh.X25519().GenerateKey(rand.Reader)
	srv, _ := netplay.ListenUDPServer("127.0.0.1:0", 1, netplay.Auth{StaticKey: serverKey})
	defer func() { _ = srv.Close() }()

	// Clients obtain the server's 32-byte X25519 public key out of band (e.g. matchmaking ticket or config).
	pubBytes := srv.PublicKey().Bytes()
	pubKey, _ := ecdh.X25519().NewPublicKey(pubBytes)

	cli, _ := netplay.DialUDP(srv.Addr().String(), pubKey, []byte("ticket"))
	defer func() { _ = cli.Close() }()

	_ = cli.Send(srv.LocalID(), netplay.ChannelUnreliable, []byte("move"))
	for {
		if pkt, ok := srv.Recv(); ok {
			fmt.Println("server got:", pkt.From, string(pkt.Payload))
			break
		}
		runtime.Gosched()
	}
}
Output:
server got: 2 move

func NewUDPServer

func NewUDPServer(conn stdnet.PacketConn, serverID PeerID, auth Auth) (*UDPServer, error)

NewUDPServer starts a UDPServer on a PacketConn the caller already opened, such as one bound with a custom net.ListenConfig. The server takes ownership of conn: Close closes it. serverID defaults to 1 when zero, and auth is validated as in ListenUDPServer.

Unlike TCP WebSocket listeners, a UDP PacketConn cannot be shared across two processes during a zero-downtime restart because two readers on one datagram socket split incoming packets at random. For UDP restarts, bind the replacement process on a fresh port and route new rooms there.

func (*UDPServer) Account

func (s *UDPServer) Account(peer PeerID) (string, bool)

Account returns the account Auth.Identify bound to peer's live or grace-period session. It returns ("", false) for anonymous peers, unknown peers, handshakes still in Identify, or after Close.

func (*UDPServer) Addr

func (s *UDPServer) Addr() stdnet.Addr

Addr returns the local bound UDP address.

func (*UDPServer) ChannelConfig

func (s *UDPServer) ChannelConfig() ChannelConfig

ChannelConfig returns the server's active channel and fragmentation configuration.

func (*UDPServer) Close

func (s *UDPServer) Close() error

Close closes the UDP socket.

func (*UDPServer) CongestionConfig

func (s *UDPServer) CongestionConfig() CongestionConfig

CongestionConfig returns the server's active congestion control configuration.

func (*UDPServer) Err

func (s *UDPServer) Err() error

Err returns why the server stopped receiving: ErrReceiveFailed wrapping the socket's error. Send returns the same error from then on, and clients time out as their datagrams go unread, so a game should close the server and listen again. It is nil while the server receives, and after Close. Errors about a single datagram, such as an ICMP port unreachable for an earlier send, do not stop it.

func (*UDPServer) ExtendGrace

func (s *UDPServer) ExtendGrace(peer PeerID, d time.Duration) error

ExtendGrace gives peer's session a grace period of at least d from its drop, clamped to Auth.MaxGracePeriod when that is nonzero. A game calls it to keep one peer's seat longer than Auth.GracePeriod, for example a ranked match that allows a dropped player more time to come back. Called while the peer is connected, it sets the window for its next drop; called inside its grace period, it extends the current one. It never shortens a window, and a non-positive d does nothing. ExtendGrace returns ErrUnknownPeer for an ID with no session (including a handshake still in Verify) and ErrClosed once the server is closed.

func (*UDPServer) InboxStats

func (s *UDPServer) InboxStats() InboxStats

InboxStats reports what the server's inbox holds and what its limits dropped or warned about.

func (*UDPServer) Kick

func (s *UDPServer) Kick(peer PeerID, reason string) error

Kick ends peer's session now: a connected client receives the reason in an encrypted kick datagram, sent udpKickCopies times since UDP may drop it, and the session's resume secret is gone, so the client's Reconnect cannot resume it and joins as a new peer only if Auth.Verify accepts its token again. NextEvent reports PeerLeft with the reason. It returns ErrUnknownPeer for an ID with no session (including a handshake still in Verify) and ErrClosed once the server is closed. A peer inside its grace period gets no datagram; its next datagram simply finds no session.

func (*UDPServer) LinkStats

func (s *UDPServer) LinkStats(peer PeerID) (LinkStats, bool)

LinkStats reports the per-peer RTT, RTT variance, sequence-gap packet loss, and byte/packet counters for a connected client.

func (*UDPServer) LocalID

func (s *UDPServer) LocalID() PeerID

LocalID returns the server's PeerID.

func (*UDPServer) NextEvent

func (s *UDPServer) NextEvent() (PeerEvent, bool)

NextEvent pops the next join, drop, resume or leave without blocking, after dropping clients silent for Auth.IdleTimeout and ending sessions whose grace period has passed.

func (*UDPServer) PeerByAccount

func (s *UDPServer) PeerByAccount(account string) (PeerID, bool)

PeerByAccount returns the PeerID of the live or grace-period session bound to account by Auth.Identify. It returns (0, false) for an empty account, an account with no session, or after Close.

func (*UDPServer) Peers

func (s *UDPServer) Peers() []PeerID

Peers returns the sorted IDs of connected clients. Clients inside their grace period are left out.

func (*UDPServer) PublicKey

func (s *UDPServer) PublicKey() *ecdh.PublicKey

PublicKey returns the server's static X25519 public key that clients pass to DialUDP.

func (*UDPServer) Recv

func (s *UDPServer) Recv() (Packet, bool)

Recv pops the next authenticated and decrypted packet without blocking.

func (*UDPServer) Send

func (s *UDPServer) Send(to PeerID, ch Channel, payload []byte) error

Send encrypts and authenticates payload with the client's server-to-client ChaCha20-Poly1305 key and sends it to the client (or all connected clients when to == PeerBroadcast). It supports ChannelReliableOrdered (and extra reliable lanes configured via Auth.Channels or SetChannelConfig), ChannelUnreliable, and ChannelUnreliableSequenced, splitting payloads larger than ChannelConfig.MTU into numbered fragments. It returns ErrInvalidPacket for an undeclared channel, ErrPayloadTooLarge above maxUDPPayloadSize, ErrReliableBacklog when a client's reliable window is full, ErrDisconnected for a client inside its grace period, ErrUnknownPeer for an ID with no session, and ErrSequenceExhausted if the session's 32-bit sequence counter would wrap.

func (*UDPServer) SetChannelConfig

func (s *UDPServer) SetChannelConfig(cfg ChannelConfig)

SetChannelConfig updates the server's reliable lane count, UDP MTU, and per-peer reassembly cap.

func (*UDPServer) SetCompression

func (s *UDPServer) SetCompression(cfg CompressionConfig) error

SetCompression updates the server's opt-in per-packet deflate compression settings and decompression cap. Even when Enabled is false, UDPServer still inflates compressed packets from peers up to MaxInflated (capped at maxUDPPayloadSize).

func (*UDPServer) SetCongestionConfig

func (s *UDPServer) SetCongestionConfig(cfg CongestionConfig)

SetCongestionConfig updates the server's per-peer send-rate bounds, initial rate, MTU, and over-budget unreliable policy.

func (*UDPServer) SetDraining

func (s *UDPServer) SetDraining(reason string, retryAfter time.Duration)

SetDraining switches the server into draining mode: new handshakes are refused with RejectMaintenance, reason ("draining" when empty), and retryAfter, while already-connected peers keep their sessions and dropped peers may still resume within their grace period. Calling it again updates the reason and retry hint.

func (*UDPServer) SetInboxLimits

func (s *UDPServer) SetInboxLimits(l InboxLimits)

SetInboxLimits bounds the packets the server keeps until Recv takes them (see InboxLimits).

type UDPTransport

type UDPTransport struct {
	// contains filtered or unexported fields
}

UDPTransport is an unreliable/sequenced native UDP Transport between peers that know each other's addresses in advance.

Peers registered with AddPeer use an unauthenticated 9-byte cleartext header (from PeerID + channel + sequence number) suited only for trusted LAN use and tests: a datagram is accepted if its source address matches the address registered for the PeerID it claims, which does not protect against IP spoofing or on-path observers.

Peers registered with AddPeerKey share a 32-byte pre-shared key and use the same ChaCha20-Poly1305 AEAD framing, 10-byte associated-data header, implicit nonce, 64-entry replay window and sequence-wrap refusal as UDPServer and UDPClient. A server whose clients are not known in advance uses ListenUDPServer and DialUDP, which run a Noise NK key exchange per session.

func ListenUDP

func ListenUDP(addr string, localID PeerID) (*UDPTransport, error)

ListenUDP binds a UDP socket on addr for localID and starts receiving datagrams.

func (*UDPTransport) AddPeer

func (u *UDPTransport) AddPeer(id PeerID, addr string) error

AddPeer registers or updates a remote peer's UDP address without cryptography (unauthenticated, for LAN use and tests). Datagrams claiming to be from id are accepted only from this address. Use AddPeerKey for authenticated encryption between peers with a pre-shared key.

func (*UDPTransport) AddPeerKey

func (u *UDPTransport) AddPeerKey(id PeerID, addr string, key [32]byte) error

AddPeerKey registers or updates a remote peer's UDP address with a 32-byte pre-shared ChaCha20-Poly1305 key. Datagrams exchanged with id use the same 26-byte AEAD framing, replay window, reflection protection and sequence-wrap refusal as UDPServer and UDPClient, and plaintext datagrams claiming to be from id are dropped. Calling AddPeerKey again resets the peer's sequence counter and replay window, allowing callers to rekey with a fresh key. An all-zero key returns ErrInvalidKey; id == 0 or id == LocalID returns ErrInvalidPacket.

Example

UDPTransport.AddPeerKey protects direct peer-to-peer UDP datagrams with ChaCha20-Poly1305 using a 32-byte pre-shared key, refusing tampered, replayed, reflected or plaintext datagrams.

package main

import (
	"crypto/rand"
	"fmt"
	"runtime"

	"github.com/nsgo-dev/game/pkg/online/netplay"
)

func main() {
	a, _ := netplay.ListenUDP("127.0.0.1:0", 1)
	defer func() { _ = a.Close() }()
	b, _ := netplay.ListenUDP("127.0.0.1:0", 2)
	defer func() { _ = b.Close() }()

	var key [32]byte
	_, _ = rand.Read(key[:])
	_ = a.AddPeerKey(2, b.Addr().String(), key)
	_ = b.AddPeerKey(1, a.Addr().String(), key)

	_ = a.Send(2, netplay.ChannelUnreliable, []byte("ping"))
	for {
		if pkt, ok := b.Recv(); ok {
			fmt.Println("peer 2 got:", pkt.From, string(pkt.Payload))
			break
		}
		runtime.Gosched()
	}
}
Output:
peer 2 got: 1 ping

func (*UDPTransport) Addr

func (u *UDPTransport) Addr() stdnet.Addr

Addr returns the local bound UDP address.

func (*UDPTransport) Close

func (u *UDPTransport) Close() error

Close closes the underlying UDP socket.

func (*UDPTransport) Err

func (u *UDPTransport) Err() error

Err returns why the transport stopped receiving: ErrReceiveFailed wrapping the socket's error. Send returns the same error from then on. It is nil while the transport receives, and after Close. Errors about a single datagram, such as an ICMP port unreachable for an earlier send, do not stop it.

func (*UDPTransport) InboxStats

func (u *UDPTransport) InboxStats() InboxStats

InboxStats reports what the transport's inbox holds and what its limits dropped or warned about.

func (*UDPTransport) LinkStats

func (u *UDPTransport) LinkStats(peer PeerID) (LinkStats, bool)

LinkStats reports sequence-gap packet loss and byte/packet counters for a registered peer.

func (*UDPTransport) LocalID

func (u *UDPTransport) LocalID() PeerID

LocalID returns this endpoint's PeerID.

func (*UDPTransport) Peers

func (u *UDPTransport) Peers() []PeerID

Peers returns the sorted list of known remote PeerIDs.

func (*UDPTransport) Recv

func (u *UDPTransport) Recv() (Packet, bool)

Recv pops the next received UDP packet without blocking.

func (*UDPTransport) RemovePeer

func (u *UDPTransport) RemovePeer(id PeerID)

RemovePeer removes a remote peer from the routing table.

func (*UDPTransport) Send

func (u *UDPTransport) Send(to PeerID, ch Channel, payload []byte) error

Send transmits payload in a single UDP datagram to the target peer (or all registered peers when to == PeerBroadcast). Keyed peers registered with AddPeerKey receive AEAD-sealed datagrams and return ErrSequenceExhausted once their 32-bit sequence counter would wrap.

UDPTransport has no acknowledgement or retransmission, so reliable channels are refused with ErrUnsupportedChannel instead of quietly losing packets. Use UDPServer/UDPClient, WebTransport, WebSocket, loopback, or a RelayTransport for reliable delivery.

func (*UDPTransport) SetCompression

func (u *UDPTransport) SetCompression(cfg CompressionConfig) error

SetCompression updates opt-in per-packet deflate compression settings and the decompression cap for UDPTransport. Even when Enabled is false, UDPTransport still inflates compressed datagrams from peers up to MaxInflated (capped at maxUDPPayloadSize).

func (*UDPTransport) SetInboxLimits

func (u *UDPTransport) SetInboxLimits(l InboxLimits)

SetInboxLimits bounds the packets the transport keeps until Recv takes them (see InboxLimits).

type UnreliablePolicy

type UnreliablePolicy uint8

UnreliablePolicy selects how a paced transport handles ChannelUnreliable and ChannelUnreliableSequenced sends when a peer's unreliable send queue exceeds its pacing budget.

const (
	// UnreliableDrop silently drops excess unreliable messages when over budget (default).
	UnreliableDrop UnreliablePolicy = iota
	// UnreliableRefuse refuses excess unreliable messages with ErrCongestionBudget when over budget.
	UnreliableRefuse
)

type WebSocketOptions

type WebSocketOptions struct {
	// TLS, when non-nil, wraps the listener with tls.NewListener for wss://.
	TLS *tls.Config
	// AllowedOrigins lists the browser Origins allowed to upgrade; empty allows any, "*" allows all, and an Origin outside the list is refused before the handshake.
	AllowedOrigins []string
}

WebSocketOptions configures ServeWebSocketWith when serving WebSocket clients on a caller-owned listener.

type WebSocketServer

type WebSocketServer struct {
	// contains filtered or unexported fields
}

WebSocketServer accepts RFC 6455 WebSocket clients and exposes them through the standard Transport interface.

Every client runs the connection handshake before its packets reach Recv: Auth.Verify checks its token, the server assigns its ID and tells the client, and NextEvent reports joins, drops, resumes and leaves.

The server pings every client and reports PeerDropped for one that stays silent for Auth.IdleTimeout. Browsers answer pings on their own, so browser clients need no code for it.

Send queues each client's frames in an outbox that a goroutine of the client's own writes out, so a client that reads slowly or not at all never blocks Send or delays the other clients (see OutboxLimits).

func ListenWebSocket

func ListenWebSocket(addr string, serverID PeerID, auth Auth) (*WebSocketServer, error)

ListenWebSocket starts a pure-Go RFC 6455 WebSocket server on addr. serverID is the server's own PeerID (1 when zero); clients get the IDs after it. auth decides who may connect and how long a dropped client keeps its ID.

func ListenWebSocketTLS

func ListenWebSocketTLS(addr string, serverID PeerID, auth Auth, config *tls.Config, allowedOrigins []string) (*WebSocketServer, error)

ListenWebSocketTLS starts the server with TLS, so a browser on an HTTPS page can connect with wss:// without a reverse proxy. auth is as for ListenWebSocket. allowedOrigins lists the browser Origins allowed to upgrade; empty allows any, "*" allows all, and an Origin outside the list is refused before the handshake.

func ListenWebSocketTLSFiles

func ListenWebSocketTLSFiles(addr string, serverID PeerID, auth Auth, certFile, keyFile string, allowedOrigins []string) (*WebSocketServer, error)

ListenWebSocketTLSFiles is ListenWebSocketTLS with a certificate and key loaded from PEM files.

func ServeWebSocket

func ServeWebSocket(ln stdnet.Listener, serverID PeerID, auth Auth) (*WebSocketServer, error)

ServeWebSocket is ListenWebSocket on a listener the caller already opened, such as one inherited from a parent process or from systemd socket activation, so a replacement process can take over a port without a gap in which new players are refused. The server takes ownership of ln: StopAccepting and Close both close it. Wrap ln with tls.NewListener for wss://, or use ServeWebSocketWith to configure TLS and browser Origins while keeping the raw listener for descriptor handoff.

func ServeWebSocketWith

func ServeWebSocketWith(ln stdnet.Listener, serverID PeerID, auth Auth, opt WebSocketOptions) (*WebSocketServer, error)

ServeWebSocketWith is ServeWebSocket taking optional TLS configuration and a browser Origin allow-list. The server takes ownership of ln: StopAccepting and Close both close it. Passing opt.TLS here lets callers keep the underlying *net.TCPListener for descriptor handoff while serving wss://.

func (*WebSocketServer) Account

func (s *WebSocketServer) Account(peer PeerID) (string, bool)

Account returns the account Auth.Identify bound to peer's live or grace-period session. It returns ("", false) for anonymous peers, unknown peers, handshakes still in Identify, or after Close.

func (*WebSocketServer) Addr

func (s *WebSocketServer) Addr() stdnet.Addr

Addr returns the listener's network address.

func (*WebSocketServer) Close

func (s *WebSocketServer) Close() error

Close stops accepting new clients and closes all active client connections. Each client receives the frames already sent to it and then a close frame, all clients at once; Close waits at most a second for them and cuts off the connections of clients that read too slowly to take theirs by then.

func (*WebSocketServer) ExtendGrace

func (s *WebSocketServer) ExtendGrace(peer PeerID, d time.Duration) error

ExtendGrace gives peer's session a grace period of at least d from its drop, clamped to Auth.MaxGracePeriod when that is nonzero. A game calls it to keep one peer's seat longer than Auth.GracePeriod, for example a ranked match that allows a dropped player more time to come back. Called while the peer is connected, it sets the window for its next drop; called inside its grace period, it extends the current one. It never shortens a window, and a non-positive d does nothing. ExtendGrace returns ErrUnknownPeer for an ID with no session (including a handshake still in Verify) and ErrClosed once the server is closed.

func (*WebSocketServer) InboxStats

func (s *WebSocketServer) InboxStats() InboxStats

InboxStats reports what the server's inbox holds and what its limits dropped or warned about.

func (*WebSocketServer) Kick

func (s *WebSocketServer) Kick(peer PeerID, reason string) error

Kick ends peer's session now: a connected client receives the frames already sent to it, then a close frame with the wsCloseKicked code and the reason, and the session's resume secret is gone, so the client's Reconnect cannot resume it and joins as a new peer only if Auth.Verify accepts its token again. NextEvent reports PeerLeft with the reason. It returns ErrUnknownPeer for an ID with no session (including a handshake still in Verify) and ErrClosed once the server is closed. Kick does not wait for the connection: the client's own goroutine writes the queued frames and the close frame, and whatever a client that reads too slowly has not taken within a second is cut off with the connection.

func (*WebSocketServer) LinkStats

func (s *WebSocketServer) LinkStats(peer PeerID) (LinkStats, bool)

LinkStats reports the per-peer RTT, RTT variance, and byte/packet counters for a connected client.

func (*WebSocketServer) LocalID

func (s *WebSocketServer) LocalID() PeerID

LocalID returns the server's PeerID.

func (*WebSocketServer) NextEvent

func (s *WebSocketServer) NextEvent() (PeerEvent, bool)

NextEvent pops the next join, drop, resume or leave without blocking, after ending the sessions whose grace period has passed.

func (*WebSocketServer) OutboxStats

func (s *WebSocketServer) OutboxStats() OutboxStats

OutboxStats reports what the connected clients' outboxes hold and what their limits dropped.

func (*WebSocketServer) PeerByAccount

func (s *WebSocketServer) PeerByAccount(account string) (PeerID, bool)

PeerByAccount returns the PeerID of the live or grace-period session bound to account by Auth.Identify. It returns (0, false) for an empty account, an account with no session, or after Close.

func (*WebSocketServer) Peers

func (s *WebSocketServer) Peers() []PeerID

Peers returns the sorted list of currently connected client PeerIDs. Clients inside their grace period are left out.

func (*WebSocketServer) Recv

func (s *WebSocketServer) Recv() (Packet, bool)

Recv pops the next received packet from any connected client without blocking.

func (*WebSocketServer) Send

func (s *WebSocketServer) Send(to PeerID, ch Channel, payload []byte) error

Send queues payload for a connected client (or all clients when to == PeerBroadcast) and returns without waiting for the connection: each client's own goroutine writes its frames in order (see OutboxLimits). It returns ErrDisconnected for a client inside its grace period or whose session a full outbox has just ended, ErrUnknownPeer for an ID with no session, and ErrPayloadTooLarge for a payload that does not fit a WebSocket message. A write that later fails or times out is not returned by any Send: NextEvent reports it as PeerDropped.

func (*WebSocketServer) SetChannelConfig

func (s *WebSocketServer) SetChannelConfig(cfg ChannelConfig)

SetChannelConfig updates the extra reliable lanes accepted by this server.

func (*WebSocketServer) SetCompression

func (s *WebSocketServer) SetCompression(cfg CompressionConfig) error

SetCompression updates the server's RFC 7692 permessage-deflate compression settings for connections upgraded afterwards.

func (*WebSocketServer) SetDraining

func (s *WebSocketServer) SetDraining(reason string, retryAfter time.Duration)

SetDraining switches the server into draining mode: new handshakes are refused with RejectMaintenance, reason ("draining" when empty), and retryAfter, while already-connected peers keep their sessions and dropped peers may still resume within their grace period. Calling it again updates the reason and retry hint.

func (*WebSocketServer) SetInboxLimits

func (s *WebSocketServer) SetInboxLimits(l InboxLimits)

SetInboxLimits bounds the packets the server keeps until Recv takes them (see InboxLimits). A client whose queued reliable packets would pass InboxLimits.Reliable has its session ended, as if it had left.

func (*WebSocketServer) SetOutboxLimits

func (s *WebSocketServer) SetOutboxLimits(l OutboxLimits)

SetOutboxLimits bounds the frames the server holds for each client before they are written (see OutboxLimits).

func (*WebSocketServer) StopAccepting

func (s *WebSocketServer) StopAccepting() error

StopAccepting closes the listener so no new client connects, while connected clients keep their sessions, Send and Recv work as before, and Close later ends them. Call it in the old process once its replacement accepts on the shared socket, then drain. Calling it again, or Close after it, does not close the listener twice.

type WebSocketTransport

type WebSocketTransport struct {
	// contains filtered or unexported fields
}

WebSocketTransport is a client-side RFC 6455 WebSocket Transport. Binary WebSocket frames carry the 5-byte channel+seq wire header.

The first message each way is the connection handshake: the client presents its token and the server answers with the ID it assigned, or a reason for refusing. A dropped client keeps its session on the server for Auth.GracePeriod, and Reconnect resumes it with the same ID.

func DialWebSocket

func DialWebSocket(rawURL string, token []byte) (*WebSocketTransport, error)

DialWebSocket opens an RFC 6455 WebSocket connection to rawURL (ws:// or wss://), presents token in the connection handshake and returns a Transport ready for non-blocking Send/Recv once the server accepts it. The server assigns the client's ID, which LocalID reports. A refusal returns a *RejectError that matches ErrRejected.

The client pings the server every 2 seconds and counts the connection as dropped, reporting ConnDisconnected, when no frame arrives for 10 seconds.

func DialWebSocketResume

func DialWebSocketResume(rawURL string, token []byte, resume string) (*WebSocketTransport, error)

DialWebSocketResume is DialWebSocket for a client that stored a ResumeToken, for example across an app restart: within the server's grace period it resumes the session, keeping the peer ID, and Resumed reports true. Past it, or when the server replaced the token's secret, the handshake is a fresh join that Auth.Verify checks as usual. A malformed token returns ErrInvalidResumeToken without dialing.

func DialWebSocketWith

func DialWebSocketWith(rawURL string, o DialOptions) (*WebSocketTransport, error)

DialWebSocketWith is DialWebSocket taking the client's options: its token, the build string it reports to the server and an optional resume token.

func (*WebSocketTransport) Close

func (wt *WebSocketTransport) Close() error

Close sends a WebSocket close frame and closes the underlying connection. The server reports PeerLeft at once rather than holding the session for a reconnect.

func (*WebSocketTransport) Err

func (wt *WebSocketTransport) Err() error

Err returns why the client is disconnected: a *RejectError, or ErrDisconnected wrapping the I/O error. It is nil while the connection is open.

func (*WebSocketTransport) InboxStats

func (wt *WebSocketTransport) InboxStats() InboxStats

InboxStats reports what the transport's inbox holds and what its limits dropped or warned about.

func (*WebSocketTransport) LinkStats

func (wt *WebSocketTransport) LinkStats(peer PeerID) (LinkStats, bool)

LinkStats reports RTT, RTT variance, and byte/packet counters for the connected server.

func (*WebSocketTransport) LocalID

func (wt *WebSocketTransport) LocalID() PeerID

LocalID returns the PeerID the server assigned this client.

func (*WebSocketTransport) Peers

func (wt *WebSocketTransport) Peers() []PeerID

Peers returns the connected server's PeerID, or nil while disconnected or closed.

func (*WebSocketTransport) Reconnect

func (wt *WebSocketTransport) Reconnect() error

Reconnect drops the current connection, if any, without a goodbye, dials the server again and resumes the session: within the server's grace period the client keeps its ID, and Resumed reports true. Past it, the server admits the client as a new peer when its token is still valid, and LocalID changes.

func (*WebSocketTransport) Recv

func (wt *WebSocketTransport) Recv() (Packet, bool)

Recv pops the next received packet without blocking.

func (*WebSocketTransport) ResumeToken

func (wt *WebSocketTransport) ResumeToken() string

ResumeToken returns an opaque credential for the current session, empty before the first welcome on a fresh join. A client created with DialWebSocketResume reports the stored token until the first welcome replaces it. Store it after every handshake, because each one replaces the secret it carries, treat it like a password, and clear it after Close. DialWebSocketResume presents it.

func (*WebSocketTransport) Resumed

func (wt *WebSocketTransport) Resumed() bool

Resumed reports whether the last handshake resumed an existing session, keeping the client's ID.

func (*WebSocketTransport) Send

func (wt *WebSocketTransport) Send(to PeerID, ch Channel, payload []byte) error

Send frames payload with the 5-byte channel+seq header and sends it as a masked RFC 6455 binary WebSocket frame to the server. It returns ErrDisconnected while the connection is down.

func (*WebSocketTransport) SetChannelConfig

func (wt *WebSocketTransport) SetChannelConfig(cfg ChannelConfig)

SetChannelConfig updates the extra reliable lanes accepted by this transport.

func (*WebSocketTransport) SetCompression

func (wt *WebSocketTransport) SetCompression(cfg CompressionConfig) error

SetCompression updates the client's RFC 7692 permessage-deflate compression settings. Negotiation happens during the HTTP upgrade (on dial or Reconnect), while MinSize, Level, and MaxInflated apply immediately when permessage-deflate was negotiated on the current connection.

func (*WebSocketTransport) SetInboxLimits

func (wt *WebSocketTransport) SetInboxLimits(l InboxLimits)

SetInboxLimits bounds the packets the transport keeps until Recv takes them (see InboxLimits).

func (*WebSocketTransport) State

func (wt *WebSocketTransport) State() ConnState

State returns the connection state.

type WebTransportOptions

type WebTransportOptions struct {
	// ServerCertificateHashes pins expected SHA-256 digests (32 bytes each) of the server's leaf X.509 DER certificate.
	// In browsers, these are passed as serverCertificateHashes to the WebTransport constructor so self-signed development certificates (at most 14 days validity per the WebTransport specification) work without installing a root CA.
	// On native targets, when non-empty, certificate verification accepts a server whose leaf certificate SHA-256 digest matches any entry instead of verifying against system roots.
	ServerCertificateHashes [][]byte
}

WebTransportOptions configures DialWebTransport.

type WebTransportServer

type WebTransportServer struct {
	// contains filtered or unexported fields
}

WebTransportServer accepts WebTransport clients over HTTP/3 and QUIC and exposes them through the standard Transport and RelayServer interfaces.

ChannelReliableOrdered packets travel over each client's bidirectional QUIC stream, and ChannelUnreliable packets travel as independent QUIC datagrams. Every client runs the connection handshake on the bidirectional stream before its packets reach Recv: Auth.Verify checks its token, the server assigns its ID and tells the client, and NextEvent reports joins, drops, resumes and leaves.

Send queues each client's reliable frames in an outbox that a goroutine of the client's own writes to its stream, and its unreliable datagrams in a second outbox that another goroutine hands to QUIC, so a client that stops reading the stream, or whose acknowledgements stop coming, never blocks Send or delays the other clients (see OutboxLimits).

func ListenWebTransport

func ListenWebTransport(addr string, serverID PeerID, auth Auth, cfg *tls.Config, allowedOrigins []string) (*WebTransportServer, error)

ListenWebTransport starts a WebTransport server over QUIC/HTTP/3 on addr. serverID is the server's own PeerID (1 when zero); clients get the IDs after it. auth decides who may connect and how long a dropped client keeps its ID. cfg provides the TLS 1.3 certificate and is required. allowedOrigins lists the browser Origins allowed to connect; empty allows any, "*" allows all, and an Origin outside the list is refused with 403 before the handshake.

func ListenWebTransportFiles

func ListenWebTransportFiles(addr string, serverID PeerID, auth Auth, certFile, keyFile string, allowedOrigins []string) (*WebTransportServer, error)

ListenWebTransportFiles is ListenWebTransport with a certificate and key loaded from PEM files.

func (*WebTransportServer) Account

func (s *WebTransportServer) Account(peer PeerID) (string, bool)

Account returns the account Auth.Identify bound to peer's live or grace-period session. It returns ("", false) for anonymous peers, unknown peers, handshakes still in Identify, or after Close.

func (*WebTransportServer) Addr

func (s *WebTransportServer) Addr() stdnet.Addr

Addr returns the listener's UDP network address.

func (*WebTransportServer) Close

func (s *WebTransportServer) Close() error

Close stops accepting new clients and closes all active client sessions and the underlying UDP socket.

func (*WebTransportServer) InboxStats

func (s *WebTransportServer) InboxStats() InboxStats

InboxStats reports what the server's inbox holds and what its limits dropped or warned about.

func (*WebTransportServer) LinkStats

func (s *WebTransportServer) LinkStats(peer PeerID) (LinkStats, bool)

LinkStats reports per-peer RTT, RTT variance, datagram sequence-gap loss, and byte/packet counters for a connected client.

func (*WebTransportServer) LocalID

func (s *WebTransportServer) LocalID() PeerID

LocalID returns the server's PeerID.

func (*WebTransportServer) NextEvent

func (s *WebTransportServer) NextEvent() (PeerEvent, bool)

NextEvent pops the next join, drop, resume or leave without blocking, after ending the sessions whose grace period has passed.

func (*WebTransportServer) OutboxStats

func (s *WebTransportServer) OutboxStats() OutboxStats

OutboxStats reports what the connected clients' outboxes hold and what their limits dropped.

func (*WebTransportServer) PeerByAccount

func (s *WebTransportServer) PeerByAccount(account string) (PeerID, bool)

PeerByAccount returns the PeerID of the live or grace-period session bound to account by Auth.Identify. It returns (0, false) for an empty account, an account with no session, or after Close.

func (*WebTransportServer) Peers

func (s *WebTransportServer) Peers() []PeerID

Peers returns the sorted list of currently connected client PeerIDs. Clients inside their grace period are left out.

func (*WebTransportServer) Recv

func (s *WebTransportServer) Recv() (Packet, bool)

Recv pops the next received packet from any connected client without blocking.

func (*WebTransportServer) Send

func (s *WebTransportServer) Send(to PeerID, ch Channel, payload []byte) error

Send queues payload for a connected client (or all clients when to == PeerBroadcast) and returns without waiting for the connection: each client's own goroutines write its frames in order (see OutboxLimits). Reliable frames travel on each client's bidirectional stream; ChannelUnreliable and ChannelUnreliableSequenced frames travel as independent QUIC datagrams (returning ErrPayloadTooLarge if payload exceeds the QUIC datagram MTU). It returns ErrDisconnected for a client inside its grace period or whose session a full outbox has just ended, and ErrUnknownPeer for an ID with no session. A write that later fails or times out is not returned by any Send: NextEvent reports it as PeerDropped.

func (*WebTransportServer) SetChannelConfig

func (s *WebTransportServer) SetChannelConfig(cfg ChannelConfig)

SetChannelConfig updates the extra reliable lanes accepted by this server.

func (*WebTransportServer) SetDraining

func (s *WebTransportServer) SetDraining(reason string, retryAfter time.Duration)

SetDraining switches the server into draining mode: new handshakes are refused with RejectMaintenance, reason ("draining" when empty), and retryAfter, while already-connected peers keep their sessions and dropped peers may still resume within their grace period. Calling it again updates the reason and retry hint.

func (*WebTransportServer) SetInboxLimits

func (s *WebTransportServer) SetInboxLimits(l InboxLimits)

SetInboxLimits bounds the packets the server keeps until Recv takes them (see InboxLimits). A client whose queued reliable packets would pass InboxLimits.Reliable has its session ended, as if it had left.

func (*WebTransportServer) SetOutboxLimits

func (s *WebTransportServer) SetOutboxLimits(l OutboxLimits)

SetOutboxLimits bounds the frames the server holds for each client before they are written (see OutboxLimits). Each client's reliable frames and its unreliable datagrams have an outbox of their own, each with these limits.

type WebTransportTransport

type WebTransportTransport struct {
	// contains filtered or unexported fields
}

WebTransportTransport is a client-side WebTransport Transport over HTTP/3 and QUIC.

ChannelReliableOrdered packets travel over one bidirectional QUIC stream with 4-byte length-prefixed frames; ChannelUnreliable packets travel as independent QUIC datagrams so a lost packet never blocks newer unreliable updates.

The first message each way on the bidirectional stream is the connection handshake: the client presents its token and the server answers with the ID it assigned, or a reason for refusing. A dropped client keeps its session on the server for Auth.GracePeriod, and Reconnect resumes it with the same ID.

func DialWebTransport

func DialWebTransport(rawURL string, token []byte, opts WebTransportOptions) (*WebTransportTransport, error)

DialWebTransport opens a WebTransport session to rawURL (https://), presents token in the connection handshake on the reliable stream, and returns a Transport ready for non-blocking Send/Recv once the server accepts it. The server assigns the client's ID, which LocalID reports. A refusal returns a *RejectError that matches ErrRejected.

When opts.ServerCertificateHashes is non-empty, certificate verification matches the server's leaf certificate SHA-256 digest against the provided hashes instead of system root CAs.

func DialWebTransportWith

func DialWebTransportWith(rawURL string, o DialOptions, opts WebTransportOptions) (*WebTransportTransport, error)

DialWebTransportWith is DialWebTransport taking the client's options, so it can report its build string and resume a session with a resume token.

func (*WebTransportTransport) Close

func (wt *WebTransportTransport) Close() error

Close sends a clean goodbye on the reliable stream and closes the WebTransport session so the server reports PeerLeft at once rather than holding the session for a reconnect.

func (*WebTransportTransport) Err

func (wt *WebTransportTransport) Err() error

Err returns why the client is disconnected: a *RejectError, or ErrDisconnected wrapping the I/O error. It is nil while the connection is open.

func (*WebTransportTransport) InboxStats

func (wt *WebTransportTransport) InboxStats() InboxStats

InboxStats reports what the transport's inbox holds and what its limits dropped or warned about.

func (*WebTransportTransport) LinkStats

func (wt *WebTransportTransport) LinkStats(peer PeerID) (LinkStats, bool)

LinkStats reports RTT, RTT variance, datagram sequence-gap loss, and byte/packet counters for the connected server.

func (*WebTransportTransport) LocalID

func (wt *WebTransportTransport) LocalID() PeerID

LocalID returns the PeerID the server assigned this client.

func (*WebTransportTransport) Peers

func (wt *WebTransportTransport) Peers() []PeerID

Peers returns the connected server's PeerID, or nil while disconnected or closed.

func (*WebTransportTransport) Reconnect

func (wt *WebTransportTransport) Reconnect() error

Reconnect drops the current WebTransport session without a goodbye (sending wtCloseReconnect so the server keeps the session for Auth.GracePeriod), dials the server again, and resumes the session: within the server's grace period the client keeps its ID, and Resumed reports true. Past it, the server admits the client as a new peer when its token is still valid, and LocalID changes.

func (*WebTransportTransport) Recv

func (wt *WebTransportTransport) Recv() (Packet, bool)

Recv pops the next received packet without blocking.

func (*WebTransportTransport) Resumed

func (wt *WebTransportTransport) Resumed() bool

Resumed reports whether the last handshake resumed an existing session, keeping the client's ID.

func (*WebTransportTransport) Send

func (wt *WebTransportTransport) Send(to PeerID, ch Channel, payload []byte) error

Send transmits payload to the server. Reliable frames travel on the bidirectional QUIC stream; ChannelUnreliable and ChannelUnreliableSequenced frames travel as independent QUIC datagrams (returning ErrPayloadTooLarge if payload exceeds the QUIC datagram MTU).

func (*WebTransportTransport) SetChannelConfig

func (wt *WebTransportTransport) SetChannelConfig(cfg ChannelConfig)

SetChannelConfig updates the extra reliable lanes accepted by this transport.

func (*WebTransportTransport) SetInboxLimits

func (wt *WebTransportTransport) SetInboxLimits(l InboxLimits)

SetInboxLimits bounds the packets the transport keeps until Recv takes them (see InboxLimits).

func (*WebTransportTransport) State

func (wt *WebTransportTransport) State() ConnState

State returns the connection state.

type WireDecoder

type WireDecoder interface {
	DecodeWire(src []byte) (int, error)
}

WireDecoder is implemented by message pointers (including types generated by game wire) that decode their binary wire encoding from src into caller-owned storage without heap allocations once slices have capacity.

type WireEncoder

type WireEncoder interface {
	AppendWire(dst []byte) []byte
}

WireEncoder is implemented by message pointers (including types generated by game wire) that append their binary wire encoding onto dst without allocating when dst has capacity.

Directories

Path Synopsis
Package roomstate is experimental: its API and documented formats may change in a minor release; see https://nsgo.games/docs/stability/.
Package roomstate is experimental: its API and documented formats may change in a minor release; see https://nsgo.games/docs/stability/.
Package wire is experimental: its API and documented formats may change in a minor release; see https://nsgo.games/docs/stability/.
Package wire is experimental: its API and documented formats may change in a minor release; see https://nsgo.games/docs/stability/.
Package worldsync is experimental: its API and documented formats may change in a minor release; see https://nsgo.games/docs/stability/.
Package worldsync is experimental: its API and documented formats may change in a minor release; see https://nsgo.games/docs/stability/.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL