statesync

package module
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Oct 8, 2026 License: MIT Imports: 24 Imported by: ? modules, 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.

README

Go StateSync

用 Go(编程语言)构建联机游戏的服务器权威状态同步。

English · 接入指南 · 协议 · 断线续接 · 验收报告

面向每房间最多 16 人的合作游戏与实时交互应用。核心库独立于游戏引擎,提供独立服务器、无界面参考客户端、二维移动与拾取示例,以及真实加密连接上的弱网测试。

当前发布 v0.2.0,使用第 2 版同步协议。库版本与协议版本分别管理;客户端与服务器需要使用相同协议。

核心能力

能力 行为
多房间权威模拟 每个房间独占游戏状态,固定步长推进,网络消息经有界队列投递
本地预测与校正 输入立即预测;收到权威状态后重放尚未确认的输入
远端快照插值 默认缓冲 200 毫秒;缓冲不足时保持最后状态
进程内断线续接 默认保留会话 60 秒;新连接接管原角色,最近操作结果可原样重试
生命周期与故障隔离 可靠同步生成、销毁和拾取;非法批次或可恢复异常只结束受影响房间
明确的资源边界 输入、控制和发送队列均有上限;慢客户端被剔除,旧运动快照可被替换

架构

flowchart LR
    subgraph C[参考客户端]
        P[输入与本地预测]
        R[权威校正与远端插值]
    end
    Q[QUIC 加密传输]
    subgraph S[服务器]
        A[房间 A 独立循环]
        B[房间 B 独立循环]
    end
    P -->|移动输入数据报| Q
    Q --> A
    Q --> B
    A -->|运动快照数据报| Q
    B -->|运动快照数据报| Q
    Q --> R
    C <-->|加入、完整状态、生命周期、操作、续接:可靠流| Q

QUIC(基于数据报的加密传输协议)由 quic-go(网络传输库)提供。移动输入和运动快照允许丢失,生命周期与离散操作使用可靠流;每条实体运动记录可独立应用。游戏自己定义输入、状态与编码,核心不扫描属性或依赖反射。

默认每秒执行 30 个逻辑步、发送 15 次运动快照,单个数据报不超过 1000 字节。完整配置及边界见接入指南。

快速运行

需要 Go(编程语言)1.26 或以上。

git clone https://github.com/qihai-coding/go-statesync.git
cd go-statesync
go mod download
go run ./cmd/server -generate-cert
go run ./cmd/server -rooms alpha,beta

在另外两个终端分别启动客户端:

go run ./cmd/client -room alpha -x 1 -duration 10s
go run ./cmd/client -room alpha -y 1 -duration 10s

演示拾取和断线续接:

go run ./cmd/client -room beta -pickup 1 -x 1 -duration 8s -disconnect-after 2s

本地演示证书有效期为 24 小时,生成命令不覆盖已有证书。重复运行时用 -cert、-key 和客户端的 -ca 指定新文件;客户端始终校验证书。

作为库使用

go get github.com/qihai-coding/go-statesync@v0.2.0

实现 Game(服务端游戏接口)和 Model(客户端预测及编码接口),为每个房间创建独立游戏实例。可先查看二维示例,再按接入指南替换游戏规则。

业务保存凭证并显式续接,成功后获得新的客户端对象:

token := client.ResumeToken()
client.Disconnect()
next, err := statesync.DialResume(ctx, address, room, tlsConfig, model, token)
if err != nil {
    return err
}
client = next

ResumeToken(续接凭证)不得写入日志。未确认操作使用原编号、原负载重试;LastActionID(最近处理操作编号)包括失败操作,不表示业务成功。完整规则见续接说明。

验证与性能

go test -count=1 ./...
go vet ./...
go test -race -count=1 ./...
go run ./cmd/check -rooms 8 -clients 16 -duration 10m -resume-every 30s -report soak.json

竞态检测需要兼容的 C(编程语言)编译器。持续集成在三种桌面系统上执行原生测试和构建,另在 Linux(开源操作系统)执行竞态检测与四类模糊测试。

