@typeonce/ritmo-netcode
v0.28.0
Published
Rollback and lockstep sessions over any transport for Ritmo: input timelines, checkpoint history, pacing, resync, and desync checks
Maintainers
Readme
@typeonce/ritmo-netcode
Online multiplayer for ritmo: peers that run the same simulation and agree on it. A session per peer exchanges inputs over any transport and ticks the simulation with every seat's input: Netcode.rollback runs at once on guesses and rolls back when real input contradicts one (with the runtime's checkpoints); Netcode.lockstep waits for every seat's input. Sessions start and resync every peer from one save, pace the peer that runs ahead, compare checksums to catch a desync the tick it happens, and play on when a seat leaves.
pnpm add @typeonce/ritmo-netcode @typeonce/ritmoThe package carries no server and opens no connection: a NetworkLink wraps one the game made. WebSocketNetworkLink.make(socket) (to a relay that forwards every message to the other peers) and WebRtcNetworkLink.make(channel) (straight between peers) ship here; any other transport, an Effect Socket for example, implements the three methods of NetworkLink. MemoryNetworkLink.make(...) joins peers in one process with seeded latency, jitter, and loss, for headless tests.
import { Descriptor, FixedLoop } from "@typeonce/ritmo"
import { BrowserHostClock, BrowserTickSource, BrowserVisibility, InputCapture } from "@typeonce/ritmo-browser"
import { Netcode, WebSocketNetworkLink } from "@typeonce/ritmo-netcode"
// The simulation reads every seat's input from one source, captured once per tick.
const Seats = Descriptor.Service<Netcode.Source<PlayerInput>>()("Game/Seats")
const Inputs = Descriptor.TransientResource<InputCapture.SnapshotOf<typeof Seats>>()("Game/Inputs")
const Capture = InputCapture.system(Game, { name: "Game/Capture", source: Seats, resource: Inputs })
const simulate = Game.Schedule(Capture, Move, Fire)
// PlayerInput here is the game's own Standard Schema: every seat's input, the local one too, is decoded with it.
const seats = Netcode.seats(PlayerInput, { count: 2, idle: { dx: 0, fire: false } })
if (!seats.ok) throw new Error(seats.error.reason)
const session = Netcode.rollback(
(source) => Game.Runtime.make({
services: Game.Runtime.services(Game.Runtime.service(Seats, source)),
resources: { Time: Clock.start(step), Inputs: [] },
checkpoints: 16
}),
{
simulate,
seats: seats.value,
seat: 0, // seat 0 hosts: it starts the match and answers resyncs, until it leaves
links: [WebSocketNetworkLink.make(socket)],
hostClock: BrowserHostClock.make(window),
step,
hidden: { visibility: BrowserVisibility.make(document), afterMS: 30_000, policy: "resync-on-return" }
}
)
if (!session.ok) throw new Error(session.error._tag)
FixedLoop.start({
source: BrowserTickSource.make(window), step, maxFrameSeconds: 0.25, maxStepsPerFrame: 5,
rate: session.value.rate, // slows this peer while it runs ahead of the others
// Advances the session each step. A halt (a desync, a failed tick) is reported and answered with a resync.
update: session.value.update({ input: readLocalInput, onHalted: (error) => console.error(error) }),
render: () => session.value.render(draw),
onFailure: (failure) => showDisconnected(failure) // the session ended: this page is out of the match or the last one in it (Disconnected's `who`), or the peers run different versions
})One socket for the lobby and the match
A page usually keeps one WebSocket to its room, for the lobby's messages and the match's. WebSocketNetworkLink.shared(socket) splits it in two: link for the session, and channel for the game's own texts, which it sends and reads as they are. Neither sees the other's messages.
const socket = new WebSocket("wss://relay.example.com/room/42")
const { link, channel } = WebSocketNetworkLink.shared(socket)
channel.send(JSON.stringify({ ready: true }))
for (const text of channel.receive()) lobby.show(JSON.parse(text)) // each frame: never a session messageThe session's messages start with a reserved character ("\u0001") that a JSON text never starts with; literal strings starting with it do not compile on channel.send, and dynamic ones return Result.failure(ReservedPrefix). The relay is the game's own code (a Cloudflare Worker, a Node server), and needs one rule on such a socket:
// For each text message from a page:
if (WebSocketNetworkLink.isSession(text)) for (const other of room.others(from)) other.send(text) // untouched
else room.handle(from, text) // the lobby'sThe framing is part of the session protocol, so the relay and every page run the same release, as for any protocol change. Both link and channel read closed once the socket closes. A WebRTC data channel needs none of this: open a channel of its own for the match beside the lobby's.
Traffic
A session says everything of one frame in one message per link: driven by session.update from a FixedLoop, that is one per host frame however many steps the frame ran (a frame that runs none sends nothing); each advance called directly is a frame of its own. A relay that bills per message (a Cloudflare Durable Object) sees one message per peer per frame, so a link sends each as it is, with no outbox or batching of its own. A game whose update wraps the session's passes both of the loop's arguments through:
const tick = session.value.update({ input: readLocalInput, onHalted: (error) => console.error(error) })
FixedLoop.start({ ...loop, update: (seconds, at) => tick(seconds, at) })Each message still carries every input a peer has not acknowledged, so one that is lost costs nothing the next one does not repeat, but it writes each distinct input once (a held input is two numbers however many ticks it was held). The input's saved form (what seats' schema encodes) is the rest of the weight: a small one, such as a packed integer, is the lightest. status().sent counts the messages handed to the links and their bytes in UTF-8; read it twice for a rate. Over 120 ms with 60 ms of jitter and 5% loss, 8 peers at 60 Hz on pages that sometimes run two or three steps in a frame send about 390 messages and 70 to 100 KiB a second in all.
Input delay
A session records the local input for a tick a few ticks ahead (inputDelay, 2 by default): a little lag that lets the input reach the other peers before its tick runs, so rollback guesses less often and lockstep waits less. The right value depends on the connection, which changes during a match. Give adaptiveDelay instead and the session moves the delay with the measured round trip:
Netcode.rollback(makeRuntime, { ...options, adaptiveDelay: { min: 1, max: 4 } })
session.status().inputDelay // the delay in use; status().delayChanges counts movesIt starts at max and moves to ceil(roundTripMS / 2 / step ms) (the round trip to the slowest other seat, smoothed), clamped to the bounds, once that target held for 4 measurements in a row (one every 250 ms), so a noisy link does not move it back and forth. Each seat moves only its own delay: every input message names its tick, so peers never agree on a change and seats may run different delays. A rise leaves the ticks it skips idle (seats.idle); a fall drops the local input for as many frames (Advanced.input is undefined). Giving both inputDelay and adaptiveDelay does not compile. Peers exchange inputDelay / adaptiveDelay.max on match start and end with OptionsMismatch if they disagree.
In tests, link.setLatency(ms) on a MemoryNetworkLink changes a peer's latency mid-match.
What does not compile: a rollback simulate that cannot be rewound (a service with effects, local state; a library that keeps its own world, like a physics engine, is provided through Checkpoint.rewindable from @typeonce/ritmo instead), a schedule whose requirements the runtime does not provide, and both inputDelay and adaptiveDelay. What fails at construction, as a typed Result: a seat out of range, seats the runtime does not provide or another session took, and a maxRollback larger than the checkpoints the runtime keeps.
Effects under rollback
A rollback runs ticks again, and a tick run again publishes its events again: a sound played from an event would play once per run. Host code (sound, particles, a message to a server) reads the simulation's events through the session, one reader per place that acts on them:
const hits = session.events(Hit) // an event of the runtime's schema; one reader per call
// After each frame's steps (in FixedLoop's render):
for (const { tick } of hits.withdrawn()) particles.cancel(tick) // a rollback undid this tick's hits
for (const { tick, value } of hits.predicted()) particles.burst(tick, value.at) // may still be undone
for (const { value } of hits.confirmed()) sounds.play(value.kind) // exactly once per hit
const lost = hits.lost() // EventsLost: a reader that stopped reading, a resync that replaced confirmed ticks, or ticks a save made final that this peer did not run as the host did; never silentconfirmed()hands out each event once, when its tick can no longer run again within the epoch. A lockstep session confirms every tick it runs. A peer ahead of seat 0 can confirm a tick or two that seat 0's next save makes idle: when the resync runs them again with other events,lost()reports them withreason: "resync", and the new run is not handed out again.predicted()hands out events of ticks that may still be rolled back. A tick a rollback runs again keeps what was handed out when it publishes the same events (plain data, compared by value); otherwise it is withdrawn and its new events are predicted again.- A save (the match's start, a resync, a seat seated again after a reload or a hidden tab) makes every tick before it final as the host's world went through it, guesses included. Each peer confirms the ticks it ran with the same inputs as the host (the save carries them), and the host confirms every tick it ran. The ticks before the save that a peer ran otherwise, or did not run, are reported by
lost()withreason: "save", and what was predicted of them is withdrawn. A page the save seats for its first match (one that loaded again) is told nothing of the ticks before it: the save's world holds them. From the save's tick on, every peer confirms each tick once. withdrawn()names those ticks, so the host cancels what it started. A save withdraws every predicted tick from its own tick on, which runs again. A tick waiting to be withdrawn is held back frompredicted()untilwithdrawn()named it, so a cancel never undoes the new run.- A reader that does not call
confirmed()for more thanRuntime.eventWindowticks loses the oldest:lost()reports them asEventsLostwithreason: "unread". One report per call: a"resync"one first, then"save", then"unread". - Under a session, read events only through
session.events(...). The runtime's ownruntime.events(...)is for a host that ticks the runtime itself: under rollback it reports every rollback as lost (reason: "rewind") and hands out the ticks run again a second time. Both hand out the sameRuntime.EventRecord. For the devtools lints, list the events the session reads ashostReadsin the lint target.
When checksums differ, advance fails with Desynced until resync(). With keepSnapshots: true it carries this peer's save of that tick; Desync.compare(mine, theirs) from @typeonce/ritmo-devtools lists what differs.
Hidden tabs
A browser stops a hidden tab's animation frames, so that peer sends nothing, and after timeoutMS the others count it out and play on without it (see Seats that leave). With the hidden option, the session hears the moment its page hides (Visibility, a contract: BrowserVisibility.make(document) from @typeonce/ritmo-browser, MemoryVisibility.make() in tests), tells the others, and they apply the policy:
const session = Netcode.rollback(makeRuntime, {
...options,
hidden: { visibility: BrowserVisibility.make(document), afterMS: 30_000, policy: "resync-on-return" }
})
// The HUD: session.status().hidden[seat] is true while that seat's tab is hidden ("waiting for Ada").The announcement carries the inputs the others still need, goes out several times, and every peer that heard it passes it on with its pings while the seat is hidden, so it survives a link that loses messages (a WebRTC channel with maxRetransmits: 0). With two seats no other peer can pass it on: it is lost only when all five copies are.
"stall": the others wait for the hidden seat's input, as for a slow one (rollback runsmaxRollbackticks on guesses, then stalls), and it goes on from where it stopped when it shows again."resync-on-return": the others play on with idle input for the hidden seat after its last sent input. When it shows again, the host sends a save and it restores it, as inresync(); until then itsadvanceisWaiting. The host (the lowest seat playing: seat 0 until it leaves) is never played around, since every save is its world: while it is hidden, the others wait for it.
The bound: a hidden seat's silence counts only after afterMS, so a seat that hides and never returns (the tab was closed) is out of the match at most afterMS + timeoutMS after it hid: from then on the simulation reads seats.left for it, and status().left names it. If its page does show again later, a save seats it again. Pass hidden: "none" for headless peers or bots; peers that disagree on afterMS or policy end with OptionsMismatch on match start. The session unsubscribes from the visibility once it ends, or leaves (session.leave()). On return, FixedLoop drops the hidden time beyond maxFrameSeconds and maxStepsPerFrame, so the loop does not burst through the missed frames. Pausing a single-player game on a hidden tab is the game's own policy (read BrowserVisibility in host code).
Seats that leave
A match outlives the seats that leave it. A seat is out of the match once it sent nothing for timeoutMS (5000 by default), once the link that carried it closed (one link per peer), once the game tells a session that its transport saw the seat go, or once its own session leaves:
// A relay sees a socket close long before timeoutMS: tell the session.
room.onPlayerGone((seat) => session.drop(seat))
// The player quits the race and goes back to the lobby, on a socket the lobby keeps.
loop.stop()
session.leave()session.leave() tells the other peers at once (its last inputs, then that it leaves, a few times against loss), and they count the seat out with reason: "left" about one round trip later, the host too, with no timeoutMS to wait. A peer that missed it hears it from the others. The session then ends: every later advance fails with Disconnected (who: "self", reason: "left"), a FixedLoop driven by update stops, and the session unsubscribes from the hidden visibility. It closes no link, since the socket may be the lobby's. A second call does nothing. Before the match starts it ends the session too, and seat 0 forgets its hello: the match waits for a new session of that seat, which is the lobby's to start or call off.
One peer that knows is enough, since it tells the others: a relay can tell every page, and in a mesh the peer whose channel closed learns it from its own link. The peers still playing then agree on the seat's last input and go on, with no save and no restart:
const seats = Netcode.seats(PlayerInput, {
count: 8,
idle: { steer: 0, gone: false },
left: { steer: 0, gone: true } // what the simulation reads for a seat that left (idle when omitted)
})
// In a system, the game decides what a seat without a driver does: park it, remove it, hand it to a bot.
if (inputs[car.seat]?.gone) park(car)
// In host code, for the HUD ("Ada left"):
session.status().left[seat] // undefined, or { reason: "timeout" | "closed" | "dropped" | "restarted" | "left", lastInput, tick }- Every peer agrees on the tick. Each peer stops taking the seat's inputs and reports the last one it has. The seat's own inputs end at the furthest one any of them received (
lastInput), and fromtickon, the same on every peer, the simulation readsseats.leftfor it. That is a value in the simulation's input like any other, so what the game does with it is rewound, replayed and checksummed with the rest. - Events stay exact. No peer confirmed a tick past its own report, so no confirmed tick runs again:
session.events(...)readers lose and repeat nothing. Ticks a peer ran on a guess of the seat's input are withdrawn and predicted again, as after any wrong guess. - No seat is special. The host is the lowest seat still playing. When seat 0 leaves, the next seat answers
resync(), seats the sessions that come back, and decides who else is out. - How long the others wait. They run
maxRollbackticks on guesses, then stall (status().waitingnames the seat) until they agree it is gone:timeoutMSfor a seat that went silent, about one round trip after adropor a closed link. - Coming back. A seat that left gets its seat back with a save, as a hidden seat does: when its session reaches the others again (the same page, over a link the game reconnected), or when a new session says hello for the seat (the page reloaded: build the runtime and the session again, with the same
seat). From that save's tick the simulation reads its real input again. Until the save arrives itsadvanceisWaitingandstatus().leftnames its own seat; without one fortimeoutMS, it ends withDisconnected. - When a session ends. With
Disconnected, whosewhosays which message to show."others": everyone else left, andseatis the last other seat that was in the match (reasonis why it left)."self": this session is the one out, andseatis its own: it left ("left", afterleave()), every link closed ("closed"), another page took its seat ("restarted"), or the others went on without it and no save seated it again. A match of two therefore ends as before when the other seat leaves: aftertimeoutMS, or at once ondrop. What changed for two: a page that reloads withintimeoutMSgets its seat back instead of ending both. - Before the match starts, nothing times out. A match begins once every seat said hello; a seat that never does (a tab closed while the game loads) leaves every session
Waiting, anddropdoes nothing there, since there is no match to play on. What to do about a seat that never arrives is the lobby's job: end those sessions and start a match with the seats that are there.
The seat that decides is the lowest one playing, and its word counts over a higher seat's. So a seat dropped by mistake while it still reaches the others is put out and seated again a moment later, and a drop of the host counts only once no playing peer hears it: until then the session that called it is the one put out, and seated again. A page that froze for longer than timeoutMS (a suspended laptop, a debugger) is counted out like any silent seat, the host too, and seated again when it wakes: a session knows from its own clock that it was the silent one. In a mesh, when the channel between two peers closes, one of them is out for good, since no save could bring it back to a peer it cannot reach: its session ends.
What does not survive: a match whose every playing page is gone at once, with only hidden pages left under "resync-on-return", since nobody holds the world they would resync from; they end with Disconnected when they show again. And a match still starts only once every seat said hello: a session cannot take a seat that was never in the match, and there are no spectators.
In tests, close a seat's MemoryNetworkLink and stop advancing it. Fuzz.run with network.leave in @typeonce/ritmo-devtools makes seats leave on seeded frames, so what the game does with seats.left is fuzzed too.
Stalls
advance returns Stalled while it waits for another seat's input (lockstep at once, rollback maxRollback ticks past it). status().waiting names what it waits for, { seat, tick, forMS }, or is undefined while it runs, so a HUD can say "waiting for seat 1" and a headless test can say why a match stopped. A seat that stays silent is out of the match after timeoutMS, and the others run again.
Sync test
A rollback game is only as good as the code it rewinds. Netcode.syncTest runs one peer with no network, forces a rollback of rewind ticks after every tick, runs those ticks again with the same input, and compares the world's checksum at the start of each one with the first run's. State a rewind cannot put back (a module variable, a service with its own memory) fails the test on the first tick it matters, where two real peers would only desync later. Run it in the game's tests before shipping:
const test = Netcode.syncTest(makeRuntime, { simulate, seats: seats.value, rewind: 8, keepSnapshots: true })
if (!test.ok) throw new Error(test.error.reason)
for (const local of scriptedInput) {
const advanced = test.value.advance(local) // seat 0's input; every other seat gets `predict` of its previous one
if (!advanced.ok && advanced.error._tag === "RewindDiffers") {
// The world at the start of `tick` differs: tick `tick - 1` read state outside the world.
console.log(advanced.error.tick, Desync.compare(advanced.error.snapshots!.expected, advanced.error.snapshots!.actual).text)
}
}It takes rollback's types: a simulate that cannot be rewound does not compile here either, and a rewind deeper than the runtime's checkpoints fails at construction. status() counts the forced rollbacks. A failure (RewindDiffers, TickFailed, CheckpointLost, or SyncFailed when the world does not checksum) is final: fix the game. To shake out peers over a faulty network, Fuzz.run with network in @typeonce/ritmo-devtools drives rollback sessions over a seeded MemoryNetworkLink.
Released together with @typeonce/ritmo, always with the same version.
Source: https://github.com/typeonce-dev/ritmo
