GitHubはじめる

このページはまだ日本語訳がないため、英語の原文を表示しています。

マルチプレイ・MOD

gameserver

github.com/nsgo-dev/game/pkg/online/gameserver runs a game's fixed-step updates in a plain Go process, without an NSGo app, window, core.Scope or cgo.

The Update function a game hands to game.Loop runs unchanged on the server: both step it with the same fixed 1/Rate duration, so a dedicated server and the client share one simulation.

Runner

r := &gameserver.Runner{
	Matches: []*gameserver.Match{
		{Name: "match-1", Rate: 60, Update: update},
		{Name: "match-2", Rate: 30, Update: update},
	},
	OnOverrun: func(m *gameserver.Match, lag time.Duration, missed int) {
		log.Printf("%s overran by %v (%d ticks missed)", m.Name, lag, missed)
	},
}
if err := r.Run(ctx); err != nil { ... }

Runner.Run blocks until its context is canceled, then waits for each match's in-flight tick and runs its OnStop before returning. Each match runs on its own goroutine at its own rate.

Ticks and overruns

A match's step is 1/Rate seconds (60 Hz when Rate is zero or negative). Runner schedules each tick against a fixed deadline (next += step), so Update's own runtime and minor timer jitter come out of the remaining step budget rather than slowing the tick rate. When an update finishes past the next tick's deadline, Runner calls OnOverrun with the lateness and the number of whole steps it covers (at least 1). Missed ticks are not caught up: the deadline resets to one step from the moment the slow update returns, so a slow update slows the match rather than producing a burst.

Stopping

A dedicated server usually runs under signal.NotifyContext:

ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
defer stop()

On SIGTERM/SIGINT the context ends; the runner lets the current tick finish, then calls OnStop (for example to notify peers and flush state) and returns. Update must return promptly for the stop to stay bounded.

A panic in one match's Update never takes down the process. The runner recovers it, reports it through OnPanic, and — with the default StopMatch action — ends only that match: it never ticks again (its state may be half-updated), its OnStop runs once, and every other match keeps ticking. Returning Crash instead stops every match, runs every OnStop, then re-panics from Run once they have all returned. A panic inside OnStop is recovered and reported the same way, with Tick 0.

r := &gameserver.Runner{
	Matches: matches,
	OnPanic: func(p gameserver.Panic) gameserver.PanicAction {
		save(p.Report()) // crashreport.CrashReport: the client's crash schema
		return server.StopMatch
	},
}

Panic carries the match, the recovered value, the goroutine stack, the 1-based tick and the time. Panic.Report() builds a crashreport.CrashReport, so server panic files and client crash files share one JSON schema.

The runnable example is examples/dedicatedserver:

go build ./examples/dedicatedserver

It builds with the plain Go toolchain and no NSGo runtime.

Data tables load headlessly too: pkg/datatable imports no NSGo package, so the server reads item and enemy tables with datatable.LoadFile or datatable.NewTable exactly as the client does. Hot reload (pkg/datatable/datatablewatch) is dev-time tooling only the client links.

Matchmaking

Matchmaker queues Tickets by mode and region and fills rooms of RoomSize players:

mm := gameserver.NewMatchmaker(4)
mm.BaseWindow = 100       // rating difference allowed at enqueue time
mm.WindowGrowthPerSecond = 10
mm.MaxWindow = 400
mm.Enqueue(gameserver.Ticket{ID: 7, Mode: "coop", Region: "eu", Rating: 1200, Party: []string{"ada", "lin"}})
rooms := mm.Match()       // []gameserver.Matchup with TicketIDs and Players

A ticket's party is placed whole or not at all. The default rule fills rooms oldest-first and adds a ticket only when its rating difference from the room's oldest ticket fits within both tickets' current windows: BaseWindow + WindowGrowthPerSecond * waited, capped by MaxWindow. Matches never mix beyond the newer ticket's window, and an old ticket's window widening lets it meet a later arrival. Cancel(id) removes a waiting ticket without disturbing the rest; Waiting lists the queue oldest-first.