本次发布验收记录 8 房间 × 16 人十分钟负载、三档弱网、周期续接、资源及每客户端带宽。性能数据来自指定环境实测,房间单步目标为第 99 百分位低于 10 毫秒;不等于每一步都有硬性十毫秒上限。处理器与内存数据包含同进程的服务器和参考客户端,带宽为应用负载口径。

接入范围

  • 每个玩家会话对应一个受控动态实体;本阶段不支持角色重生或控制权切换。
  • 续接仅在当前服务器进程内有效,重启后凭证失效;账号认证、持久化、匹配和跨服务器调度由接入应用提供。
  • 游戏回调必须快速且不阻塞。异常隔离覆盖可恢复运行时异常,不处理中断进程或无限阻塞。
  • 使用完整运动快照及显式离散事件;差量压缩和可见范围筛选尚未加入。

文档与贡献

文档 内容
接入指南 配置、游戏接口、预测模型、计时与验证口径
同步协议 字节布局、生命周期、输入确认与固定报文样例
断线续接 会话、接管、取消、操作重试与故障处理
验收报告索引 当前发布与历史验证证据
更新记录 版本变化与核心加固记录
贡献指南 复现问题、运行检查和提交变更

设计参考:Nakama(游戏后端框架)的房间调度、Mirror(游戏网络同步框架)的插值、Colyseus(状态同步框架)的编码、客户端预测与服务器校正。实现独立编写,这些项目不构成运行依赖。

本项目采用 MIT(开源许可证)。

Documentation

Overview

Package statesync provides authoritative rooms and a transport-independent game API.

Index

Constants

View Source
const (
	ProtocolVersion byte = 2
	ALPN                 = "statesync/2"
	MaxState             = 512
	MaxInput             = 64
	MaxAction            = 512
	MaxEntities          = 256
	MaxFrame             = 256 * 1024
	HistorySize          = 128
)

Variables

View Source
var ErrBusy = errors.New("statesync: queue full")
View Source
var ErrClosed = errors.New("statesync: closed")
View Source
var ErrProtocol = errors.New("statesync: invalid protocol")
View Source
var ErrResumeRejected = errors.New("statesync: resume rejected")
View Source
var ErrSessionReplaced = errors.New("statesync: session replaced")

Functions

func ClientTLS

func ClientTLS(certPEM []byte, serverName string) (*tls.Config, error)

func LocalCertificate

func LocalCertificate() (tls.Certificate, []byte, error)

LocalCertificate generates a short-lived localhost certificate for demos/tests. The client explicitly trusts this certificate; verification is never disabled.

func ServerTLS

func ServerTLS(cert tls.Certificate) *tls.Config

func WriteLocalCertificate

func WriteLocalCertificate(certFile, keyFile string) error

Types

type Change

type Change struct {
	Delete bool
	Entity Entity
}

type Client

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

func Dial

func Dial(ctx context.Context, addr, room string, tlsConfig *tls.Config, model Model) (*Client, error)

func DialResume

func DialResume(ctx context.Context, addr, room string, tlsConfig *tls.Config, model Model, token ResumeToken) (*Client, error)

func (*Client) Action

func (c *Client) Action(ctx context.Context, id uint64, data []byte) ([]byte, error)

Action uses a caller-supplied monotonically increasing request ID. Retrying the same ID and payload in this session returns the previous result.

func (*Client) Authoritative

func (c *Client) Authoritative() View

func (*Client) Bytes

func (c *Client) Bytes() (sent, received uint64)

func (*Client) Close

func (c *Client) Close()

func (*Client) Disconnect

func (c *Client) Disconnect()

Disconnect closes transport but allows the session to be resumed.

func (*Client) Done

func (c *Client) Done() <-chan struct{}

func (*Client) Err

func (c *Client) Err() error

func (*Client) LastActionID

func (c *Client) LastActionID() uint64

func (*Client) Player

func (c *Client) Player() uint32

func (*Client) ResumeGracePeriod

func (c *Client) ResumeGracePeriod() time.Duration

func (*Client) ResumeToken

func (c *Client) ResumeToken() ResumeToken

func (*Client) Resync

func (c *Client) Resync() error

