diff --git a/docs/DESIGN.md b/docs/DESIGN.md index 0eff292..c31b9c7 100644 --- a/docs/DESIGN.md +++ b/docs/DESIGN.md @@ -1,6 +1,6 @@ # FFF_vtt design -Status: draft v0.2, 2026-11-08 (owner decisions recorded in section 14). Audience: the owner and coding agents. +Status: draft v0.3, 2026-11-08 (owner decisions recorded in section 14; v0.3 records Q13, Q20 and the mummy tag pin). Audience: the owner and coding agents. Legend: - **[FIXED]** owner decision, not up for debate here. @@ -46,7 +46,7 @@ A browser virtual tabletop for one table (1 GM + up to 6 players [FIXED, Q1]), s ### Fixed stack [FIXED] - Client: TypeScript + PixiJS v8 + Vite; plain HTML/DOM overlay for UI (no UI framework). Agents use the official pixijs-skills (already in `.agents/skills/pixijs*`). -- Server: Nim 2.x; `mummy` pinned to commit `01deb1ff694988635c7bf0f24f6088a0bdf6db5d` (no upstream tags; `prototype-server-vision/servervision.nimble`); `db_connector/db_sqlite`, WAL. No Nim in the browser. +- Server: Nim 2.x; `mummy` pinned to tag `0.4.8` (commit `77a7563e`; `src/` identical to the former pin `01deb1ff694988635c7bf0f24f6088a0bdf6db5d`) [FIXED (owner decision), 2026-11-08; tags 0.4.6-0.4.8 exist]. `prototype-server-vision/servervision.nimble` still pins the commit until ported; `db_connector/db_sqlite`, WAL. No Nim in the browser. - nginx (existing, HTTPS) in front: static client, reverse proxy for `/ws`, `/join/`, `/tiles/`; internal location for tile bytes. - Dev env: NixOS, devbox per project for toolchains, nothing global. @@ -172,7 +172,7 @@ Under the single global lock (as prototype, order proven correct by 3 x 60 s run 4. **Apply** to memory. 5. **Recompute** vision only for players whose input changed (mover's owner; all players for door/wall changes). Update explored; collect `fresh`. 6. **Persist**: `BEGIN; ...; COMMIT` including dirty explored chunks. -7. **Ack** to sender, then **egress**: for each connection compute recipient view, diff against `known`, send `token`/`remove`/`vision`/`explored`/`door`/... Only recipients with a change get bytes. +7. **Ack** to sender, then **egress**: for each connection compute the recipient view and enqueue it in that connection's bounded outbox (4.3; state keys coalesced). The diff against `known` happens at flush time; only changed items (`token`/`remove`/`vision`/`explored`/`door`/...) get bytes. 8. Clear `fresh`. Invariants (carry from prototype): @@ -190,7 +190,13 @@ Second limitation [INFERRED]: a fast drag sampled at ~50 ms can produce a straig - **One global lock** around intent handling and send. [MEASURED] 13748 mutations / ~36k messages in 60 s with 3 clients (~223 intents/s): no crash, no reorder, no loss, consistent final views (`results/concurrency-final{1,2,3}.log`); intent->ack avg 1.40 ms, p99 4.58 ms, worst 20.31 ms. - Decision [PROPOSED]: keep the global lock in v1. A table of <= ~10 clients is 2 orders of magnitude below the single-core limit (server total per mutation avg 0.70 ms [MEASURED]). Revisit only if a measured p99 > 50 ms appears in production logs. - Worker threads: prototype uses 8; one table needs 2-4 [INFERRED]. -- Slow client: mummy's send queue is one unbounded deque, no per-socket depth available to us [MEASURED finding]. Mitigations [PROPOSED]: max connections (8 = 6 players + GM + headroom; PROPOSED, derived from FIXED max 6, Q1), tiny messages, WS ping/pong timeout, per-connection byte counter we maintain ourselves and close when `sent - acked-by-pong` exceeds a bound (needs ping with counters; feasibility to be confirmed in M5). Q13 still open: owner leans to queued channels (MQTT-like) for slow clients; research pending on mummy capabilities. +- **Slow client [FIXED (owner decision), 2026-11-08, Q13 option A]**. mummy's send queue is one unbounded deque and per-socket backlog is invisible to app code (no forced close, no depth API at this pin). No mummy patch. Research: `docs/research/q13-mummy-slow-clients.md`. + - **Bounded outbox per connection** (keyed by app `connId`), with byte and message caps. State messages (vision, token, explored, door) are **latest-state-wins coalesced per key** (MQTT-retained-like). The diff against `known` is computed at **flush time**, not enqueue time, so a dropped intermediate state cannot desynchronise the client. + - **Ack by Ping/Pong**: server sends WS `Ping(seq)` (payload <= 125 B) on a timer; the client's Pong echoes `seq` (RFC 6455 ยง5.5.2-5.5.3; browsers answer without JS). Acks give bytes in flight and lag per connection. + - **Lagging client** (outbox over cap, or no Pong within a bound): stop feeding it, keep the connection. On recovery, full resync (6.3). + - **Dead or stuck peers**: closed by nginx proxy timeouts [PROPOSED mechanism; verify in M5 that `/ws` goes through nginx and which directive fires, `send_timeout` is the candidate]. `close(ws)` cannot force-close at this pin (it queues behind the backlog). + - Connection cap 8 (6 players + GM + headroom) [PROPOSED, derived from FIXED max 6, Q1]. Inbound message rate limit in `websocketHandler` (mummy's inbound queue is unbounded). + - Forking mummy (per-socket depth, forced close) is fallback only, not planned. - `WebSocket` has no `==`/hash; prototype keys connections by the raw bytes of the ref (`key(ws)`), flagged as shortcut. Real build: assign a connection id at upgrade and keep it in a table indexed by the ws via a documented wrapper; add a test that fails if mummy's layout changes (pinned commit makes this stable but the test makes it explicit) [PROPOSED]. - Handler discipline: no blocking I/O under the lock except the one SQLite COMMIT; no logging formatting of large structures under the lock; metrics are O(1) updates (section 11). - SQLite tail: server worst ~20 ms is the COMMIT (WAL autocheckpoint / OS scheduling [INFERRED]) and every other mutation queues behind it as `lock_wait` (`results/spike/investigation.md`). Accepted for v1. Moving persist out of the lock breaks ack-after-commit and order; not done. @@ -285,7 +291,7 @@ Client -> server (intents). Authority column: P = player, G = GM. | `prop.set` | `id, bucket, key, value` | G (v1) | owner-bucket writes by players come with FFF actions (section 9) | | `scene.set` | scene meta | G | broadcasts new `hello`-equivalent reset to all; no `scene.activate` (one scene, Q3) | | `invite.create` / `invite.revoke` | player id | G | returns link; secret stored plaintext, re-copyable by GM (Q11, FIXED) | -| `ping` | `ts` | any | `pong` (also feeds slow-client detection) | +| `ping` | `ts` | any | `pong` (liveness only; lag is measured with WS Ping/Pong, 4.3) | | `act` | `actor, action, args` | P/G | **reserved**: v1 replies `error: no-rules` (section 9) | Server -> client. @@ -433,7 +439,7 @@ Principles carried from the prototype: the checker must be independent of the co - **Auth tests**: invite revoke, one invite reused on several devices (Q10 FIXED), Origin mismatch rejected, cookie flags present. - **Protocol tests**: proto mismatch, unknown message type both directions, oversized frame, malformed JSON flood, rate limit. - **Persistence**: migration tests (old DB -> new), chunked explored round trip, restart test extended to wall CRUD and entity props. -- **Slow client**: a client that stops reading; server memory bounded / connection closed (depends on Q13 outcome). +- **Slow client** (Q13, 4.3): a client that stops reading; outbox stays under cap, no further state is queued to it, RSS flat, full resync on recovery equals a fresh connection; nginx closes the dead `/ws` socket within its configured timeout. - **Browser e2e (new, none in prototype)**: headless Chromium via playwright-core (the perf prototype already drives devbox chromium, `prototype-pixi-perf/bench.mjs`; SwiftShader is fine for correctness, not for perf). Checks: join -> canvas renders; pixel probe shows unexplored area black, visible area map-coloured, dimmed explored area; GM sees walls, player DOM/network contains none; reconnect restores view; drag moves token and rollback works. - **Independent traffic audit in e2e**: record all WS frames and HTTP responses seen by a player browser and run the leak checker's (a)(e) assertions over them. - **Load/perf regression gate**: `bench` + concurrency numbers (section 5.3 and 4.3) compared with committed baselines; fail on > 2x regression [PROPOSED]. @@ -445,7 +451,7 @@ Principles carried from the prototype: the checker must be independent of the co ## 11. Ops ### 11.1 Deployment on NixOS [PROPOSED] -- **Service**: a NixOS module `services.fffVtt` (name indicative) defining: package (Nim binary built by Nix; nimble dependencies pinned including mummy commit; packaging method open, Q20), a systemd unit, state dir, options for `publicOrigin`, `port`. +- **Service** [FIXED, Q20; research: `docs/research/q20-nix-packaging.md`]: NixOS module `services.fffVtt` in `nix/module.nix`, defining: package from `nix/package.nix` (`buildNimPackage`; dependencies from committed `nix/lock.json` generated by `nim_lk`; mummy tag `0.4.8`; nixpkgs input pinned to match devbox Nim 2.2.12; fallback: vendored deps via `nimFlags --path:`), a systemd unit, state dir, options for `publicOrigin`, `port`. Imported from the owner's server NixOS config, like `foundryvtt.nix`. - Unit hardening: `DynamicUser` or dedicated user, `StateDirectory=fff-vtt`, `ProtectSystem=strict`, `ProtectHome`, `NoNewPrivileges`, `PrivateTmp`, `RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6`, `MemoryMax`. Listen on `127.0.0.1:` only [MEASURED prototype binds 127.0.0.1]. - `Restart=on-failure`; `TimeoutStopSec` short; SIGTERM handler flushes (4.4). - **Client build**: Vite `dist/` produced by Nix (or CI), served by nginx from the store path. Hashed assets, long cache; `index.html` no-cache. @@ -499,7 +505,7 @@ Source: `prototype-server-vision/HANDOFF.md` (and README/NOTES worries). | H15 | `synchronous=NORMAL` vs FULL | Decision [FIXED, Q12]: NORMAL; FULL around GM authoring transactions | M3 | | H16 | Timing instrumentation unbounded and under lock | Decision: do not port; ring buffer/histogram, snapshot outside lock | M5 | | H17 | 583 ms spike unexplained | Open: not reproduced; production SLOW logging to catch recurrence | M5/M7 | -| H18 | mummy: unbounded send queue, no backpressure | Open Q13; v1 mitigations: connection cap, ping timeout, size limits | M5 | +| H18 | mummy: unbounded send queue, no backpressure | Decision [FIXED (owner decision), Q13]: app-level bounded per-client outbox, coalescing, WS Ping(seq)/Pong lag tracking, stop feeding + full resync; no mummy patch; fork is fallback only (4.3) | M5 | | H19 | `WebSocket` keyed by raw bytes | Decision: documented wrapper + test | M3 | | H20 | Fog masks Graphics grow unbounded | Decision: fixed-size baked fog texture (7.3) | M4 | | H21 | Pixi `Text` per token heavy | Decision: BitmapText; glyph set Latin incl. accents + Nerd Font icons (Q17 FIXED) | M4 | @@ -529,10 +535,10 @@ Each is small, ends with a green gate, and no milestone depends on browser UI be - Scope: new `client/` dir (first real client build): Vite + TS + Pixi v8 client: layers, tiles, grid, tokens (BitmapText), fog textures, wall/door editor, token drag with prediction/rollback, DOM overlay, reconnect backoff, reducer tests; after the client port, archive `prototype-*` dirs (Q24). - Accept: headless e2e: fog pixel checks, player traffic audit clean, reconnect restores; manual run on laptop and Note 10 at 60 fps with 50 tokens, 16384 px map (tiled; PROPOSED test target, Q2), fog active. - **M5 - Robustness and observability.** - - Scope: SIGTERM handler, bounded metrics + SLOW lines, connection cap, frame/rate limits, slow-client handling per Q13, healthz. - - Accept: concurrency 60 s x3 pass with p99 <= prototype (4.98 ms) +50%; slow-client test bounded; stats computation shown outside the lock (lock hold time unchanged with metrics on, measured). + - Scope: SIGTERM handler, bounded metrics + SLOW lines, connection cap, frame/rate limits, per-client bounded outbox with coalescing and Ping(seq)/Pong lag tracking (Q13, 4.3), verify `/ws` goes through nginx and its timeouts, healthz. + - Accept: concurrency 60 s x3 pass with p99 <= prototype (4.98 ms) +50%; slow-client test: client that stops reading -> outbox stays under cap, RSS flat, no further state queued to it, full resync on recovery equals a fresh connection; nginx closes a dead `/ws` within its configured timeout (measured); stats computation shown outside the lock (lock hold time unchanged with metrics on, measured). - **M6 - NixOS deployment.** - - Scope: `nix/` dir (Nix packaging of the Nim server and client build; method per Q20), NixOS module, nginx vhost, systemd hardening, backups timer (Q21), restore drill, import CLI for maps. + - Scope: `nix/` dir per Q20: un-ignore `nix/` in `.gitignore`; `lock.json` (nim_lk), `package.nix` (buildNimPackage, nixpkgs pinned to devbox Nim 2.2.12, mummy tag 0.4.8), `module.nix` (`services.fffVtt`); declare a nimble `bin` in `fff_vtt.nimble` (nim_builder builds only `bin` entries, so the package is empty without it); client build; nginx vhost; systemd hardening; backups timer (Q21), restore drill, import CLI for maps. - Accept: deployed behind HTTPS on the owner's server; `/_tiles/` 404 directly; WS upgrade works; invite join works from phone; access log has no secret; backup + restore drill passes. - **M7 - Real-world pass.** - Scope: real-network latency/throughput run, iOS/Safari check (if available), one real session with the owner's table, collect SLOW lines. @@ -555,14 +561,14 @@ Each is small, ends with a green gate, and no milestone depends on browser UI be 10. Q10 - Session lifetime and invite policy: session expiry, how often invites rotate, single-use vs reusable invite links, can one player use multiple devices at once? **RESOLVED [FIXED (owner decision), 2026-11-08]:** sessions never expire; one invite link is reusable on multiple devices. 11. Q11 - Invite secrets: stored hashed (shown once, GM regenerates to re-share) or stored plaintext so the GM can re-copy a link? **RESOLVED [FIXED (owner decision), 2026-11-08]:** invite secrets stored plaintext so the GM can re-copy the link. 12. Q12 - Durability: is `synchronous=NORMAL` (can lose the last few commits on power loss/OS crash, never corrupts) acceptable, or should it be FULL for some or all writes? **RESOLVED [FIXED (owner decision), 2026-11-08]:** `synchronous=NORMAL`; `FULL` around GM authoring transactions. -13. Q13 - Slow/dead client policy: acceptable to disconnect clients that fall behind? Willing to patch/fork the pinned mummy commit if per-socket queue depth cannot be read from outside? **OPEN (owner, 2026-11-08):** still open. Research pending on mummy capabilities; owner leans to queued channels (MQTT-like) for slow clients. +13. Q13 - Slow/dead client policy: acceptable to disconnect clients that fall behind? Willing to patch/fork the pinned mummy commit if per-socket queue depth cannot be read from outside? **RESOLVED [FIXED (owner decision), 2026-11-08]:** option A: app-level bounded per-client outbox, latest-state-wins coalescing per key (MQTT-retained-like), diff at flush time, server Ping(seq)/Pong ack tracking for lag, stop feeding lagging clients + full resync on recovery; no mummy patch. Dead/stuck peers closed by nginx proxy timeouts (mechanism PROPOSED; verify WS goes through nginx in M5). Fork of mummy (option B) is fallback only, not planned. Research: `docs/research/q13-mummy-slow-clients.md`; detail in 4.3. 14. Q14 - Moving tokens when walls change: what should happen if the GM closes a door (or edits a wall) on top of a token? Allow the token to walk out, auto-nudge it, or refuse the edit? **RESOLVED [FIXED (owner decision), 2026-11-08]:** a GM edit that lands on a token gives it status `blocked`: server refuses that token's player moves; GM can still move it; status clears when the wall is removed or the door opened, or when the GM clears it. 15. Q15 - Reconnect: is a full resync on every reconnect fine up to what explored/state size, or do you want `resume since N` later? **RESOLVED [FIXED (owner decision), 2026-11-08]:** full resync on every reconnect; revisit if a measured snapshot exceeds ~100 KB. 16. Q16 - Vision payload: OK with full polygon per move (~3.4-3.7 KB per mover delivery, measured on loopback) for v1, or do you want deltas/binary earlier (e.g. for mobile data plans)? **RESOLVED [FIXED (owner decision), 2026-11-08]:** full vision polygon, integer px, sent only on change; deltas post-v1. 17. Q17 - Names/labels: which character sets must labels support (Latin only, accents, non-Latin, emoji)? Affects BitmapText glyph atlas vs Text/HTMLText. **RESOLVED [FIXED (owner decision), 2026-11-08]:** labels in Latin incl. accented characters plus Nerd Font icon glyphs. 18. Q18 - Grid and movement: snap to grid on drop? Any server-side speed/distance limit per move, given there are no rules yet? **RESOLVED [FIXED (owner decision), 2026-11-08]:** grid snap off by default (client option); server step cap = token vision radius. 19. Q19 - FFF engine: implementation language/runtime, current maturity, and whether it should run inside the VTT server process, as a sidecar, or in the browser for display only? Does it need hidden/secret state beyond the three property buckets (public / owner / GM)? **PARTLY RESOLVED [FIXED (owner decision), 2026-11-08]:** no hidden state beyond the `public`/`owner`/`gm` buckets and `gm_only` flag in v1; revisit when FFF starts (schema change accepted then). Engine language, runtime and location: not answered, still open. -20. Q20 - Nix packaging: how do you want the Nim server built (nimble lock + `buildNimPackage` or a vendored deps approach), and which repo hosts the NixOS module (this repo or your nixos-configuration repo)? **OPEN (owner, 2026-11-08):** still open. Research pending (buildNimPackage + pinned mummy). +20. Q20 - Nix packaging: how do you want the Nim server built (nimble lock + `buildNimPackage` or a vendored deps approach), and which repo hosts the NixOS module (this repo or your nixos-configuration repo)? **RESOLVED [FIXED (owner decision), 2026-11-08]:** `buildNimPackage` with a committed `nix/lock.json` (`nim_lk` JSON lock). `nix/package.nix` and `nix/module.nix` (`services.fffVtt`) live in this repo and are imported from the owner's server NixOS config, like `foundryvtt.nix`. nixpkgs input pinned to match devbox Nim (2.2.12). Fallback: vendored deps if `nim_lk` cannot resolve the mummy pin. `nix/` un-ignored in `.gitignore` when M6 starts, not now. mummy pinned to tag `0.4.8` (same `src/` as `01deb1ff`). Research: `docs/research/q20-nix-packaging.md`; detail in 11.1. 21. Q21 - Backups: where should off-box backups go (existing mechanism on the server?), and how many dated copies to keep? **RESOLVED [FIXED (owner decision), 2026-11-08]:** v1 backups go to a backup folder the server creates under its data root; off-box backups out of v1 scope. 22. Q22 - Observability: journald lines only, or also an internal metrics endpoint scraped by something you run? **RESOLVED [FIXED (owner decision), 2026-11-08]:** journald lines only; `/healthz` stays. 23. Q23 - Public exposure: reachable from the internet (domain, rate-limiting, fail2ban expectations) or LAN/VPN only? **RESOLVED [FIXED (owner decision), 2026-11-08]:** network exposure and access are out of project scope (owner handles reachability). Built-in protections stay (127.0.0.1 bind, connection cap, frame/rate limits, Origin check); internet-only hardening (fail2ban etc.) not in scope.