Set Rule to replace the matching function; it receives a group of tickets with the same mode and region, the room size and a window function, and returns Matchups. The matchmaker removes the tickets listed in each returned room.

Rooms

Rooms groups peers into independent rooms with a per-match lifecycle and its own packet inboxes:

rs := gameserver.NewRooms()
rs.EmptyTimeout = 30 * time.Second
rs.Snapshot = func(r *gameserver.Room) []byte { return encodeWorldState(r) }
room, _ := rs.Create(4, true)             // capacity 4, private with a code
join, _ := rs.JoinCode(room.Code(), peer) // or rs.Join(room.ID(), peer)
room.Start()                              // epoch 1, tick 0
room.Advance()                            // tick 1 while running
room.End()
room.Start()                              // epoch 2, tick 0: a fresh match
rs.Leave(room.ID(), peer)
rs.Tick()                                 // close rooms empty for EmptyTimeout
  • A room's Deliver/Recv only accept and expose packets of its own members, so two rooms never see each other's traffic.
  • Join on a running match calls Snapshot and returns it with the current epoch and tick; the joiner applies that full state before deltas.
  • Start after End advances the epoch and resets the tick, so clients can drop the old match's tick state without waiting for the counter to wrap.
  • A private room's Code is accepted by JoinCode; a full room returns ErrRoomFull, an unknown code ErrRoomNotFound.
  • An empty room — whether nobody joined it or its last member left — closes after EmptyTimeout when Tick runs, releasing its ID and private code.

Each room's inbox is bounded per member, like the transports' inboxes, so a match that falls behind its packet loop holds a fixed amount of memory:

rs.SetLimits(gameserver.RoomLimits{PerPeer: 256, Warning: 1024}) // the defaults; applies to open and future rooms
if err := room.Deliver(peer, pkt); errors.Is(err, gameserver.ErrRoomInboxFull) {
	wsServer.Kick(peer, "room inbox full")
}
room.Drain(4, func(p netplay.Packet) { apply(p) }) // up to 4 per member, round robin in join order
stats := room.InboxStats()                          // Queued, Dropped, Refused, Warnings, Backlog
  • A member's queue holds at most PerPeer packets (zero uses DefaultRoomInboxPerPeer, 256; negative removes the cap). A packet that arrives at a full queue evicts that member's oldest unreliable packet; when the queue holds only reliable packets, an arriving unreliable packet is dropped and a reliable one is refused with ErrRoomInboxFull, so the packet loop should disconnect that peer. One member's flood evicts only its own packets.
  • Drain reads every member fairly: each member's oldest packet, then each member's next, up to the budget per member, so a peer that floods the room does not delay the others. Its callback runs without the room's lock held. Members returns peers in join order.
  • InboxStats().Warnings counts once when the room's whole backlog passes Warning and again only after it has fallen to half of it (zero uses DefaultRoomInboxWarning, 1024; negative turns it off).
  • End, Leave (for the leaving member) and Tick closing a room discard the packets still queued.

Rate limits and input validation

Guard enforces a per-peer policy before packets reach a room or simulation:

g := gameserver.NewGuard(gameserver.Limits{
	PacketsPerSecond:   60,
	BytesPerSecond:     64 << 10,
	MaxMessageSize:     8 << 10,
	MaxPendingReliable: 256 << 10,
}, gameserver.LimitDisconnect)
g.Validate = func(peer netplay.PeerID, p netplay.Packet) error { return checkInput(p) }
action, err := g.Check(peer, packet)
if action == server.GuardDisconnect {
	_ = srv.Kick(peer, err.Error()) // end the transport session for good
}
  • Token buckets for packets and bytes with optional bursts; LimitThrottle/LimitDrop refuse the packet and keep the peer connected, LimitDisconnect refuses the peer from then on (GuardDisconnect). GuardDisconnect only flips the guard's own flag, so act on it with Kick on the WebSocketServer or UDPServer, which removes the session for good and tells the client why (see the netplay guide).
  • MaxMessageSize rejects an oversized packet before it is buffered; ReserveReliable/ReleaseReliable bound reserved reliable bytes.
  • Validate runs only for an admitted packet; a non-nil error drops it with ErrInvalidInput, increments that peer's Violations, and never reaches the simulation.
  • Stats(peer) reports packets, bytes, dropped, violations and pending reliable bytes per peer; Reset forgets a reconnecting peer. Per-peer state and O(1) checks leave other peers' ticks unaffected.

The guard is transport-agnostic: call Check at the packet loop and act on the returned GuardAction.

Audit log

audit keeps an append-only record of the server's administrative and security-relevant events — kicks, replaced sessions, operator commands, destructive routes — as JSON Lines, one file per UTC day:

log, err := audit.Open(audit.Options{Dir: "audit", Retain: 30})
log.Log(audit.Record{Actor: "admin:ada", Action: "peer.kick", Subject: "peer:42", Data: map[string]any{"reason": "cheating"}})
// on shutdown, after the runner drains:
log.Close()
  • Each line is one record: {"v":1,"time":"2026-11-28T09:15:02.500Z","actor":"admin:ada","action":"peer.kick","subject":"peer:42","data":{"reason":"cheating"}}; the schema, versioned by each line's v, is on File Formats. Log fills in v, the current time and an empty actor as "system", and a record lands in the file of its own UTC day, so a replayed batch lands in the files of the days it happened.
  • Files are <Dir>/<yyyy-mm-dd>.jsonl, opened append-only and never rewritten, rolled at UTC midnight: greppable, diffable and shippable to a log store, with no database.
  • Log never blocks the tick: records buffer in a queue of Queue (4096 by default), and a full queue drops and counts. Dropped() reports the total, worth exporting on /metrics. One background goroutine appends and fsyncs in batches; Close flushes what remains and returns the first write failure.
  • Retain keeps that many days of files, counting back from the day being written, and deletes older ones as the log rolls; 0 keeps everything.

Peer-to-peer relay

Lockstep and rollback sessions are peer-to-peer, but players behind NAT or in a browser cannot reach each other. netplay.Relay forwards their packets: each player connects to the relay with a netplay.RelayTransport, and the relay passes each frame to the member of the player's session it is addressed to.

relay, err := netplay.NewRelay(netplay.RelayConfig{
	// Check the player's token and name the match it joins; the error text is the rejection reason.
	Join: func(peer netplay.PeerID, token []byte) (string, error) {
		return matchOf(token)
	},
	MaxSessionPeers: 2,
})
auth := relay.Auth(netplay.Auth{GracePeriod: 15 * time.Second})
srv, err := netplay.ListenWebSocketTLSFiles(":443", 1, auth, "cert.pem", "key.pem", nil) // or netplay.ListenUDPServer(":7777", 1, auth)
go relay.Serve(ctx, srv)
cli, err := netplay.DialWebSocket("wss://relay.example.com/", token) // or netplay.DialUDP(addr, serverPubKey, token)
peerTx := netplay.NewRelayTransport(cli, netplay.RelayTransportConfig{})
// Once peerTx.Peers() lists the opponent:
session := netplay.NewRollbackSession(netplay.RollbackConfig{Transport: peerTx, Sim: sim})
  • The relay runs on a WebSocketServer, WebTransportServer, or UDPServer, so every player passes the connection handshake first. relay.Auth runs the base Auth.Verify, when set, and then Join; an empty session name is rejected with no session, and a session that already holds MaxSessionPeers (8 by default) with session full.
  • Frames go only between members of one session. A frame addressed to another session's peer, to the relay, to its sender, or malformed is dropped and counted in Stats().Dropped; RelayTransport.Send refuses an ID outside the session with ErrUnknownPeer.
  • Peers lists the other members, including members inside the grace period, so a session does not lose a player who is reconnecting. The relay sends the membership again every second, so a client whose update was lost on UDP catches up.
  • A player who joins the relay session while a match runs takes part once the match's host admits them with AddPeer, and one who leaves is no longer waited for once the host calls RemovePeer (see the netplay guide).
  • ChannelReliableOrdered is reliable end to end: each message is numbered per peer, the receiver acknowledges it (with a selective acknowledgement of the next 64), and the sender resends what is missing after a timeout adapted to the measured round trip. It works over UDP, and a message the relay could not deliver while a player reconnected with the inner transport's Reconnect arrives once the player is back. At most 1024 messages may wait for acknowledgement per peer; past that Send returns ErrRelayBacklog. A receiver holds at most 4 MB of one peer's messages that arrived ahead of a missing one and drops the rest until they are resent. ChannelUnreliable packets are sent once.
  • When the inner transport's Reconnect admits the player as a new peer instead of resuming, because the grace period passed or the relay restarted, the RelayTransport starts over: it forgets the old members and unacknowledged messages, even when the relay hands out the same ID again, and waits for the new session's membership.
  • Acknowledgements and resends happen inside Recv, which the sessions call every tick through Poll.
  • The relay never reads payloads. It writes to each member on that member's own goroutine through a queue of QueueSize frames (256 by default), so a slow player delays only itself; frames past the queue are dropped, and reliable ones are resent by their sender.
  • A relay serves one server for its lifetime, so WebSocket and UDP players cannot share a session; run one relay per protocol. Serve may be called again on the same server after it returns, and the players still connected keep their sessions. A payload is at most MaxRelayPayload bytes.
  • Client-to-relay UDP links are encrypted and authenticated with Noise NK and ChaCha20-Poly1305 (see the netplay guide); use wss:// for WebSocket links. The relay itself still sees forwarded payloads, as end-to-end encryption between relay peers is out of scope.

Relay latency

BenchmarkRelayRoundTrip in game/online/netplay measures the round trip of a 48-byte message on one machine over the loopback interface. "Direct" is a client and its server, one hop each way; "relay" is two RelayTransports through a local relay, two hops each way, sending reliably as rollback does:

Path Linux x86-64, 24 cores macOS arm64, 10 cores
UDP direct 63 µs 34 µs
UDP through the relay 188 µs 94 µs
WebSocket direct 44 µs 33 µs
WebSocket through the relay 187 µs 87 µs

A local relay adds roughly 55 to 145 µs to a round trip, well under a millisecond and under a tenth of a 60 Hz tick. Over the internet the relay's cost is the extra network distance of the detour, so run relays in the regions where players are. Reproduce the numbers with:

go tool nsgo test ./pkg/online/netplay -run '^$' -bench BenchmarkRelayRoundTrip

WebRTC data channels

Decision: game/online/netplay does not build WebRTC data channels with STUN now; the relay is the path for every peer-to-peer session.

  • WebRTC needs ICE with STUN and TURN, DTLS and SCTP. Browsers provide them through RTCPeerConnection, but native targets would need all of them in Go; NSGo does not expose a platform WebRTC stack, and the only complete Go implementation is a large third-party stack that every native build would carry.
  • A relay is needed anyway: STUN fails behind symmetric NATs, common on mobile carriers, and TURN is itself a relay. Signaling also needs a server.
  • Rollback traffic is small, and a nearby relay adds little latency (see above).

Revisit it when measurements show players near each other but far from every relay region, or when NSGo exposes WebRTC on native targets. The design then is a WebRTC transport behind the same Transport interface that tries a direct path with STUN and falls back to RelayTransport, so sessions do not change.

TLS, origins, health and metrics

A browser on an HTTPS page needs wss:// (WebSocket) or https:// over HTTP/3 QUIC (WebTransport). netplay.ListenWebSocketTLS wraps the WebSocket listener in TLS and checks the browser Origin during the upgrade, ListenWebSocketTLSFiles loads a PEM certificate and key, and ListenWebTransport / ListenWebTransportFiles expose the same Origin policy over QUIC/HTTP/3. All take the same Auth as ListenWebSocket (see the connection handshake):