func (*Client) ResyncCount

func (c *Client) ResyncCount() uint64

func (*Client) Sample

func (c *Client) Sample(id uint32, now time.Time) ([]byte, bool)

Sample returns predicted local state or a delayed interpolated remote state.

func (*Client) SetInterpolationDelay

func (c *Client) SetInterpolationDelay(delay time.Duration) error

func (*Client) SubmitInput

func (c *Client) SubmitInput(data []byte) error

SubmitInput predicts exactly one fixed simulation step. Call at TickRate. The server independently caps processing to one input per player per tick.

func (*Client) TickRate

func (c *Client) TickRate() int

type Config

type Config struct {
	TickRate          int
	SnapshotRate      int
	MaxPlayers        int
	DatagramSize      int
	ResumeGracePeriod time.Duration
}

func DefaultConfig

func DefaultConfig() Config

type Entity

type Entity struct {
	ID         uint32
	Generation uint32
	Owner      uint32
	Dynamic    bool
	Ack        uint64 // Filled by the server; all inputs <= Ack have been resolved.
	State      []byte
}

State is an immutable, game-encoded value once returned to the framework.

type Game

type Game interface {
	Join(player uint32) ([]Change, error)
	Leave(player uint32) []Change
	ValidateInput(data []byte) error
	Step(dt float32, inputs []PlayerInput) []Change
	Action(player uint32, data []byte) ([]Change, []byte, error)
	Entities() []Entity
}

After the initial Entities call, Game methods execute on the room's owning goroutine. Returned slices must not subsequently be modified by the game. Join/Action errors must leave game state unchanged.

type Input

type Input struct {
	Sequence uint64
	Data     []byte
}

type Metrics

type Metrics struct {
	Ticks           uint64
	StepTotal       time.Duration
	StepP99         time.Duration
	StepMax         time.Duration
	InputDrops      uint64
	SnapshotDrops   uint64
	ReliableBytes   uint64
	DatagramBytes   uint64
	Players         int
	RetainedPlayers int
	InputQueue      int
	ControlQueue    int
	ReliableQueued  int
	SnapshotQueued  int
}

type Model

type Model interface {
	ValidateInput([]byte) error
	ValidateState([]byte) error
	Predict(state, input []byte, dt float32) ([]byte, error)
	Interpolate(a, b []byte, fraction float32) []byte
}

Model supplies the same movement rules and codec to the reference client. Implementations must return owned byte slices and must not modify arguments.

type PlayerInput

type PlayerInput struct {
	Player uint32
	Data   []byte
}

type ResumeToken

type ResumeToken [32]byte

ResumeToken is a bearer credential; never include its bytes in logs.

func (ResumeToken) GoString

func (ResumeToken) GoString() string

func (ResumeToken) String

func (ResumeToken) String() string

type Room

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

func (*Room) Close

func (r *Room) Close()

func (*Room) Done

func (r *Room) Done() <-chan struct{}

func (*Room) Err

func (r *Room) Err() error

func (*Room) Inspect

func (r *Room) Inspect(ctx context.Context) (View, Metrics, error)

type Server

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

func Listen

func Listen(addr string, tlsConfig *tls.Config, cfg Config) (*Server, error)

func (*Server) Addr

func (s *Server) Addr() net.Addr

func (*Server) Close

func (s *Server) Close()

func (*Server) CloseRoom

func (s *Server) CloseRoom(name string) error

func (*Server) CreateRoom

func (s *Server) CreateRoom(name string, game Game) (*Room, error)

type View

type View struct {
	Tick     uint64
	Revision uint64
	Player   uint32
	Entities []Entity
}

Directories

Path Synopsis
Package arena is the explicitly encoded 2D example game.
Package arena is the explicitly encoded 2D example game.
cmd
check command
Command check validates real QUIC rooms, headless clients and bounded UDP impairment.
Command check validates real QUIC rooms, headless clients and bounded UDP impairment.
client command
server command
internal
nettest
Package nettest provides a bounded, seeded UDP impairment proxy.
Package nettest provides a bounded, seeded UDP impairment proxy.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL