GitHub시작하기

이 페이지는 아직 한국어로 번역되지 않아 영문 원문을 표시하고 있습니다.

멀티플레이 및 모딩

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.

server.yaml

dedicatedserver init -config server.yaml writes the default configuration, and dedicatedserver serve -config server.yaml starts the listeners, the match and the health endpoint it names. gameserver.ParseConfig reads the file, Config.Marshal writes it back, DefaultConfig returns what init writes, and Config.Validate checks every value. The file is strict: unknown fields, a second YAML document and a version other than 1 are refused with a *loaderr.Error naming the field, and durations are strings such as 15s.

Key Default Meaning
listen.websocket.addr :8443 The WebSocket listener's host:port.
listen.websocket.origins none Browser origins allowed to upgrade, such as https://play.example.com. Only the TLS listener filters origins, so naming any requires tls.
listen.udp.addr :8444 The plain UDP listener's host:port. An address outside listen is not read; set at least one listener.
tls.certFile, tls.keyFile none The server's own certificate and key, so a page on HTTPS connects with wss:// without a reverse proxy. Both or neither.
auth.gracePeriod 15s How long a dropped peer keeps its ID and session.
auth.idleTimeout 10s How long a peer may stay silent before it counts as dropped.
auth.maxPeers 1024 The most sessions held at once, peers inside their grace period included.
limits.policy disconnect What the guard does past a limit: throttle, drop or disconnect.
limits.packetsPerSecond, limits.bytesPerSecond 120, 65536 Per-peer sustained rates; zero disables that bound.
limits.burstPackets, limits.burstBytes none A short burst on top of the sustained rate, one second's rate when omitted.
limits.maxMessageSize 4096 The largest single message, in bytes.
limits.maxPendingReliable none Reliable bytes reserved but not yet released per peer.
rooms.defaultCapacity 4 The seats a room serve opens gets.
rooms.emptyTimeout 2m0s How long an empty room stays open before it is closed.
rooms.maxRooms, rooms.maxMembers none Process-wide room and member caps; zero leaves that cap off.
match.rate 60 Steps per second of the match serve runs.
health.addr :9090 The /healthz, /readyz and /metrics endpoint; empty serves none.

The file holds addresses and file paths, never credentials: a client is admitted by netplay.Auth.Verify in code, not by a secret in server.yaml. The example's serve loop seats each peer in a room, enforces the per-peer limits, relays accepted packets within the room and exposes health; a real server replaces the relay with its own packet handling.

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.

Asynchronous jobs

Use gameserver.Go for blocking work that must report back to a match. The function runs on a worker goroutine, while its callback runs on the match goroutine before a later Update, so the callback can safely mutate match state. A worker panic is recovered as *gameserver.PanicError.

gameserver.Go(match,
	func(ctx context.Context) (PlayerRecord, error) {
		return loadRecord(ctx, playerID)
	},
	func(record PlayerRecord, err error) {
		if err == nil { match.Apply(record) }
	})

match.Serial(key) returns a queue whose jobs run in submission order, which is useful for writes belonging to one player. MaxPending bounds accepted jobs per match and defaults to 256; a rejected job calls its callback with gameserver.ErrBusy. On shutdown, Runner stops accepting jobs, waits up to PendingTimeout (five seconds when zero), and invokes unfinished callbacks with context.DeadlineExceeded before OnStop.

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

Servers can load item and enemy tables through pkg/datatable, which has no NSGo dependency. For one table, take a Table.View at the start of the match. For several tables, register and load a datatable.Set, then assign it to Runner.Data. Before stepping the matches, the runner captures the latest published snapshot for each match whose Match.Data is unset. You can supply an earlier snapshot in Match.Data when replaying a match.

Read the rows from Match.Data and record Match.Data.Version() alongside the game's replay or result. After a successful reload, a new runner can use the new generation while the active matches keep their pinned data.

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 TicketTTL to give new tickets a deadline. Expire removes expired tickets in deterministic order, and Match skips them. Set Teams to a value greater than one to split a room into balanced teams while keeping each party together. The split is deterministic by party size, rating and ticket ID, and is exposed as Matchup.Teams. Enqueue refuses a party larger than one team and a Teams count that does not divide RoomSize, the default rule only adds a party the teams can still hold, and a room a custom Rule returns that cannot be split with every party whole is not formed, so its tickets stay queued.

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.

Ticket properties and count bounds

gameserver.Ticket accepts copied string and numeric properties plus a typed Query. Must and MustNot terms must hold both ways between every pair of tickets in a match, while Should terms can contribute a deterministic score for queue rules. Numeric terms use inclusive NumericRange values, which is suitable for latency properties such as Numbers["ping.eu"].

MinCount, MaxCount and CountMultiple let a queue start with fewer players and fill only valid party-preserving sizes. Zero values retain the previous exact RoomSize behavior. Matchmaker queue operations are safe for concurrent enqueue, cancel, listing and matching.

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

To bind data tables to a room match, call room.StartWithData(set.Current()). Get the epoch and snapshot together with room.MatchData(), then give that snapshot to Match.Data and record its version with the epoch for replays or results. The ended room keeps the pair until the next start.

  • 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.

Capacity and load shedding

The per-room capacity and inbox limits above protect one match. SetCapacity caps the whole process, so a host that is full or behind refuses new matches quickly and the matchmaker places them elsewhere, instead of every running match slowing down:

var overloaded atomic.Bool // set by the game's own load policy, for example from runner overruns
rs.SetCapacity(gameserver.Capacity{MaxRooms: 200, MaxMembers: 800}, overloaded.Load)
if _, err := rs.Create(4, false); errors.Is(err, gameserver.ErrServerBusy) {
	// tell the matchmaker to place this match on another host
}
health := gameserver.NewHealth(func() bool { return worldReady() && !overloaded.Load() }, metrics)
  • Create past MaxRooms, and the join of a new member past MaxMembers (counted across every room, MemberCount), return ErrServerBusy; a zero field leaves that limit off.
  • While the busy callback returns true, Create and the join of a new member return ErrServerBusy too. A member already in the room keeps resuming with Join, and Leave and Tick work as before, so running matches drain normally.
  • The callback runs with no Rooms or Room lock held, so it may call List or MemberCount. The rule deciding when the host is busy (an overrun ratio over a window, hysteresis so it does not flap) is the game's; feed the same flag to /readyz so a load balancer stops sending players while it is set.

Broadcast groups

Room.Broadcast sends one payload to the room's current members, and Group is an ordered peer set for anything else that receives the same message, such as a team or a match's spectators:

failed := room.Broadcast(tx, netplay.ChannelReliableOrdered, msg, sender) // everyone but the sender
var red gameserver.Group
red.Add(peer)                                                           // false if already a member
failed = red.Broadcast(tx, netplay.ChannelUnreliable, state)
red.Remove(peer)                                                        // on PeerLeft
  • Both send in join order through netplay.SendMany and return the peers whose send failed, in that order, so the caller can kick or remove exactly those peers; a nil result means every send was accepted.
  • except skips peers such as the sender. Group.Add ignores PeerBroadcast and peers already in the group; Group is safe for concurrent use.
  • A Group does not follow the transport's membership: remove a peer when NextEvent reports it left.

Match lifecycle handlers

A room may attach a gameserver.MatchHandler before admitting peers. JoinWithMeta calls JoinAttempt before taking a seat, then calls Joined after admission. Returning false leaves the room unchanged and returns the handler's reason. LeaveWithReason reports quit, dropped, kicked or replaced departures through Left. Room.Signal invokes the handler with a copied message, while Room.Terminate calls Terminate(grace) before ending the room. Room.SetLabel replaces searchable metadata copied into RoomInfo.Label.

The legacy Join and Leave methods remain valid and use empty metadata and the quit reason. Callbacks should finish quickly and coordinate any longer work through the server's match mailbox.

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

Health answers the three endpoints through package servicehealth, which the account, cloud save and leaderboard daemons serve theirs with too (see Health and metrics), so every service answers its probes, methods and unknown paths the same way.

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).

Graceful WebSocket handoff

To restart a server without refusing new players, open the TCP listener in a parent process or let systemd socket activation open it, and give the same socket to every server process that serves it through netplay.ServeWebSocket instead of ListenWebSocket. Once the replacement process accepts on the socket, the old process calls StopAccepting: new clients reach only the replacement, while the old process keeps serving the clients it already has until their rooms end, then calls Close. ServeWebSocket takes ownership of the listener, so StopAccepting and Close both close the old process's copy; wrap the listener with tls.NewListener to serve wss://. Passing the descriptor to the new process and waiting for it to be ready is up to the deployment for now. A client of the old process cannot resume its session in the new one, because session secrets live in process memory; it reconnects as a new peer. UDP sockets are not shared this way, because two processes reading one datagram socket split its packets at random: start the new process's UDP server on a new port and send new rooms there.

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.

Seat reservations and server directories

Rooms.Reserve holds a named account seat until its TTL (15 seconds when zero) and counts it against the room's capacity. Rooms.Claim converts a live reservation into a connected member in the same locked step that checks capacity, so no other join can take the seat in between, and a claim the match handler refuses keeps the reservation. SignReservation and SignedReservation.Verify wrap a reservation in an Ed25519 signature for offline verification. MemoryDirectory tracks process heartbeats, removes expired servers, and chooses the least-loaded live server for a region. Postgres-backed directory and matchmaker wiring remain deployment-specific.

Idempotent match results

gameserver.ResultsBackend provides the result-commit boundary for finished matches. Commit validates the grants, then applies record grants, wallet grants and best-score grants under one lock keyed by MatchID. Retrying the same result is a no-op that returns a receipt with Applied false, while a different payload for the same match ID, or a record grant whose Version is not the stored record's version (0 for a record that does not exist yet), is ErrResultConflict and applies nothing. A committed record grant stores the record at Version+1, so a second match that read the same version conflicts. An empty match ID, record key, wallet account or currency, score board or account, or a record key granted twice is ErrResultInvalid, refused before anything changes. Score grants stay in an outbox until DeliverScores hands them to a ScoreSink; a failed delivery leaves that grant and the ones after it queued for the next call, so a leaderboard outage is retried. Record, Balance and BestScore read the committed state, and PendingScores lists the queued score grants. The backend keeps everything in memory, so a process crash loses the outbox; a persistent adapter maps the same contract to one database transaction.

For a room match, set ResultCommit.Epoch and ResultCommit.DataVersion from the pair returned by Room.MatchData(). Receipts repeat those values. A retry for the same match ID must use the original epoch and version along with the original grants.

Match mailbox and one-writer state

A Match owns its game state on its runner goroutine. Use Post for bounded FIFO work that should run before a future Update, and Call when an outside goroutine needs a result. Post never blocks. It returns ErrMailboxFull when the configured capacity is reached (1024 by default), and ErrMatchStopped after shutdown. The runner drains at most 64 callbacks per tick, so a burst spreads across ticks. When the match stops, queued work is dropped and a pending Call returns ErrMatchStopped. A panic in a queued callback is handled like a panic in Update: Runner.OnPanic chooses between stopping the match and crashing, and the Call that queued it returns ErrMatchStopped. Keep callbacks short, never Call a match from its own goroutine (it blocks until the context ends), and route room-scoped handlers through this mailbox instead of touching match state directly. The mailbox does not make UDP or HTTP handlers safe to read game state synchronously.

Live inspection and pprof

Mount gameserver.NewInspector(authorize) only on an authenticated admin listener; a nil callback refuses every request with 401, and the handler answers only GET. It never registers on http.DefaultServeMux, and a player-facing listener has no inspection endpoint unless you mount the handler there yourself. The callback owns authentication and should not hold a match lock while it runs. Each request reads its view afresh:

  • /admin/v1/runtime: the process's JSON runtime view (goroutines, heapBytes, heapInUse, numGC, gcPauseTotalNs).
  • /admin/v1/matches, /admin/v1/rooms and /admin/v1/peers, when Inspector.Provider is set: JSON lists of InspectMatch (name, rate, ticks, overruns), InspectRoom (id, state, members, created) and InspectPeer (id, room, inbox) from an InspectProvider the application implements over its own state. Return snapshots; never hold a match lock across the response.
  • /admin/v1/pprof/<name>, when Inspector.Pprof is true: any profile runtime/pprof knows by name, such as goroutine, heap or mutex, and /admin/v1/pprof/profile?seconds=N for an N-second CPU profile (default 30, at most 300; 409 while another CPU profile runs). A profile comes in the protobuf form go tool pprof reads, or as text with ?debug=1. Profiling is off by default, so a handler mounted for its JSON views serves no profiles.

For operators listed in an operators file, build the inspector with gameserver.NewOperatorInspector(srv) from an admin.Server and mount it on that server with srv.Mount: a request without a session or an admin bearer token gets 401, and an operator without server.read (server.pprof for the profiles) gets 403, which the server records in its audit log.

The Inspect state dump of one match and a game server inspect subcommand remain to be added.

See Deploying backend services for production store and daemon topology.

이 페이지 편집