diff --git a/.changeset/fixed-loop-step-in-frame.md b/.changeset/fixed-loop-step-in-frame.md new file mode 100644 index 00000000..63f0428c --- /dev/null +++ b/.changeset/fixed-loop-step-in-frame.md @@ -0,0 +1,7 @@ +--- +"@typeonce/ritmo": minor +--- + +`FixedLoop`'s `update` gets a second argument, `at: FixedLoop.StepInFrame`: `at.last` is true on the frame's last update (by the accumulator and `maxStepsPerFrame`), for code that acts once per frame after its steps, as a networked session does to send what the frame said in one message. An `update` that takes no arguments is unchanged. + +The `ritmo` skill's netcode playbook says that a session sends one message per link per frame and repeats what was lost, so a link sends each message as it is (no outbox or batching of its own), that a game's `update` around `session.update` passes the loop's arguments through, and to measure with `status().sent`. diff --git a/.changeset/netcode-one-message-per-frame.md b/.changeset/netcode-one-message-per-frame.md new file mode 100644 index 00000000..12b55cca --- /dev/null +++ b/.changeset/netcode-one-message-per-frame.md @@ -0,0 +1,26 @@ +--- +"@typeonce/ritmo-netcode": minor +--- + +**A session sends one message per link per frame, and lighter ones.** Until now a session handed its links a message for each thing it said (inputs, checksums, pings, pongs), every step, so a frame that ran several steps sent several of each, and a relay that bills per message (a Cloudflare Durable Object) paid for all of them. Now everything one frame says goes out as one message per link, a bundle: driven by `session.update` from a `FixedLoop`, one per host frame however many steps it ran; each `advance` called directly is a frame of its own. + +- A bundle names the protocol, the sender, and its epoch once. It still carries every input a peer has not acknowledged (a lost message costs nothing the next one does not repeat), but writes each distinct input once and which of them each tick had: a held input is two numbers however many ticks it was held. Acknowledgements are written as how far behind the sender's tick they are. +- A message that must survive loss (a seat reported gone, a change of who plays) goes out with the next five frames' bundles instead of five times in one frame. A page that hides still sends its announcement five times at once: no frame follows. +- `status().sent` counts the messages handed to the links and their bytes in UTF-8. + +Over 120 ms with 60 ms of jitter and 5% loss, on pages at 60 Hz that sometimes run two or three steps in a frame: 2 peers went from 139 messages and 62 KiB a second to 97 and 16 to 23 KiB; 8 peers from 728 and 290 KiB to 387 and 73 to 103 KiB (the lower figure for input held 20 frames, the higher for input that changes nearly every frame). + +**Breaking: every page of a match must run this version.** The session protocol changed (version 5): a peer on 0.26 or older ends with `ProtocolMismatch`. + +**Breaking: the function `session.update(...)` returns takes the loop's two arguments.** Passed to `FixedLoop.start` as it is, nothing changes. Called from the game's own `update`, pass them through, so the session knows the frame's last step: + +```diff + const tick = session.update({ input: readInput, onHalted }) + FixedLoop.start({ + ...loop, +- update: () => tick(), ++ update: (seconds, at) => tick(seconds, at), + }) +``` + +A link that batched the session's messages itself (an outbox flushed once per task) can send each as it is now. diff --git a/packages/core/bench/baseline.json b/packages/core/bench/baseline.json index 9811ad3b..309ea0df 100644 --- a/packages/core/bench/baseline.json +++ b/packages/core/bench/baseline.json @@ -3,241 +3,241 @@ "tolerance": 0.25, "allocationTolerance": 0.1, "allocationSlackBytes": 1024, - "calibrationMs": 2.9835, + "calibrationMs": 2.9794, "environment": "Apple M1 / node v24.16.0 / darwin", "cases": { "top-down/frame-x60": { - "minMs": 0.3947, - "medianMs": 0.4264, - "score": 0.1316, - "bytesPerRun": 791188 + "minMs": 0.3933, + "medianMs": 0.4095, + "score": 0.1319, + "bytesPerRun": 791068 }, "random/next-100k": { - "minMs": 0.793, - "medianMs": 0.8086, - "score": 0.2644, - "bytesPerRun": 800335 + "minMs": 0.7935, + "medianMs": 0.7993, + "score": 0.2661, + "bytesPerRun": 800328 }, "random/draw-resource-100k": { - "minMs": 3.8234, - "medianMs": 3.9643, - "score": 1.2749, - "bytesPerRun": 3060234 + "minMs": 3.7912, + "medianMs": 3.8564, + "score": 1.2725, + "bytesPerRun": 3060597 }, "ops/steer-10k": { - "minMs": 0.908, - "medianMs": 0.9547, - "score": 0.3023, - "bytesPerRun": 1760392 + "minMs": 0.8736, + "medianMs": 0.891, + "score": 0.2931, + "bytesPerRun": 1760399 }, "clock/advance-1000": { - "minMs": 0.1623, - "medianMs": 0.181, - "score": 0.0544, - "bytesPerRun": 423932 + "minMs": 0.1643, + "medianMs": 0.1802, + "score": 0.0551, + "bytesPerRun": 423904 }, "spawn/10k-3c": { - "minMs": 6.8922, - "medianMs": 7.1016, - "score": 2.2982, - "bytesPerRun": 20430330 + "minMs": 6.5764, + "medianMs": 6.9084, + "score": 2.2054, + "bytesPerRun": 20430358 }, "despawn/10k": { - "minMs": 9.6658, - "medianMs": 11.2189, - "score": 3.2231, - "bytesPerRun": 9099760 + "minMs": 9.4083, + "medianMs": 10.7152, + "score": 3.1551, + "bytesPerRun": 9099753 }, "query/iterate-read-10k-of-20k": { - "minMs": 0.0797, - "medianMs": 0.0829, - "score": 0.0265, + "minMs": 0.0791, + "medianMs": 0.0794, + "score": 0.0266, "bytesPerRun": 1648 }, "query/optional-read-20k": { - "minMs": 0.2029, - "medianMs": 0.208, - "score": 0.0677, + "minMs": 0.2091, + "medianMs": 0.2123, + "score": 0.0701, "bytesPerRun": 1629 }, "query/rows-10k": { - "minMs": 0.4956, - "medianMs": 0.5048, - "score": 0.1653, + "minMs": 0.4833, + "medianMs": 0.488, + "score": 0.1621, "bytesPerRun": 1041966 }, "query/iterate-write-10k": { - "minMs": 0.1798, - "medianMs": 0.1953, - "score": 0.0603, + "minMs": 0.1716, + "medianMs": 0.1737, + "score": 0.0575, "bytesPerRun": 401491 }, "query/number-write-10k": { "minMs": 0.0983, - "medianMs": 0.1013, - "score": 0.0327, + "medianMs": 0.0991, + "score": 0.033, "bytesPerRun": 1473 }, "query/set-raw-10k": { - "minMs": 0.6286, - "medianMs": 0.678, - "score": 0.2096, + "minMs": 0.6508, + "medianMs": 0.6681, + "score": 0.2183, "bytesPerRun": 1281581 }, "entity-state/update-transition-10k": { - "minMs": 1.5723, - "medianMs": 1.9196, - "score": 0.5243, - "bytesPerRun": 3583323 + "minMs": 1.5572, + "medianMs": 1.8858, + "score": 0.5225, + "bytesPerRun": 3583296 }, "machine/update-10k": { - "minMs": 2.6962, - "medianMs": 2.7534, - "score": 0.899, + "minMs": 2.4407, + "medianMs": 2.467, + "score": 0.8192, "bytesPerRun": 5522969 }, "query/single-in-20k-x1000": { "minMs": 0.1616, - "medianMs": 0.164, - "score": 0.0539, + "medianMs": 0.1636, + "score": 0.0542, "bytesPerRun": 288321 }, "query/changed-100-of-10k-x20": { - "minMs": 0.1989, - "medianMs": 0.2035, - "score": 0.0663, + "minMs": 0.1983, + "medianMs": 0.2018, + "score": 0.0666, "bytesPerRun": 341047 }, "structural/insert-remove-1k": { "minMs": 0.1804, - "medianMs": 0.1926, + "medianMs": 0.1989, "score": 0.0605, - "bytesPerRun": 666319 + "bytesPerRun": 666333 }, "schedule/100-systems-x10": { - "minMs": 0.0416, - "medianMs": 0.0448, - "score": 0.014, - "bytesPerRun": 9634 + "minMs": 0.0421, + "medianMs": 0.0428, + "score": 0.0141, + "bytesPerRun": 9627 }, "schedule/150-systems-thistick-x10": { - "minMs": 0.0866, - "medianMs": 0.0886, - "score": 0.0288, + "minMs": 0.0846, + "medianMs": 0.0859, + "score": 0.0284, "bytesPerRun": 18377 }, "lookup/get-10k": { - "minMs": 0.6422, - "medianMs": 0.66, - "score": 0.2138, - "bytesPerRun": 1617 + "minMs": 0.6451, + "medianMs": 0.6554, + "score": 0.2163, + "bytesPerRun": 1609 }, "events/emit-read-10k": { - "minMs": 0.0958, - "medianMs": 0.099, - "score": 0.032, - "bytesPerRun": 248139 + "minMs": 0.0961, + "medianMs": 0.098, + "score": 0.0322, + "bytesPerRun": 248132 }, "relations/descendants-100x100": { - "minMs": 0.2976, - "medianMs": 0.3034, - "score": 0.0992, + "minMs": 0.2997, + "medianMs": 0.3065, + "score": 0.1006, "bytesPerRun": 329778 }, "snapshot/json-roundtrip-10k": { - "minMs": 21.874, - "medianMs": 22.5813, - "score": 7.294, - "bytesPerRun": 32366761 + "minMs": 21.531, + "medianMs": 22.8133, + "score": 7.2266, + "bytesPerRun": 32366705 }, "frame/50-systems-5k": { - "minMs": 1.7777, - "medianMs": 1.8718, - "score": 0.5918, - "bytesPerRun": 3031185 + "minMs": 1.7606, + "medianMs": 1.8217, + "score": 0.5909, + "bytesPerRun": 3031199 }, "checkpoint/take-tick-10k": { - "minMs": 0.2767, - "medianMs": 0.3001, - "score": 0.0927, - "bytesPerRun": 514931 + "minMs": 0.2641, + "medianMs": 0.2766, + "score": 0.0886, + "bytesPerRun": 514982 }, "checkpoint/rollback-8-of-5k": { - "minMs": 2.6436, - "medianMs": 2.8452, - "score": 0.8801, + "minMs": 2.694, + "medianMs": 2.8384, + "score": 0.9042, "bytesPerRun": 4515720 }, "math/vec2-steer-10k": { - "minMs": 1.2167, - "medianMs": 1.2957, - "score": 0.4051, - "bytesPerRun": 3567291 + "minMs": 1.2133, + "medianMs": 1.2387, + "score": 0.4071, + "bytesPerRun": 3567298 }, "math/scalar-spring-10k": { - "minMs": 0.5461, - "medianMs": 0.5595, - "score": 0.1821, + "minMs": 0.5456, + "medianMs": 0.5533, + "score": 0.1831, "bytesPerRun": 1655520 }, "math/flow-field-search": { - "minMs": 0.1872, - "medianMs": 0.1953, - "score": 0.0624, - "bytesPerRun": 382 + "minMs": 0.1869, + "medianMs": 0.1958, + "score": 0.0627, + "bytesPerRun": 375 }, "math/flow-field-way-1k": { - "minMs": 0.0924, - "medianMs": 0.0943, - "score": 0.0308, + "minMs": 0.0923, + "medianMs": 0.0959, + "score": 0.031, "bytesPerRun": 116471 }, "math/collide-move-circle-1k": { - "minMs": 0.5152, - "medianMs": 0.5274, - "score": 0.1718, - "bytesPerRun": 246848 + "minMs": 0.5119, + "medianMs": 0.5151, + "score": 0.1717, + "bytesPerRun": 246855 }, "math/collide-move-circle-segments-1k": { - "minMs": 2.2302, - "medianMs": 2.2964, + "minMs": 2.2272, + "medianMs": 2.2433, "score": 0.7475, - "bytesPerRun": 254535 + "bytesPerRun": 254542 }, "netcode/rollback-frame-2-peers": { - "minMs": 0.0659, - "medianMs": 0.0904, - "score": 0.0219, - "bytesPerRun": 190837 + "minMs": 0.0607, + "medianMs": 0.0715, + "score": 0.0204, + "bytesPerRun": 189691 }, "netcode/lockstep-frame-2-peers": { - "minMs": 0.0089, - "medianMs": 0.0099, - "score": 0.003, - "bytesPerRun": 26215 + "minMs": 0.0086, + "medianMs": 0.0093, + "score": 0.0029, + "bytesPerRun": 25170 }, "render/sync-1k-changed-of-10k": { - "minMs": 0.2317, - "medianMs": 0.2585, - "score": 0.0772, + "minMs": 0.2211, + "medianMs": 0.2379, + "score": 0.0741, "bytesPerRun": 326545 }, "render/sync-hierarchy-1k-changed-of-10k": { - "minMs": 0.4137, - "medianMs": 0.458, - "score": 0.1377, + "minMs": 0.4022, + "medianMs": 0.4301, + "score": 0.135, "bytesPerRun": 366447 }, "render/sync-spawn-despawn-500": { - "minMs": 1.4494, - "medianMs": 1.6079, - "score": 0.4825, - "bytesPerRun": 1892511 + "minMs": 1.428, + "medianMs": 1.5785, + "score": 0.4789, + "bytesPerRun": 1892532 }, "render/interpolate-10k": { - "minMs": 0.2897, - "medianMs": 0.2958, - "score": 0.0971, + "minMs": 0.2911, + "medianMs": 0.2955, + "score": 0.0976, "bytesPerRun": 1489 } } @@ -246,8 +246,8 @@ "tolerance": 0.05, "typescript": "Version 7.0.2", "metrics": { - "types": 138626, - "instantiations": 1516105 + "types": 138656, + "instantiations": 1516132 } } } diff --git a/packages/core/dtslint/FixedLoop.tst.ts b/packages/core/dtslint/FixedLoop.tst.ts index cef837bb..7e39f874 100644 --- a/packages/core/dtslint/FixedLoop.tst.ts +++ b/packages/core/dtslint/FixedLoop.tst.ts @@ -32,6 +32,11 @@ describe("FixedLoop.start", () => { }) }) + it("tells update where its step falls in the frame", () => { + expect["update"]>>().type.toBe<[stepSeconds: number, at: FixedLoop.StepInFrame]>() + expect().type.toBe<{ readonly last: boolean }>() + }) + it("reads an optional rate per frame", () => { expect["rate"]>().type.toBe<(() => number) | undefined>() expect, { readonly kind: "InvalidRate" }>>().type.toBe<{ readonly kind: "InvalidRate"; readonly rate: number }>() diff --git a/packages/core/skills/ritmo/playbooks/netcode.md b/packages/core/skills/ritmo/playbooks/netcode.md index 789e804f..bf038c2b 100644 --- a/packages/core/skills/ritmo/playbooks/netcode.md +++ b/packages/core/skills/ritmo/playbooks/netcode.md @@ -14,6 +14,7 @@ - **A seat leaves and the match plays on.** What a seat without a driver does is a rule of the game, so it lives in the simulation: give `Netcode.seats` a `left` input no player can send, and let one system read it (park it, remove it, hand it to a bot). Never decide it in host code from `status().left`: that is for the HUD, and peers would disagree. - **Tell the session what the transport knows.** A relay sees a socket close at once: pass it on with `session.drop(seat)`, or every player waits `timeoutMS` behind a stall. Wait before calling it only if a short disconnect should stall the match instead of costing the seat. - **`onFailure` means this page is out, or alone.** `Disconnected.who` says which, and each gets its own message. Other seats leaving never reach it. +- **A link sends each message as it is.** A session says one message per link per host frame when `session.update` drives it, however many steps the frame ran, and repeats what a lossy link lost, so a link adds no outbox, batching, or copies of its own. A game's own `update` that wraps `session.update` passes the loop's two arguments through. Measure with `status().sent`, and keep the input's saved form small: it is what goes over the wire. - **A page that comes back builds its session again.** After a reload, make the runtime and the session for the same seat: the match seats it with a save. Nothing of the old page carries over. Order matters for the proofs, which come before shipping: diff --git a/packages/core/src/FixedLoop.ts b/packages/core/src/FixedLoop.ts index 22b85591..3ac8fc3f 100644 --- a/packages/core/src/FixedLoop.ts +++ b/packages/core/src/FixedLoop.ts @@ -136,10 +136,26 @@ export interface Driver extends Subscription { reset(): void } +/** + * Where one fixed update falls in its host frame, the second argument of + * `update`. `last` is true when no further update runs in this frame, by + * the accumulator and `maxStepsPerFrame`: code that should act once per + * frame after its updates (a networked session sending what the frame's + * steps said) acts on it. A `reset()` or `stop()` from an earlier update + * ends the frame before the update that would have been `last`. + */ +export interface StepInFrame { + readonly last: boolean +} + +const lastStep: StepInFrame = { last: true } +const notLastStep: StepInFrame = { last: false } + /** Input for a fixed-step driver. */ export interface StartOptions extends Options { readonly source: TickSource - readonly update: (stepSeconds: number) => Result.Result + /** One fixed update: `stepSeconds` is `step.dt`, and `at` where it falls in the host frame. */ + readonly update: (stepSeconds: number, at: StepInFrame) => Result.Result readonly render: (frame: Frame) => void readonly onFailure: (failure: Failure) => void /** @@ -238,7 +254,9 @@ export const start = ( let fixedSteps = 0 while (accumulator >= options.step.dt && fixedSteps < options.maxStepsPerFrame) { const resetsBefore = resets - const update = options.update(options.step.dt) + // The loop's own condition, as it will read after this update. + const last = !(accumulator - options.step.dt >= options.step.dt && fixedSteps + 1 < options.maxStepsPerFrame) + const update = options.update(options.step.dt, last ? lastStep : notLastStep) if (!update.ok) { fail({ kind: "UpdateFailure", error: update.error }) return diff --git a/packages/core/test/FixedLoop.test.ts b/packages/core/test/FixedLoop.test.ts index 1d00a7bd..d717e7b2 100644 --- a/packages/core/test/FixedLoop.test.ts +++ b/packages/core/test/FixedLoop.test.ts @@ -44,6 +44,35 @@ describe("FixedLoop.start", () => { expect(stopped).toBe(false) }) + it("tells each update whether it is the frame's last", () => { + let tick: ((value: FixedLoop.Tick) => void) | undefined + const lasts: Array> = [] + const driver = FixedLoop.start({ + source: FixedLoop.source((onTick) => { + tick = onTick + return { stop: () => {} } + }), + step: Clock.hz(100), + maxFrameSeconds: 0.1, + maxStepsPerFrame: 3, + update: (_, at) => { + lasts[lasts.length - 1]!.push(at.last) + return Result.success(undefined) + }, + render: () => {}, + onFailure: () => { + throw new Error("unexpected loop failure") + } + }) + expect(driver.ok).toBe(true) + // Two steps and a half; one more with the half; none; then more than maxStepsPerFrame allows. + for (const deltaMS of [25, 10, 4, 100]) { + lasts.push([]) + tick?.({ deltaMS }) + } + expect(lasts).toEqual([[false, true], [true], [], [false, false, true]]) + }) + it("bounds catch-up work and reports expected update failures", () => { let tick: ((value: FixedLoop.Tick) => void) | undefined let stopCount = 0 diff --git a/packages/netcode/README.md b/packages/netcode/README.md index 8e75e381..4955fc51 100644 --- a/packages/netcode/README.md +++ b/packages/netcode/README.md @@ -47,6 +47,17 @@ FixedLoop.start({ }) ``` +## 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: + +```ts +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: diff --git a/packages/netcode/dtslint/Netcode.tst.ts b/packages/netcode/dtslint/Netcode.tst.ts index ef2d2c08..932adedc 100644 --- a/packages/netcode/dtslint/Netcode.tst.ts +++ b/packages/netcode/dtslint/Netcode.tst.ts @@ -249,6 +249,20 @@ describe("session.update", () => { expect(session.value.update).type.not.toBeCallableWith({ input: () => ({ dx: "left" }), onHalted: () => {} }) }) + it("needs the loop's step, to send once per frame, when called from the game's own update", () => { + const session = Netcode.rollback(runtime, { ...options, simulate }) + if (!session.ok) return + const tick = session.value.update({ input: () => ({ dx: 0 }), onHalted: () => {} }) + FixedLoop.start({ + source: FixedLoop.source(() => ({ stop() {} })), step, maxFrameSeconds: 0.25, maxStepsPerFrame: 5, + update: (seconds, at) => tick(seconds, at), + render: () => {}, + onFailure: () => {} + }) + // @ts-expect-error Expected 2 arguments, but got 0 + tick() + }) + it("narrows a halt from an end", () => { const error = {} as Netcode.SessionError<"Overflow"> if (Netcode.isHalted(error)) expect(error).type.toBe>() @@ -337,6 +351,14 @@ describe("status().waiting", () => { }) }) +describe("status().sent", () => { + it("counts the messages and bytes handed to the links", () => { + const session = Netcode.rollback(runtime, { ...options, simulate }) + if (!session.ok) return + expect(session.value.status().sent).type.toBe<{ readonly messages: number; readonly bytes: number }>() + }) +}) + describe("a seat that leaves", () => { it("is dropped by its number, and nothing comes back", () => { const session = Netcode.rollback(runtime, { ...options, simulate }) diff --git a/packages/netcode/src/Netcode.ts b/packages/netcode/src/Netcode.ts index cdf69094..b99607ab 100644 --- a/packages/netcode/src/Netcode.ts +++ b/packages/netcode/src/Netcode.ts @@ -102,7 +102,7 @@ * }) * ``` */ -import type { Clock, HostClock } from "@typeonce/ritmo" +import type { Clock, FixedLoop, HostClock } from "@typeonce/ritmo" import type * as Checkpoint from "@typeonce/ritmo/Checkpoint" import type * as Descriptor from "@typeonce/ritmo/Descriptor" import * as Result from "@typeonce/ritmo/Result" @@ -391,6 +391,15 @@ export interface Status { * play on. */ readonly waiting: { readonly seat: number; readonly tick: number; readonly forMS: number } | undefined + /** + * What this session handed its links, in total: `messages`, one per open + * link per frame that said anything, and their `bytes` in UTF-8. A + * session says everything of one frame in one message, however many steps + * the frame ran (when driven by `update`; each `advance` called directly + * is a frame of its own), so a relay that bills per message sees one per + * peer per frame. Read it twice to measure a rate for a budget. + */ + readonly sent: { readonly messages: number; readonly bytes: number } } /** One event the simulation published, and the session tick that published it. */ @@ -481,7 +490,9 @@ export interface Session number /** * The `update` of the `FixedLoop` that drives this session: each step - * advances it with `input()`. A halt is reported to `onHalted` once (a - * desync is a bug in the game's determinism: log it) and answered with - * `resync()`, and the loop keeps running; the loop stops with the error - * once the session ended. + * advances it with `input()`, and what the frame's steps say goes out as + * one message per link after its last step (`FixedLoop.StepInFrame`). A + * halt is reported to `onHalted` once (a desync is a bug in the game's + * determinism: log it) and answered with `resync()`, and the loop keeps + * running; the loop stops with the error once the session ended. + * + * Pass it to `FixedLoop.start` as it is, or call it from the loop's own + * `update` with both of the loop's arguments: `(seconds, at) => tick(seconds, at)`. */ readonly update: (options: { /** This seat's input for the step, read once per step. */ readonly input: () => Input readonly onHalted: (error: Halted) => void - }) => () => Result.Result + }) => (stepSeconds: number, at: FixedLoop.StepInFrame) => Result.Result readonly status: () => Status /** * A new host reader of `descriptor`'s events, an event of the runtime's diff --git a/packages/netcode/src/NetworkLink.ts b/packages/netcode/src/NetworkLink.ts index 111d6cff..94e99c41 100644 --- a/packages/netcode/src/NetworkLink.ts +++ b/packages/netcode/src/NetworkLink.ts @@ -7,7 +7,10 @@ * to every other peer. Every message names the seat it comes from, so a * session does not care which. The session owns what the text says (inputs, * checksums, saves); a link only carries it, in any order, and may lose - * some: sessions repeat what was not acknowledged. + * some: sessions repeat what was not acknowledged. A session hands its + * link one message per frame (everything that frame's steps said, when + * `session.update` drives it), so a link sends each as it is, with no + * batching or copies of its own. * * Opening a connection, signaling, retrying, and reconnecting belong to the * game, before and around the link: an adapter wraps a connection that is diff --git a/packages/netcode/src/internal/session.ts b/packages/netcode/src/internal/session.ts index 2e9cb161..424e1e25 100644 --- a/packages/netcode/src/internal/session.ts +++ b/packages/netcode/src/internal/session.ts @@ -274,6 +274,8 @@ export const make = (mode: Mode, runtime: Driven, options: MakeOptions): Result. let suspects = 0 /** Reports go out at once, not with the next ping. */ let reportNow = false + /** The frames a new report still goes out in, against loss. */ + let reportFrames = 0 /** Per seat, what each peer reported of it in this epoch: its last input there, and the inputs it carried. */ const reports: Array }>> = Array.from({ length: count }, () => new Map()) /** The changes of the roster in this epoch, by the roster each made, to pass on. */ @@ -329,9 +331,61 @@ export const make = (mode: Mode, runtime: Driven, options: MakeOptions): Result. let held: Array = [] let unsubscribe: (() => void) | undefined + // What this session says goes out once per frame, as one bundle per link. + /** The messages said since the last flush. */ + const outbox: Array = [] + /** Messages to say again with the next flushes, once each (`left` stays in the outbox `copies - 1` more frames), against loss. */ + let repeats: Array<{ readonly message: Wire.Message; left: number }> = [] + /** Bundles handed to the links, and their UTF-8 bytes: one per open link per flush. */ + let sentMessages = 0 + let sentBytes = 0 + + /** + * Says `message` with this frame's bundle. An `inputs` or `hello` replaces + * the one said before it in the frame: each says everything the earlier + * one did, and more. + */ const broadcast = (message: Wire.Message): void => { - const text = Wire.write(message) - for (let index = 0; index < options.links.length; index++) if (!linkClosed[index]) options.links[index]!.send(text) + if (message.k === "inputs" || message.k === "hello") { + for (let earlier = 0; earlier < outbox.length; earlier++) { + if (outbox[earlier]!.k !== message.k) continue + outbox[earlier] = message + return + } + } + outbox.push(message) + } + + /** Says `messages` now and with each of the next `copies - 1` flushes: one bundle more lost does not lose them. */ + const broadcastCopies = (messages: ReadonlyArray): void => { + for (const message of messages) { + broadcast(message) + repeats.push({ message, left: copies - 1 }) + } + } + + /** Hands the outbox to every open link as one bundle. */ + const flush = (): void => { + if (outbox.length === 0) return + const text = Wire.write(seat, epoch, outbox) + outbox.length = 0 + const bytes = Wire.utf8Length(text) + for (let index = 0; index < options.links.length; index++) { + if (linkClosed[index]) continue + options.links[index]!.send(text) + sentMessages += 1 + sentBytes += bytes + } + } + + /** At the start of a frame's bundle: the copies still owed. */ + const sayRepeats = (): void => { + if (repeats.length === 0) return + for (const repeat of repeats) { + outbox.push(repeat.message) + repeat.left -= 1 + } + repeats = repeats.filter((repeat) => repeat.left > 0) } /** Whether `other` plays: in the match, and not played around while its page is hidden. */ @@ -1012,7 +1066,7 @@ export const make = (mode: Mode, runtime: Driven, options: MakeOptions): Result. changes.set(head.roster, parts) applyChange(parts[0]!, carried) if (ended !== undefined) return - for (let copy = 0; copy < copies; copy++) for (const part of parts) broadcast(part) + broadcastCopies(parts) } /** A save: this peer's match starts again from it, when it is in it. */ @@ -1162,7 +1216,13 @@ export const make = (mode: Mode, runtime: Driven, options: MakeOptions): Result. const parsed = Wire.parse(text, count) if (parsed._tag === "Malformed") dropped += 1 else if (parsed._tag === "OtherVersion") end({ _tag: "ProtocolMismatch", version: parsed.version }) - else receive(parsed.message, index) + else { + dropped += parsed.malformed + for (const message of parsed.messages) { + receive(message, index) + if (ended !== undefined) return + } + } if (ended !== undefined) return } const status = link.status() @@ -1279,7 +1339,8 @@ export const make = (mode: Mode, runtime: Driven, options: MakeOptions): Result. const now = clock.now() if (now - lastPing >= pingEveryMS) { lastPing = now - broadcast({ k: "ping", from: seat, epoch, session: sessionId, at: now, shown: tracker.shown[seat]! }) + // To the millisecond: a round trip needs no finer, and the digits would go out four times a second. + broadcast({ k: "ping", from: seat, epoch, session: sessionId, at: Math.round(now), shown: tracker.shown[seat]! }) announce() adapt() } @@ -1290,12 +1351,13 @@ export const make = (mode: Mode, runtime: Driven, options: MakeOptions): Result. return } // The seats this peer stopped waiting for, until they are out: at once, then with every ping. A peer played around has no say. - if (suspects > 0 && (reportNow || pinged) && !Hidden.away(tracker, seat)) { - for (let copy = reportNow ? copies : 1; copy > 0; copy--) { - for (let other = 0; other < count; other++) if (suspected[other] !== undefined) for (const part of reportOn(other)) broadcast(part) - } - } + // A new report goes out with the next `copies` frames, then with every ping. + if (reportNow) reportFrames = copies reportNow = false + if (suspects > 0 && (reportFrames > 0 || pinged) && !Hidden.away(tracker, seat)) { + for (let other = 0; other < count; other++) if (suspected[other] !== undefined) for (const part of reportOn(other)) broadcast(part) + } + if (reportFrames > 0) reportFrames -= 1 if (wantSync && now - lastResyncAsk >= pingEveryMS) { lastResyncAsk = now broadcast({ k: "resync", from: seat, epoch }) @@ -1413,7 +1475,29 @@ export const make = (mode: Mode, runtime: Driven, options: MakeOptions): Result. waitingTick = tick } - const advance = (pressed: unknown): Result.Result> => { + /** Whether this frame's bundle is open: a step of the frame ran, and its last one has not. */ + let inFrame = false + + /** + * One step of a frame: `last` is false while more steps of the same frame + * follow, and what the step says waits for the frame's bundle. + */ + const advanceStep = (pressed: unknown, last: boolean): Result.Result> => { + if (!inFrame) { + inFrame = true + sayRepeats() + } + const advanced = advanceOnce(pressed) + if (last) { + inFrame = false + flush() + } + return advanced + } + + const advance = (pressed: unknown): Result.Result> => advanceStep(pressed, true) + + const advanceOnce = (pressed: unknown): Result.Result> => { const waitedOn = waitingSeat waitingSeat = -1 if (ended !== undefined) return Result.failure(ended) @@ -1513,8 +1597,8 @@ export const make = (mode: Mode, runtime: Driven, options: MakeOptions): Result. update: (step) => { // One report per halt: the session stays halted until the resync's save arrives. let reported = false - return () => { - const advanced = advance(step.input()) + return (_stepSeconds, at) => { + const advanced = advanceStep(step.input(), at.last) if (advanced.ok) { reported = false return Result.success(undefined) @@ -1543,7 +1627,8 @@ export const make = (mode: Mode, runtime: Driven, options: MakeOptions): Result. roundTripMS: roundTrip.map((value, other) => other === seat ? 0 : value), hidden: tracker.hides.map((_, other) => gone[other] === undefined && hiddenNow(other)), left: gone.slice(), - waiting: waitingSeat === -1 ? undefined : { seat: waitingSeat, tick: waitingTick, forMS: Math.max(0, clock.now() - waitingSince) } + waiting: waitingSeat === -1 ? undefined : { seat: waitingSeat, tick: waitingTick, forMS: Math.max(0, clock.now() - waitingSince) }, + sent: { messages: sentMessages, bytes: sentBytes } }), events: (descriptor) => { let ledger = ledgers.get(descriptor) @@ -1567,7 +1652,11 @@ export const make = (mode: Mode, runtime: Driven, options: MakeOptions): Result. if (nowHidden) { hide() // Now, and more than once: a hidden page's frames stop, so these may be its last messages for a while. - for (let copy = 0; copy < copies; copy++) for (const part of announcements[seat]!) broadcast(part) + // Each copy is a bundle of its own: no frame follows to carry the next. + for (let copy = 0; copy < copies; copy++) { + for (const part of announcements[seat]!) broadcast(part) + flush() + } return } Hidden.show(tracker, seat) diff --git a/packages/netcode/src/internal/wire.ts b/packages/netcode/src/internal/wire.ts index 1bb617dd..921ece07 100644 --- a/packages/netcode/src/internal/wire.ts +++ b/packages/netcode/src/internal/wire.ts @@ -1,12 +1,17 @@ /** - * The session protocol: JSON messages, each with the protocol version, the - * seat that sent it, and the save number (epoch) it knows. Parsed once - * here; the session trusts the shapes after that. Inputs stay in their - * saved form until the session decodes them with the game's schema. + * The session protocol: what a session says in one frame goes out as one + * text, a bundle: the protocol version, the seat that sent it, the save + * number (epoch) it knows, and its messages, each of which names its own + * epoch only when that is another one. A run of inputs is written as the + * distinct inputs once and which of them each tick had (a held input is + * one pair of numbers, not a value per tick), and acknowledgements as how + * far behind the sender's next tick they are. Parsed once here; the + * session trusts the shapes after that. Inputs stay in their saved form + * until the session decodes them with the game's schema. */ /** Bumped when a message changes shape; peers on another version fail with `ProtocolMismatch`. */ -export const version = 4 +export const version = 5 /** * Why a seat is out of the match: it sent nothing for too long, its link @@ -191,11 +196,17 @@ export interface Out extends Base { export type Message = Hello | Sync | Resync | Inputs | Sum | Ping | Pong | Hidden | Gone | Left | Out +/** + * A bundle's messages, and how many of them were malformed (dropped, the + * rest kept), or a bundle that is malformed as a whole, or of another + * version. + */ export type Parsed = - | { readonly _tag: "Message"; readonly message: Message } + | { readonly _tag: "Bundle"; readonly messages: ReadonlyArray; readonly malformed: number } | { readonly _tag: "Malformed" } | { readonly _tag: "OtherVersion"; readonly version: unknown } + const isTick = (value: unknown): value is number => Number.isSafeInteger(value) && (value as number) >= -1 const isTime = (value: unknown): value is number => typeof value === "number" && Number.isFinite(value) const isCount = (value: unknown): value is number => Number.isSafeInteger(value) && (value as number) >= 0 @@ -203,9 +214,127 @@ const isWhy = (value: unknown): value is Why => whys.includes(value) const isSeat = (value: unknown, seats: number): value is number => Number.isSafeInteger(value) && (value as number) >= 0 && (value as number) < seats -const malformed: Parsed = { _tag: "Malformed" } +const malformed = { _tag: "Malformed" } as const + +const isRecord = (value: unknown): value is Record => typeof value === "object" && value !== null && !Array.isArray(value) + +const isIndex = (index: unknown, length: number): index is number => Number.isSafeInteger(index) && (index as number) >= 0 && (index as number) < length + +/** + * A run of inputs as written: `d`, each distinct input once, and which of + * them each tick had, as `i` (an index into `d` per tick) or as `r` (pairs + * of an index and how many ticks in a row had it), whichever is shorter. + * `undefined` when malformed or longer than `most`. Reads `i` in place: the + * parsed array is this message's own. + */ +const readInputs = (value: Record, most: number): ReadonlyArray | undefined => { + const distinct = value["d"] + if (!Array.isArray(distinct)) return undefined + let inputs: Array + if ("r" in value) { + const runs = value["r"] + if ("i" in value || !Array.isArray(runs) || runs.length % 2 !== 0) return undefined + inputs = [] + for (let at = 0; at < runs.length; at += 2) { + const index = runs[at] + const length = runs[at + 1] + if (!isIndex(index, distinct.length) || !Number.isSafeInteger(length) || length < 1 || inputs.length + length > most) return undefined + for (let tick = 0; tick < length; tick++) inputs.push(distinct[index]) + } + } else { + const indices = value["i"] + if (!Array.isArray(indices) || indices.length > most) return undefined + for (let at = 0; at < indices.length; at++) { + const index: unknown = indices[at] + if (!isIndex(index, distinct.length)) return undefined + indices[at] = distinct[index] + } + inputs = indices + } + // Every distinct input is one some tick had. + return distinct.length > inputs.length ? undefined : inputs +} + +/** + * Whether two inputs in their saved form (plain JSON data) are the same + * value: compared in place, since a session compares each of its inputs it + * has not seen acknowledged in every frame's bundle. + */ +const same = (a: unknown, b: unknown): boolean => { + if (a === b) return true + if (typeof a !== "object" || typeof b !== "object" || a === null || b === null) return false + if (Array.isArray(a) || Array.isArray(b)) { + if (!Array.isArray(a) || !Array.isArray(b) || a.length !== b.length) return false + for (let index = 0; index < a.length; index++) if (!same(a[index], b[index])) return false + return true + } + const left = a as Record + const right = b as Record + let keys = 0 + for (const key in left) { + keys += 1 + if (!(key in right) || !same(left[key], right[key])) return false + } + for (const _ in right) keys -= 1 + return keys === 0 +} -/** Parses one message for a match of `seats` seats. */ +/** Writes a run of inputs into `into` as `d` and `i` or `r` (see {@link readInputs}). */ +const writeInputs = (inputs: ReadonlyArray, into: Record): void => { + const d: Array = [] + const indices: Array = new Array(inputs.length) + let runs = 0 + for (let tick = 0; tick < inputs.length; tick++) { + // A value JSON cannot write (a tick with no input) arrives as null, as it did in a plain array. + const raw = inputs[tick] + const input = raw === undefined ? null : raw + // Few inputs are distinct: a search beats a map. + let index = -1 + for (let at = 0; at < d.length && index === -1; at++) if (same(d[at], input)) index = at + if (index === -1) { + index = d.length + d.push(input) + } + if (tick === 0 || indices[tick - 1] !== index) runs += 1 + indices[tick] = index + } + into["d"] = d + // A held input is one run: a pair instead of an index per tick. + if (runs * 2 >= indices.length) { + into["i"] = indices + return + } + const pairs: Array = new Array(runs * 2) + let at = -2 + for (let tick = 0; tick < indices.length; tick++) { + if (tick > 0 && indices[tick] === indices[tick - 1]) pairs[at + 1]! += 1 + else { + at += 2 + pairs[at] = indices[tick]! + pairs[at + 1] = 1 + } + } + into["r"] = pairs +} + +/** + * Acknowledgements as written: per seat, how far behind `next` the tick is + * (a small number, where the tick itself grows all match long). Read in + * place: the parsed array is this message's own. + */ +const readAcks = (value: unknown, next: number, seats: number): ReadonlyArray | undefined => { + if (!Array.isArray(value) || value.length !== seats) return undefined + for (let seat = 0; seat < seats; seat++) { + const behind: unknown = value[seat] + if (!Number.isSafeInteger(behind)) return undefined + const ack = next - (behind as number) + if (!isTick(ack)) return undefined + value[seat] = ack + } + return value as Array +} + +/** Parses one bundle for a match of `seats` seats. */ export const parse = (text: string, seats: number): Parsed => { let raw: unknown try { @@ -213,75 +342,87 @@ export const parse = (text: string, seats: number): Parsed => { } catch { return malformed } - if (typeof raw !== "object" || raw === null || Array.isArray(raw)) return malformed - const value = raw as Record - if (value["v"] !== version) return { _tag: "OtherVersion", version: value["v"] } - const from = value["from"] - const epoch = value["epoch"] - if (!Number.isSafeInteger(from) || (from as number) < 0 || (from as number) >= seats || !isTick(epoch) || epoch < 0) return malformed - const base = { from: from as number, epoch } + if (!isRecord(raw)) return malformed + if (raw["v"] !== version) return { _tag: "OtherVersion", version: raw["v"] } + const from = raw["from"] + const epoch = raw["epoch"] + const list = raw["m"] + if (!Number.isSafeInteger(from) || (from as number) < 0 || (from as number) >= seats || !isTick(epoch) || epoch < 0 || !Array.isArray(list)) return malformed + // Each message takes the place of its text in the parsed list, and a malformed one is dropped from it. + let kept = 0 + for (let index = 0; index < list.length; index++) { + const parsed = parseOne(list[index], from as number, epoch, seats) + if (parsed !== undefined) list[kept++] = parsed + } + const dropped = list.length - kept + if (dropped > 0) list.length = kept + return { _tag: "Bundle", messages: list as Array, malformed: dropped } +} + +/** One message of a bundle from `from`, whose epoch is the bundle's unless the message names its own (`undefined`: malformed). */ +const parseOne = (raw: unknown, from: number, bundleEpoch: number, seats: number): Message | undefined => { + if (!isRecord(raw)) return undefined + const value = raw + const epoch = "epoch" in value ? value["epoch"] : bundleEpoch + if (!isTick(epoch) || epoch < 0) return undefined switch (value["k"]) { case "hello": - if (!isTime(value["session"])) return malformed - return { _tag: "Message", message: { k: "hello", ...base, session: value["session"] } } + if (!isTime(value["session"])) return undefined + return { k: "hello", from, epoch, session: value["session"] } case "resync": - return { _tag: "Message", message: { k: "resync", ...base } } + return { k: "resync", from, epoch } case "sync": { const returned = value["returned"] const sessions = value["sessions"] - if (!isTick(value["tick"]) || value["tick"] < 0 || !("save" in value)) return malformed - if (!Array.isArray(returned) || returned.length !== seats || !returned.every(isCount)) return malformed - if (!Array.isArray(sessions) || sessions.length !== seats || !sessions.every(isTime)) return malformed + if (!isTick(value["tick"]) || value["tick"] < 0 || !("save" in value)) return undefined + if (!Array.isArray(returned) || returned.length !== seats || !returned.every(isCount)) return undefined + if (!Array.isArray(sessions) || sessions.length !== seats || !sessions.every(isTime)) return undefined const left = value["left"] - if (!isCount(value["roster"]) || !Array.isArray(left) || left.length !== seats || !left.every((why) => why === null || isWhy(why))) return malformed + if (!isCount(value["roster"]) || !Array.isArray(left) || left.length !== seats || !left.every((why) => why === null || isWhy(why))) return undefined const ahead = value["ahead"] - if (!Array.isArray(ahead) || ahead.length !== seats || !ahead.every((inputs) => Array.isArray(inputs) && inputs.length <= maxInputsAhead)) return malformed - return { _tag: "Message", message: { k: "sync", ...base, tick: value["tick"], save: value["save"], returned, sessions, roster: value["roster"], left, ahead } } + if (!Array.isArray(ahead) || ahead.length !== seats || !ahead.every((inputs) => Array.isArray(inputs) && inputs.length <= maxInputsAhead)) return undefined + return { k: "sync", from, epoch, tick: value["tick"], save: value["save"], returned, sessions, roster: value["roster"], left, ahead } } case "inputs": { - const acks = value["acks"] - const inputs = value["inputs"] - if (!isCount(value["roster"]) || !isTick(value["next"]) || !isTick(value["start"]) || value["start"] < 0) return malformed - if (!Array.isArray(acks) || acks.length !== seats || !acks.every(isTick) || !Array.isArray(inputs)) return malformed - if (inputs.length > maxInputsPerMessage) return malformed - return { _tag: "Message", message: { k: "inputs", ...base, roster: value["roster"], next: value["next"], acks, start: value["start"], inputs } } + const inputs = readInputs(value, maxInputsPerMessage) + if (!isCount(value["roster"]) || !isTick(value["next"]) || !isTick(value["start"]) || value["start"] < 0) return undefined + const acks = readAcks(value["acks"], value["next"], seats) + if (acks === undefined || inputs === undefined) return undefined + return { k: "inputs", from, epoch, roster: value["roster"], next: value["next"], acks, start: value["start"], inputs } } case "sum": - if (!isCount(value["roster"]) || !isTick(value["tick"]) || typeof value["sum"] !== "string" || value["sum"].length > sumLength) return malformed - return { _tag: "Message", message: { k: "sum", ...base, roster: value["roster"], tick: value["tick"], sum: value["sum"] } } + if (!isCount(value["roster"]) || !isTick(value["tick"]) || typeof value["sum"] !== "string" || value["sum"].length > sumLength) return undefined + return { k: "sum", from, epoch, roster: value["roster"], tick: value["tick"], sum: value["sum"] } case "ping": - if (!isTime(value["session"]) || !isTime(value["at"]) || !isCount(value["shown"])) return malformed - return { _tag: "Message", message: { k: "ping", ...base, session: value["session"], at: value["at"], shown: value["shown"] } } + if (!isTime(value["session"]) || !isTime(value["at"]) || !isCount(value["shown"])) return undefined + return { k: "ping", from, epoch, session: value["session"], at: value["at"], shown: value["shown"] } case "pong": { const to = value["to"] - if (!isTime(value["at"]) || !Number.isSafeInteger(to) || (to as number) < 0 || (to as number) >= seats) return malformed - return { _tag: "Message", message: { k: "pong", ...base, to: to as number, at: value["at"] } } + if (!isTime(value["at"]) || !Number.isSafeInteger(to) || (to as number) < 0 || (to as number) >= seats) return undefined + return { k: "pong", from, epoch, to: to as number, at: value["at"] } } case "hidden": { const seat = value["seat"] - const inputs = value["inputs"] - if (!Number.isSafeInteger(seat) || (seat as number) < 0 || (seat as number) >= seats) return malformed - if (!isCount(value["roster"]) || !isCount(value["n"]) || value["n"] < 1 || !isTick(value["last"]) || typeof value["away"] !== "boolean") return malformed - if (!isCount(value["start"]) || !Array.isArray(inputs) || inputs.length > maxInputsPerMessage) return malformed + const inputs = readInputs(value, maxInputsPerMessage) + if (!Number.isSafeInteger(seat) || (seat as number) < 0 || (seat as number) >= seats) return undefined + if (!isCount(value["roster"]) || !isCount(value["n"]) || value["n"] < 1 || !isTick(value["last"]) || typeof value["away"] !== "boolean") return undefined + if (!isCount(value["start"]) || inputs === undefined) return undefined // The inputs it carries are its own, so they end at `last` at the latest. - if (value["start"] + inputs.length - 1 > value["last"]) return malformed - return { - _tag: "Message", - message: { k: "hidden", ...base, roster: value["roster"], seat: seat as number, n: value["n"], last: value["last"], away: value["away"], start: value["start"], inputs } - } + if (value["start"] + inputs.length - 1 > value["last"]) return undefined + return { k: "hidden", from, epoch, roster: value["roster"], seat: seat as number, n: value["n"], last: value["last"], away: value["away"], start: value["start"], inputs } } case "gone": { const seat = value["seat"] - const inputs = value["inputs"] - if (!isSeat(seat, seats) || seat === from || !isWhy(value["why"]) || !isTick(value["have"])) return malformed - if (!isCount(value["start"]) || !Array.isArray(inputs) || inputs.length > maxInputsPerMessage) return malformed + const inputs = readInputs(value, maxInputsPerMessage) + if (!isSeat(seat, seats) || seat === from || !isWhy(value["why"]) || !isTick(value["have"])) return undefined + if (!isCount(value["start"]) || inputs === undefined) return undefined // It reports what it has, so the inputs it carries end at `have` at the latest. - if (value["start"] + inputs.length - 1 > value["have"]) return malformed - return { _tag: "Message", message: { k: "gone", ...base, seat, why: value["why"], have: value["have"], start: value["start"], inputs } } + if (value["start"] + inputs.length - 1 > value["have"]) return undefined + return { k: "gone", from, epoch, seat, why: value["why"], have: value["have"], start: value["start"], inputs } } case "out": - if (!isSeat(value["seat"], seats) || value["seat"] === from || !isWhy(value["why"]) || !isTick(value["last"]) || !isCount(value["tick"])) return malformed - return { _tag: "Message", message: { k: "out", ...base, seat: value["seat"], why: value["why"], last: value["last"], tick: value["tick"] } } + if (!isSeat(value["seat"], seats) || value["seat"] === from || !isWhy(value["why"]) || !isTick(value["last"]) || !isCount(value["tick"])) return undefined + return { k: "out", from, epoch, seat: value["seat"], why: value["why"], last: value["last"], tick: value["tick"] } case "left": { const by = value["by"] const out = value["seats"] @@ -289,25 +430,75 @@ export const parse = (text: string, seats: number): Parsed => { const last = value["last"] const tick = value["tick"] const seat = value["seat"] - const inputs = value["inputs"] - if (!isCount(value["roster"]) || value["roster"] < 1 || !isSeat(by, seats)) return malformed - if (!Array.isArray(out) || out.length < 1 || out.length >= seats || !out.every((one) => isSeat(one, seats) && one !== by) || new Set(out).size !== out.length) return malformed - if (!Array.isArray(why) || why.length !== out.length || !why.every(isWhy)) return malformed - if (!Array.isArray(last) || last.length !== out.length || !last.every(isTick)) return malformed + const inputs = readInputs(value, maxInputsPerMessage) + if (!isCount(value["roster"]) || value["roster"] < 1 || !isSeat(by, seats)) return undefined + if (!Array.isArray(out) || out.length < 1 || out.length >= seats || !out.every((one) => isSeat(one, seats) && one !== by) || new Set(out).size !== out.length) return undefined + if (!Array.isArray(why) || why.length !== out.length || !why.every(isWhy)) return undefined + if (!Array.isArray(last) || last.length !== out.length || !last.every(isTick)) return undefined // Its input is the `left` one only after its last own one. - if (!Array.isArray(tick) || tick.length !== out.length || !tick.every((first, index) => isCount(first) && first > (last[index] as number))) return malformed + if (!Array.isArray(tick) || tick.length !== out.length || !tick.every((first, index) => isCount(first) && first > (last[index] as number))) return undefined const index = out.indexOf(seat) - if (index === -1 || !isCount(value["start"]) || !Array.isArray(inputs) || inputs.length > maxInputsPerMessage) return malformed - if (value["start"] + inputs.length - 1 > (last[index] as number)) return malformed - return { - _tag: "Message", - message: { k: "left", ...base, roster: value["roster"], by, seats: out, why, last, tick, seat: seat as number, start: value["start"], inputs } - } + if (index === -1 || !isCount(value["start"]) || inputs === undefined) return undefined + if (value["start"] + inputs.length - 1 > (last[index] as number)) return undefined + return { k: "left", from, epoch, roster: value["roster"], by, seats: out, why, last, tick, seat: seat as number, start: value["start"], inputs } } default: - return malformed + return undefined } } -/** The text of a message. */ -export const write = (message: Message): string => JSON.stringify({ v: version, ...message }) +/** + * One message as a bundle writes it: no `from` (the bundle's), no `epoch` + * when it is the bundle's, its inputs as `d` and `i` or `r`, and an + * `inputs`' acknowledgements as how far behind its `next` they are. + */ +const writeOne = (message: Message, epoch: number): object => { + const own = message.epoch === epoch ? undefined : message.epoch + if (message.k === "inputs") { + // The message every frame says, built member by member. + const acks: Array = new Array(message.acks.length) + for (let seat = 0; seat < acks.length; seat++) acks[seat] = message.next - message.acks[seat]! + const written: Record = { k: "inputs", epoch: own, roster: message.roster, next: message.next, acks, start: message.start } + writeInputs(message.inputs, written) + return written + } + const written: Record = {} + const fields = message as unknown as Record + for (const key in fields) if (key !== "from" && key !== "epoch" && key !== "inputs") written[key] = fields[key] + written["epoch"] = own + if ("inputs" in message) writeInputs(message.inputs, written) + return written +} + +/** The bundle {@link write} fills: writing is synchronous, so one serves every session. */ +const none: ReadonlyArray = [] +const scratch: { v: number; from: number; epoch: number; m: ReadonlyArray } = { v: version, from: 0, epoch: 0, m: none } + +/** The text of a bundle: `messages`, all sent by `from`, which knows `epoch`. */ +export const write = (from: number, epoch: number, messages: ReadonlyArray): string => { + const m: Array = new Array(messages.length) + for (let index = 0; index < messages.length; index++) m[index] = writeOne(messages[index]!, epoch) + scratch.from = from + scratch.epoch = epoch + scratch.m = m + // Members left undefined (an `epoch` that is the bundle's) are not written. + const text = JSON.stringify(scratch) + scratch.m = none + return text +} + +/** The length of `text` in UTF-8, as a transport counts it. */ +export const utf8Length = (text: string): number => { + let bytes = 0 + for (let index = 0; index < text.length; index++) { + const code = text.charCodeAt(index) + if (code < 0x80) bytes += 1 + else if (code < 0x800) bytes += 2 + else if (code >= 0xd800 && code < 0xdc00 && index + 1 < text.length) { + // A surrogate pair: one character of four bytes. + bytes += 4 + index += 1 + } else bytes += 3 + } + return bytes +} diff --git a/packages/netcode/test/Bounds.test.ts b/packages/netcode/test/Bounds.test.ts index 60f9d630..31303299 100644 --- a/packages/netcode/test/Bounds.test.ts +++ b/packages/netcode/test/Bounds.test.ts @@ -1,12 +1,12 @@ import { describe, expect, it } from "vitest" import { idle, pressed } from "./game.ts" -import { checksumOf, frame, playOn, setUpMatch, settleOn } from "./match.ts" +import { checksumOf, frame, playOn, setUpMatch, settleOn, wire } from "./match.ts" /** A message seat 1's link carries to seat 0, written by hand. */ const inputs = (start: number, length: number) => - JSON.stringify({ v: 4, k: "inputs", from: 1, epoch: 1, roster: 0, next: -1, acks: [-1, -1], start, inputs: Array.from({ length }, () => idle) }) -const sum = (tick: number, text: string) => JSON.stringify({ v: 4, k: "sum", from: 1, epoch: 1, roster: 0, tick, sum: text }) + wire({ k: "inputs", from: 1, epoch: 1, roster: 0, next: -1, acks: [-1, -1], start, inputs: Array.from({ length }, () => idle) }) +const sum = (tick: number, text: string) => wire({ k: "sum", from: 1, epoch: 1, roster: 0, tick, sum: text }) describe("what a peer stores for another", () => { it("drops inputs and checksums no honest peer sends, and plays on", () => { diff --git a/packages/netcode/test/InputSchema.test.ts b/packages/netcode/test/InputSchema.test.ts index 648b1f0a..513d7d0e 100644 --- a/packages/netcode/test/InputSchema.test.ts +++ b/packages/netcode/test/InputSchema.test.ts @@ -68,7 +68,7 @@ describe("the local input", () => { for (let at = 0; at < 300; at++) { current = [idle, at === 20 ? { dx: 5, fire: false } : idle] for (const peer of peers) { - const updated = peer.update() + const updated = peer.update(step.dt, { last: true }) if (!updated.ok) throw new Error(JSON.stringify(updated.error)) } hostClock.adjust(step.dt * 1000) diff --git a/packages/netcode/test/Leaving.test.ts b/packages/netcode/test/Leaving.test.ts index a8628d7d..0f79a55a 100644 --- a/packages/netcode/test/Leaving.test.ts +++ b/packages/netcode/test/Leaving.test.ts @@ -3,7 +3,7 @@ import { HostClock } from "@typeonce/ritmo" import { MemoryNetworkLink, MemoryVisibility, Netcode } from "@typeonce/ritmo-netcode" import { Fired, idle, makePeer, pressed, simulate, step, type PlayerInput } from "./game.ts" -import { checksumOf, leave, playOn, reference, setUpMatch, settleOn, staying, stepMS, type MatchPeer } from "./match.ts" +import { checksumOf, leave, playOn, reference, setUpMatch, settleOn, staying, stepMS, wire, type MatchPeer } from "./match.ts" type Match = ReturnType @@ -184,7 +184,7 @@ describe("messages about the roster", () => { const match = setUpMatch({ mode: "rollback", count: 3, latencyMS: 0, jitterMS: 0 }) const [host] = match.peers playOn(match, 30) - const send = (from: number, message: object) => match.links[from]!.send(JSON.stringify({ v: 4, from, epoch: 1, ...message })) + const send = (from: number, message: object) => match.links[from]!.send(wire({ from, epoch: 1, ...message })) const change = { k: "left", roster: 1, by: 0, seats: [2], why: ["timeout"], last: [5], tick: [6], seat: 2, start: 6, inputs: [] } // The seat that decides is one of those it puts out; a seat whose `left` input starts on its last own tick; a seat twice; inputs past the last one. send(1, { ...change, by: 2 }) diff --git a/packages/netcode/test/Netcode.test.ts b/packages/netcode/test/Netcode.test.ts index bcdc0c84..971f5921 100644 --- a/packages/netcode/test/Netcode.test.ts +++ b/packages/netcode/test/Netcode.test.ts @@ -115,7 +115,11 @@ describe("Netcode.rollback", () => { match.hostClock.adjust(stepMS) } expect(failure?._tag).toBe("Desynced") - // Still stopped. + // The other peer stops too once the checksum reaches it, and both stay stopped. + for (let at = 0; at < 10; at++) { + for (const peer of match.peers) peer.session.advance(idle) + match.hostClock.adjust(stepMS) + } expect(guest!.session.advance(idle).ok || host!.session.advance(idle).ok).toBe(false) // Only seat 1 asks: seat 0 hosts the resync either way. guest!.session.resync() @@ -227,7 +231,7 @@ describe("Netcode.rollback", () => { const link: NetworkLink.NetworkLink = { send: () => {}, receive: () => inbox.splice(0), status: () => NetworkLink.open } const peer = makePeer() const session = valueOf(Netcode.rollback(peer.runtime, { simulate, seats: peer.seats, seat: 0, links: [link], hostClock, step })) - inbox.push("not json", JSON.stringify({ v: 4, k: "hello", from: 7, epoch: 0 })) + inbox.push("not json", JSON.stringify({ v: 5, from: 7, epoch: 0, m: [{ k: "hello", session: 1 }] })) expect(session.advance(idle).ok).toBe(true) expect(session.status().dropped).toBe(2) inbox.push(JSON.stringify({ v: 1, k: "hello", from: 1, epoch: 0 })) diff --git a/packages/netcode/test/Restore.test.ts b/packages/netcode/test/Restore.test.ts index 77b0c285..4bbddd62 100644 --- a/packages/netcode/test/Restore.test.ts +++ b/packages/netcode/test/Restore.test.ts @@ -83,7 +83,7 @@ const match = (simulate: "readingDespawns" | "carryingStreak") => { const frame = (skip?: number) => { for (const [seat, peer] of peers.entries()) { if (seat === skip) continue - const updated = peer.update() + const updated = peer.update(step.dt, { last: true }) if (!updated.ok) throw new Error(JSON.stringify(updated.error)) } hostClock.adjust(step.dt * 1000) diff --git a/packages/netcode/test/Returning.test.ts b/packages/netcode/test/Returning.test.ts index ee6278c0..d5f84db1 100644 --- a/packages/netcode/test/Returning.test.ts +++ b/packages/netcode/test/Returning.test.ts @@ -3,7 +3,7 @@ import { HostClock } from "@typeonce/ritmo" import { Netcode, NetworkLink } from "@typeonce/ritmo-netcode" import { idle, makePeer, simulate, step } from "./game.ts" -import { checksumOf, flaky, frame, leave, playOn, reload, setUpMatch, settleOn, staying, stepMS } from "./match.ts" +import { checksumOf, flaky, frame, leave, playOn, reload, setUpMatch, settleOn, staying, stepMS, wire } from "./match.ts" const held = { dx: 1, fire: false } @@ -83,7 +83,7 @@ describe("a page that loads again mid-match", () => { let frames = 0 for (; frames < 200 && ended === undefined; frames++) { // Seat 0 is in epoch 3 and never answers this session. - inbox.push(JSON.stringify({ v: 4, k: "inputs", from: 0, epoch: 3, roster: 0, next: 500, acks: [499, 480], start: 500, inputs: [idle] })) + inbox.push(wire({ k: "inputs", from: 0, epoch: 3, roster: 0, next: 500, acks: [499, 480], start: 500, inputs: [idle] })) const advanced = session.advance(idle) if (!advanced.ok) ended = advanced.error hostClock.adjust(stepMS) @@ -97,7 +97,7 @@ describe("a page that loads again mid-match", () => { const match = setUpMatch({ mode: "rollback", latencyMS: 20, jitterMS: 0 }) playOn(match, 60) // Another tab of seat 1 says hello where seat 1's session hears it. - const asks = JSON.stringify({ v: 4, k: "hello", from: 1, epoch: 0, session: 123456 }) + const asks = wire({ k: "hello", from: 1, epoch: 0, session: 123456 }) const heard: Array = [asks] const link = match.links[1]! const original = link.receive diff --git a/packages/netcode/test/Traffic.test.ts b/packages/netcode/test/Traffic.test.ts new file mode 100644 index 00000000..c091180f --- /dev/null +++ b/packages/netcode/test/Traffic.test.ts @@ -0,0 +1,57 @@ +/** + * What sessions send over a slow, lossy link (120 ms, up to 60 ms of + * jitter, 5% lost), driven by `FixedLoop` on pages whose frames sometimes + * run two or three steps. Before sessions bundled a frame's messages, a + * page handed its link up to 8 messages in one frame, and 2 peers sent + * about 140 messages and 62 KiB a second (8 peers: 730 and 290 KiB). + */ +import { describe, expect, it } from "vitest" + +import { pressed } from "./game.ts" +import { playOn, setUpMatch } from "./match.ts" +import { held, traffic } from "./traffic.ts" + +describe("what a session sends", () => { + for (const count of [2, 8]) { + it(`is at most one message per link per frame, however many steps the frame ran: ${count} peers`, { timeout: 60_000 }, () => { + const measured = traffic({ count, seconds: 10 }) + expect(measured.halts).toEqual([]) + expect(measured.mostInAFrame).toBe(1) + // The pages played the match together: every seat's checksums agreed, and none fell behind. + for (const page of measured.pages) expect(page.session.status().verified).toBeGreaterThan(500) + const ticks = measured.pages.map((page) => page.session.status().tick) + expect(Math.max(...ticks) - Math.min(...ticks)).toBeLessThan(10) + }) + } + + it("is lighter: inputs written once per distinct value, acknowledgements as small numbers", { timeout: 60_000 }, () => { + // An input new almost every frame, and one held for 20 frames. + expect(traffic({ count: 2, seconds: 10 }).bytesPerSecond).toBeLessThan(25 * 1024) + expect(traffic({ count: 2, seconds: 10, input: held }).bytesPerSecond).toBeLessThan(17 * 1024) + }) + + it("counts in status() what it handed its links", () => { + let handed = 0 + let bytes = 0 + const match = setUpMatch({ + mode: "rollback", + latencyMS: 80, + loss: 0.05, + wrap: (seat, link) => ({ + ...link, + send: (message) => { + if (seat === 1) { + handed += 1 + bytes += new TextEncoder().encode(message).length + } + link.send(message) + } + }) + }) + playOn(match, 300, { input: pressed }) + const sent = match.peers[1]!.session.status().sent + expect(sent).toEqual({ messages: handed, bytes }) + // `advance` called directly is a frame of its own: one message each. + expect(sent.messages).toBe(300) + }) +}) diff --git a/packages/netcode/test/match.ts b/packages/netcode/test/match.ts index 8aca6078..91cf085e 100644 --- a/packages/netcode/test/match.ts +++ b/packages/netcode/test/match.ts @@ -267,3 +267,15 @@ export const checksumOf = (peer: Peer): string => { if (!sum.ok) throw new Error("the peer did not checksum") return sum.value } + +/** + * One message as a session's bundle writes it (protocol 5): for tests that + * hand a session what no honest peer sends. `inputs` becomes the distinct + * inputs (`d`) and an index per tick (`i`). + */ +export const wire = (message: { readonly from: number; readonly epoch: number; readonly inputs?: ReadonlyArray } & Record): string => { + const { from, epoch, inputs, ...rest } = message + const acks = rest["k"] === "inputs" ? { acks: (rest["acks"] as ReadonlyArray).map((ack) => (rest["next"] as number) - ack) } : {} + const written = { ...rest, ...acks, ...(inputs === undefined ? {} : { d: inputs, i: inputs.map((_, index) => index) }) } + return JSON.stringify({ v: 5, from, epoch, m: [written] }) +} diff --git a/packages/netcode/test/traffic.ts b/packages/netcode/test/traffic.ts new file mode 100644 index 00000000..c64ad8a6 --- /dev/null +++ b/packages/netcode/test/traffic.ts @@ -0,0 +1,142 @@ +/** + * Measures what sessions send: peers driven by `FixedLoop`, as a game + * drives them, over memory links, each page on its own frame times (some + * frames run more than one step, as on a slow device), for `seconds` of a + * match. Counted at the link, as a relay would count them. + */ +import { FixedLoop, HostClock, Random } from "@typeonce/ritmo" +import { MemoryNetworkLink, Netcode, type NetworkLink } from "@typeonce/ritmo-netcode" + +import { makePeer, pressed, simulate, step, type PlayerInput } from "./game.ts" + +export interface TrafficOptions { + readonly count: number + readonly seconds: number + readonly seed?: number + readonly latencyMS?: number + readonly jitterMS?: number + readonly loss?: number + /** A seat's input on a frame of its page: `pressed` (a new input almost every frame) when omitted. */ + readonly input?: (seat: number, frame: number) => PlayerInput +} + +/** Held input, as in most real-time games: each seat changes what it presses every 20 frames. */ +export const held = (seat: number, frame: number): PlayerInput => pressed(seat, Math.floor(frame / 20) * 20) + +/** The bytes of `text` as UTF-8. */ +const utf8 = (text: string): number => { + let bytes = 0 + for (let index = 0; index < text.length; index++) { + const code = text.charCodeAt(index) + if (code < 0x80) bytes += 1 + else if (code < 0x800) bytes += 2 + else if (code >= 0xd800 && code < 0xdc00) { + bytes += 4 + index += 1 + } else bytes += 3 + } + return bytes +} + +export const traffic = (options: TrafficOptions) => { + const { count, seconds } = options + const hostClock = HostClock.test() + const links = MemoryNetworkLink.make({ + peers: count, + hostClock, + seed: options.seed ?? 7, + latencyMS: options.latencyMS ?? 120, + jitterMS: options.jitterMS ?? 60, + loss: options.loss ?? 0.05 + }) + if (!links.ok) throw new Error(links.error.field) + const random = Random.make((options.seed ?? 7) * 31 + count) + const counted = { messages: 0, bytes: 0, frames: 0, steps: 0 } + const input = options.input ?? pressed + /** The most messages one page handed its link in one frame. */ + let mostInAFrame = 0 + let measuring = false + const halts: Array = [] + const pages = Array.from({ length: count }, (_, seat) => { + const peer = makePeer({ count, setUp: seat === 0 }) + let sends = 0 + const inner = links.value[seat]! + const link: NetworkLink.NetworkLink = { + send: (message) => { + sends += 1 + if (measuring) { + counted.messages += 1 + counted.bytes += utf8(message) + } + inner.send(message) + }, + receive: inner.receive, + status: inner.status + } + const session = Netcode.rollback(peer.runtime, { simulate, seats: peer.seats, seat, links: [link], hostClock, step, maxRollback: 16 }) + if (!session.ok) throw new Error(session.error.reason) + let frame = 0 + const update = session.value.update({ input: () => input(seat, frame), onHalted: (error) => halts.push(`seat ${seat}: ${error._tag}`) }) + let onTick: ((tick: FixedLoop.Tick) => void) | undefined + const loop = FixedLoop.start({ + source: FixedLoop.source((listener) => { + onTick = listener + return { stop: () => {} } + }), + step, + maxFrameSeconds: 0.25, + maxStepsPerFrame: 5, + rate: session.value.rate, + update, + render: (drawn) => { + frame += 1 + if (measuring) { + counted.frames += 1 + counted.steps += drawn.fixedSteps + } + }, + onFailure: (failure) => halts.push(`seat ${seat}: ${JSON.stringify(failure)}`) + }) + if (!loop.ok) throw new Error(loop.error.field) + const tick = (deltaMS: number): void => { + const before = sends + onTick!({ deltaMS }) + mostInAFrame = Math.max(mostInAFrame, sends - before) + } + return { session: session.value, runtime: peer.runtime, tick, sent: () => sends, last: 0, next: 0 } + }) + /** A page's frame time: most at 60 Hz, some long (two or three steps in one frame). */ + const frameMS = (): number => { + const roll = random.next() + if (roll < 0.05) return 50 + if (roll < 0.15) return 1000 / 30 + return 1000 / 60 + (random.next() - 0.5) * 4 + } + const warmUpMS = 2000 + const endMS = warmUpMS + seconds * 1000 + let now = 0 + for (const page of pages) page.next = frameMS() + while (now < endMS) { + let soonest = 0 + for (let seat = 1; seat < count; seat++) if (pages[seat]!.next < pages[soonest]!.next) soonest = seat + const page = pages[soonest]! + const moved = hostClock.adjust(page.next - now) + if (!moved.ok) throw new Error("the test clock did not move") + now = page.next + measuring = now >= warmUpMS + page.tick(now - page.last) + page.last = now + page.next = now + frameMS() + } + return { + halts, + pages, + messagesPerSecond: counted.messages / seconds, + bytesPerSecond: counted.bytes / seconds, + framesPerSecond: counted.frames / seconds, + stepsPerSecond: counted.steps / seconds, + messages: counted.messages, + frames: counted.frames, + mostInAFrame + } +} diff --git a/website/src/demos/rollback/game.ts b/website/src/demos/rollback/game.ts index 8f3fccc9..c484b7cd 100644 --- a/website/src/demos/rollback/game.ts +++ b/website/src/demos/rollback/game.ts @@ -139,9 +139,9 @@ export const mount = async (host: HTMLElement): Promise<() => void> => { maxStepsPerFrame: 5, // One loop drives both peers here, so they never drift apart: a real peer // passes its session's `rate` and its update straight to its own loop. - update: () => { + update: (seconds, at) => { for (const update of match.updates) { - const ran = update() + const ran = update(seconds, at) if (!ran.ok) return ran } return Result.success(undefined)