srv, err := netplay.ListenWebSocketTLSFiles(":443", 1, auth, "cert.pem", "key.pem",
	[]string{"https://game.example.com"})

An Origin outside the allow-list is refused with 403 before the WebSocket handshake; an empty allow-list accepts any Origin and "*" accepts all, while an empty Origin (native game clients) is allowed. Each entry is a scheme://host Origin such as https://game.example.com; a trailing slash is ignored, and an entry that names a path or query makes the listener fail at start-up.

gameserver.Health serves deployment endpoints:

health := gameserver.NewHealth(func() bool { return worldReady() }, func() gameserver.Metrics {
	return gameserver.Metrics{Peers: peers, Rooms: rooms, BytesIn: in, BytesOut: out}
})
http.ListenAndServe(":8080", health)
  • GET /healthz — process liveness;
  • GET /readyz — 200 while Ready returns true, else 503;
  • GET /metrics — Prometheus text metrics (see the table below).

Observe each server tick with health.ObserveTick(time.Since(start)). For per-match detail, set the runner's Health field and it records every match's tick durations itself, and wrap its overrun callback with health.OnOverrun to count overruns and missed ticks per match; an unnamed match is reported as match_<index>. health.AddCollector appends more series on every scrape: gameserver.GuardCollector(guard) exports a guard's totals across every peer it has seen (Guard.Totals keeps a peer's counters after Reset), gameserver.InboxCollector(name, transport) exports a transport's inbox drops and refusals, and any func(io.Writer) adds the game's own series.

Series Type Labels Meaning
nsgo_server_peers gauge Peers connected to this server
nsgo_server_rooms gauge Open rooms
nsgo_server_tick_duration_seconds gauge Last fixed-step duration
nsgo_server_bytes_in_total, nsgo_server_bytes_out_total counter Bytes received and sent
nsgo_server_match_tick_seconds histogram match Per-match tick durations, 0.5 ms to 100 ms buckets
nsgo_server_match_overruns_total counter match Ticks that finished past the next tick's deadline
nsgo_server_match_missed_ticks_total counter match Whole tick intervals those overruns covered
nsgo_server_guard_packets_total, nsgo_server_guard_bytes_total, nsgo_server_guard_dropped_total, nsgo_server_guard_violations_total counter Guard totals across all peers, including forgotten ones
nsgo_net_inbox_unreliable_dropped_total, nsgo_net_inbox_reliable_refused_total, nsgo_net_inbox_reliable_warnings_total counter transport Transport inbox drops, refusals and backlog warnings

Container and draining

Build the example as a static, cgo-free binary and run it as a small container:

FROM golang:1.27 AS build
WORKDIR /src
COPY . .
RUN CGO_ENABLED=0 go -C examples/dedicatedserver build -o /out/server .

FROM gcr.io/distroless/static-debian12
COPY --from=build /out/server /server
ENTRYPOINT ["/server"]

Run it with SIGTERM as the stop signal (docker stop sends SIGTERM by default). The example uses signal.NotifyContext; Runner.Run lets the current tick finish, runs each match's OnStop to notify peers and flush state, then exits, so the container drains instead of losing a tick. The example opens no network listener, so the image declares no port; to expose a health port or add a container health check, mount gameserver.NewHealth on :8080 in your own server (see above).

Player tokens

A dedicated server learns who a player is from a token the player's device got from the account service. It loads the service's key set file once and verifies each token offline with accounts/authtoken, which links none of the account service's password hashing or database drivers:

ks, err := authtoken.ParseKeySet(keysYAML)
v, err := authtoken.NewVerifier(ks)
claims, err := v.Verify(tok) // claims.Subject is the account ID

The token a player sends is for the game's servers, the key set's audience, and whoever runs a server can replay it until it expires; cloud save, the leaderboard and the account service refuse it, so a server cannot reach the player's saves, scores or account with it (see Token audiences). Never forward a player's token to another service, and never ask a player for a token for another audience or for their session.

このページを編集