From 9b3b154fc87828b9a0a4654a67621fdba753e973 Mon Sep 17 00:00:00 2001 From: Davide Cappellini Date: Sun, 8 Nov 2026 11:21:19 +0100 Subject: [PATCH] docs: add Q13/Q20 research notes Q13: mummy slow WebSocket clients (pin 01deb1f), option analysis. Q20: Nix packaging of the Nim server (buildNimPackage, nim_lk lock, NixOS module). Co-Authored-By: Claude Haiku 5.5 --- docs/research/q13-mummy-slow-clients.md | 138 +++++++++++++++++++++++ docs/research/q20-nix-packaging.md | 143 ++++++++++++++++++++++++ 2 files changed, 281 insertions(+) create mode 100644 docs/research/q13-mummy-slow-clients.md create mode 100644 docs/research/q20-nix-packaging.md diff --git a/docs/research/q13-mummy-slow-clients.md b/docs/research/q13-mummy-slow-clients.md new file mode 100644 index 0000000..b75c2e8 --- /dev/null +++ b/docs/research/q13-mummy-slow-clients.md @@ -0,0 +1,138 @@ +# Q13: mummy slow WebSocket clients (pin 01deb1f) + +Question (docs/DESIGN.md §4.3, Q13): how mummy queues WebSocket sends per connection; whether app code can see queue depth, get backpressure, close slow clients; ping/pong and timeouts; thread model; hooks; what later mummy commits change; feasibility of an app-level bounded per-client outbox with coalescing vs patching mummy vs other. Also checks the HANDOFF "mummy: unbounded send queue" note. + +Pin: `guzba/mummy` `01deb1ff694988635c7bf0f24f6088a0bdf6db5d` (2026-04-29, "Revert ..."). Read from a fresh clone of `https://github.com/guzba/mummy` at that commit. All line numbers below refer to that commit. Base link: `https://github.com/guzba/mummy/blob/01deb1ff694988635c7bf0f24f6088a0bdf6db5d/`. Local copy: `/tmp/claude-1000/-home-davide-Projects-GDR-FFF-vtt/fb922d93-7ea6-4746-9a92-5070f98248eb/scratchpad/mummy/pin/src/mummy.nim`. Nim 2.2.12 stdlib used to check `==`/`hash` and epoll error mapping. + +## TL;DR + +1. Send path: `WebSocket.send` appends to one server-wide `sendQueue` (`src/mummy.nim` L262-291, L105). The IO thread drains that whole deque in one step into a per-socket `DataEntry.outgoingBuffers` (L1230-1250, L133). That per-socket deque is unbounded and is where backlog actually accumulates. +2. App code cannot read per-socket queue depth or bytes pending. The exported API is `send`, `close(ws)`, `respond`, `upgradeToWebSocket`, `serve`, `close(server)`, `newServer`, `waitUntilReady`, `responded`, and nothing else (grep of `^proc .*\*`). +3. No backpressure. `send` never blocks or fails. Nothing reports writable state to the handler (PR 146 adds this only for response streams, not WebSockets). +4. Slow clients cannot force-close. `close(ws)` only appends a Close frame to the same per-socket FIFO (L293-311, L1248), so a stuck client never receives it. The socket closes only on: peer Close reply, EOF/send error/`Error` event (L1317, L1336, L1358-1362), or a 10 s "close timeout" check that runs only when the socket receives data (L596-597). +5. Slow clients do not block other clients. Writes are non-blocking, one `send()` per writable event per socket in a single select loop (L1340-1362). The cost of a slow client is its own memory. +6. Ping/pong: mummy never sends a Ping and never auto-replies to one. Ping/Pong arrive at the app as `MessageEvent` with `kind` Ping/Pong (L734-736, L752). `send(..., kind = Ping/Pong)` exists (L262-281). There are no timers, idle timeouts, or connection caps. `maxMessageLen` = 64 KB (L1479) is the only size bound on inbound frames. +7. Thread model: one IO thread runs `loopForever` (L1150, select at L1164, `-1` timeout). Workers number `countProcessors()*10` (L1476, L1534). WebSocket events are serialized per connection by `websocketClaimed` (L107, L464-520). The inbound per-socket event queue is also unbounded (L108, L551-573). +8. Hooks: `handler`, `websocketHandler`, `logHandler` (L1472-1480). No per-socket hooks, no metrics, no close-reason callback. `CloseEvent` fires on every socket teardown (L1393-1404), which is enough to count connections. +9. Later commits: none on `master` after the pin (origin/master = 01deb1f, 2026-04-29). `src/` is byte-identical to tag `0.4.8`. Open PR #146 (2026-05-19) adds response-stream writable backpressure and explicitly leaves WebSocket internals alone. Issue #141 (Slowloris) was closed as "non-issue ... used behind a reverse proxy". +10. Feasible without patching mummy: an app-level, per-connection outbox that caps bytes in flight. Use server-solicited Ping(seq) and client Pong echoes (RFC 6455 §5.5.2/5.5.3, WHATWG "Ping and Pong frames") as acks, coalesce latest state per key, and stop feeding a lagging client. Not achievable without a patch: a deterministic forced disconnect, or a visible per-socket queue depth. The HANDOFF note is correct in substance but overstated in location (see Corrections). + +## Findings with sources (pin 01deb1f) + +### A. Data structures +- `WebSocket` = `{server: Server, clientSocket: SocketHandle, clientId: uint64}` (L63-66). Identity is (ptr, fd, random id). +- `clientId = server.rand.next()` per accepted socket (L1312). Fd reuse is guarded by comparing `clientId` (L1193, L1242). +- `ServerObj`: `sendQueue: Deque[OutgoingBuffer]` + `sendQueueLock` (L105-106); `websocketClaimed`, `websocketQueues: Table[WebSocket, Deque[WebSocketUpdate]]`, `websocketQueuesLock` (L107-109). +- `DataEntry` (per socket, IO-thread owned): `outgoingBuffers: Deque[OutgoingBuffer]` (L133), `sendsWaitingForUpgrade: seq[OutgoingBuffer]` (L136), `closeFrameQueuedAt: float64`, `closeFrameSent`, `upgradedToWebSocket` (L120-137). +- `OutgoingBuffer` = header + payload string + `bytesSent` (L157-162). +- Hashing: `WebSocket` is a Table key (L107-108) and is hashed in `$` (L179). Nim 2.2 `std/hashes` provides a generic `hash[T: tuple|object]` (`nim/lib/pure/hashes.nim` L666) and `system.==` is generic for objects (`nim/lib/system.nim` L1981). So the pinned type hashes and compares field-wise. This contradicts the HANDOFF/README/DESIGN claim "no ==/hash, keyed by raw bytes" (see Corrections). + +### B. Send path (app -> wire) +- `send*` builds the frame (Text/Binary/Ping/Pong opcode, L268-280) and does `addLast` on the global `sendQueue` under `sendQueueLock`. It triggers the IO select event only when the queue was empty (L285-291). No size check, no return value, no failure mode. +- `close*(ws)` appends a Close frame to the same queue (L293-311). Messages queued before it are not discarded. +- IO loop drain: `if sendQueuedTriggered` moves every frame from `sendQueue` into the target socket's `outgoingBuffers` (L1230-1250). Frames for a socket that is not upgraded yet go to `sendsWaitingForUpgrade` (L1257). Frames for a socket that already sent a Close go to "Dropped message after WebSocket close" (L1246, `closeFrameQueuedAt > 0`). +- Write path: on `Write` readiness, one `send()` of the head buffer (buffer1 then buffer2) per select iteration (L1340-1362). `bytesSent > 0` is required; otherwise the socket is marked for closing (L1358-1362). Interest is `{Read, Write}` while buffers exist and `{Read}` otherwise (L1109). +- `afterSend` pops fully-sent buffers (L1091-1110). Its `isCloseFrame` branch sets `closeFrameSent`. +- Reads are never paused. Interest for upgraded sockets is always `Read` (L1315, L1109). + +Conclusion: the "one server-wide deque" in HANDOFF/README is only the entry point. The IO thread empties it every iteration, so backlog grows in per-socket `outgoingBuffers` (L1248), which app code cannot see. + +### C. Backpressure and slow-client control +- None to the app. `send` cannot block, fail, or report depth. No writable callback for WebSockets. No API to drop by key or cap bytes. +- `close(ws)` is not forced. It queues a Close frame behind the backlog (L1248 / L1220). The socket is closed only when: + - the client's Close reply arrives while `closeFrameQueuedAt > 0` (`afterRecvWebSocket`, opcode 0x8 branch, L729-730); + - recv returns 0 or send returns <= 0, or the selector reports `Error` (EPOLLERR/EPOLLHUP, nim stdlib `ioselectors_epoll.nim` L400-411) (L1317-1318, L1336-1337, L1358-1362); + - a frame arrives more than 10 s after the Close was queued (L596-597). This check runs only when the socket receives data. +- Consequence: a client that stops reading and stops sending keeps its socket and its whole backlog until the kernel reports a TCP error. Nothing in mummy times this out. Upstream explicitly declines to add timeouts (issue #141, below). +- Connection cap: none. `clientSockets` is only tracked (L1309, L1392). An app-level counter is needed (count `OpenEvent` L1213 and `CloseEvent` L1402). +- Inbound: `postWebSocketUpdate` appends every decoded message to an unbounded per-socket deque (L551-573, L108). Frame size is capped by `maxMessageLen` = 64 KB (L658, L1479). Message count is not capped, so a flooding client grows server memory on the inbound side too. + +### D. Ping/pong and timeouts +- No automatic Pong reply and no server-initiated Ping. Ping/Pong frames are decoded and delivered to the app as `MessageEvent` (L734-736, L752). The app must reply to client Pings itself. +- Control-frame payload > 125 bytes is rejected on receive (L654). `send(kind=Ping)` does not check the 125-byte limit, so the app must keep ping payloads <= 125 bytes (RFC 6455 §5.5). +- Pong from peer is a normal message with `kind == Pong` and the echoed payload. Usable as an ack, see Options. +- No idle, read, header, body, or keep-alive timeouts (issue #141 confirms; maintainer closed it as non-issue because mummy sits behind a reverse proxy). +- `waitUntilReady` only waits for startup (L1546-1560). No timer facility exists anywhere in the module. + +### E. Thread model +- One IO thread: `serve()` runs `loopForever` on the calling thread (L1414-1470, L1150). All socket IO, accept, framing decode, and the `sendQueue` drain happen there. Upstream README says the same (`README.md` L35 at pin). +- Worker threads: `countProcessors()*10` by default (L1476, L1534-1535). They run HTTP handlers and WebSocket handlers (L464-545). WebSocket handlers for one connection never run concurrently (`websocketClaimed`, L481-495, L508). +- `send`, `close(ws)` and `respond` are safe from any thread: they take a lock and call `trigger` (L286-291, L306-311). An app timer thread can call `send(kind=Ping)` directly. +- Sends to a closed connection are silently dropped (L1260-1262 "Dropped message to disconnected client", debug log only). + +### F. Hooks +- `newServer(handler, websocketHandler, logHandler, workerThreads, maxHeadersLen=8 KB, maxBodyLen=1 MB, maxMessageLen=64 KB, tcpNoDelay=true)` (L1472-1480). +- Events: `OpenEvent` after the 101 is queued (L1213), `MessageEvent`, `ErrorEvent` (only if no Close was sent, L1399-1400), `CloseEvent` (L1402). +- `logHandler` receives debug messages such as "Dropped message after WebSocket close" and "Dropped message to disconnected client" (L1218, L1260-1262). Usable as a crude drop signal, not a metric. +- No per-socket hooks, no queue metrics, no write-ready callback. + +## Later commits and related upstream work + +- Upstream `master` tip = `01deb1f` (2026-04-29). There are 0 commits on `master` after the pin. The 7 commits between tag `0.4.8` (`77a7563`) and the pin are "whatever / noise / revert" and do not change `src/`. `git diff 0.4.8 01deb1f -- src` is empty. +- Tags `0.4.6`, `0.4.7`, `0.4.8` exist upstream. `docs/DESIGN.md` L48 says "no upstream tags", which is wrong. The pin's `src/` equals tag `0.4.8`. +- Experiment branches `experiments1/2/4` (Nov-Dec 2022, pre-0.4) are not relevant to current code. Checked by subject line only. +- PR #146 (open, not merged, head `be6bbfa9de9ff6033845ee6fd8b52ef29696a490`, 2026-05-19) https://github.com/guzba/mummy/pull/146 adds response streaming with "writable-event backpressure" (`StreamWritable`, one chunk in flight). Its body says WebSocket internals are "intentionally left close to upstream". `send`/`close(ws)` are unchanged in its diff. It does not give WebSocket backpressure. +- Issue #141 https://github.com/guzba/mummy/issues/141 (Slowloris, closed 2026-03-10). Maintainer comment (guzba, 2026-03-10): "Non-issue. Mummy is used behind a reverse proxy for TLS termination which is concerned with the above." Implies upstream expects timeouts from a proxy. +- Issue #142 (pipelined HTTP responses out of order) is closed and HTTP-only; not relevant. + +## Standards (for the design) + +- RFC 6455 §5.5.2: "Upon receipt of a Ping frame, an endpoint MUST send a Pong frame in response"; §5.5.3: the Pong must echo the Ping's application data. https://www.rfc-editor.org/rfc/rfc6455#section-5.5.2 (text checked at `https://www.rfc-editor.org/rfc/rfc6455.txt` L2036-2062). +- WHATWG WebSocket Standard, "Ping and Pong frames": pings/pongs "are not currently exposed in the API"; "servers will solicit pongs whenever appropriate for the server's needs". https://websockets.spec.whatwg.org/#ping-and-pong-frames +- WHATWG exposes `WebSocket.bufferedAmount` in the browser (client side only). It gives the client no server-side signal. https://websockets.spec.whatwg.org/#dom-websocket-bufferedamount + +Consequence: browsers answer server Pings with Pongs in the network stack, without JS. A server-solicited Ping/Pong echo is a valid ack channel for current browsers without any client code change. + +## Corrections to repo docs + +- `prototype-server-vision/HANDOFF.md` L29 and `prototype-server-vision/README.md` L110-114: "one unbounded server-wide deque" is the entry point only. The backlog is per socket (`outgoingBuffers`, pin L133, L1248). The "no ==/hash, keyed by raw bytes" caveat is stale at this pin (generic field-wise `hash`/`==` apply). +- `docs/DESIGN.md` L48: "no upstream tags" is wrong. Tags `0.4.6`-`0.4.8` exist, and the pin's `src/` equals `0.4.8`. +- `docs/DESIGN.md` L192 and H18 (L500): the mitigation "close when sent - acked-by-pong exceeds a bound" cannot be executed as an immediate close at this pin. `close(ws)` queues behind the backlog. The workable action is to stop feeding the client and close once the peer responds or sends data. +- `docs/DESIGN.md` L192: "per-connection byte counter we maintain ourselves" is fine, but acks must come from server-solicited Pings. WHATWG says user agents must not use pings or unsolicited pongs to aid the server, so the server must solicit every Pong it relies on. JS cannot send or observe Pongs. + +## Options + +Each option is judged on the owner's requirements: bounded per-client memory, latest-state-wins for vision/positions, no slow client hurting others, and the ability to disconnect. Effort figures are rough estimates, not measured. + +### Option A: app-level bounded outbox + ping-acked send window (no mummy patch) +Design: +- Per connection (app-assigned `connId` at upgrade; app table keyed by `connId`, not by `WebSocket`): `inFlightBytes`, a FIFO `mustQueue` of bytes-capped messages, and a `latest: Table[key, state]` map for state messages. +- Send window: call `ws.send` only while `inFlightBytes < W` (e.g. 64 KB). Timer thread sends `Ping(seq)` (<= 125 B payload) every T (e.g. 250 ms to 1 s). On `Pong(seq)` from the peer, subtract the bytes sent before that ping. Mummy's per-socket FIFO makes this exact. +- Coalescing: vision, position and fog state are keyed by (player, token). Keep only the latest per key. The prototype's current diff-at-send-time (`known` map) must change to diff-at-flush-time against last-delivered state. Otherwise dropping a queued delta silently diverges the client. +- Overflow: if `mustQueue` exceeds its cap, or no Pong for X s, stop feeding that client (keep the connection). On recovery send a full snapshot. The prototype already resets on `hello`. +- Disconnect: call `close(ws)`. It takes effect only when the peer reads or sends data. A dead peer that also sends nothing keeps its FD until the kernel reports a TCP error (not measured here). +- Connection cap: count OpenEvent/CloseEvent; reject at upgrade. +- Inbound: app must rate-limit messages per connection in `websocketHandler` (count on enqueue). Mummy's inbound queue is unbounded. + +Trade-offs: no mummy patch, no fork; the thread-safety contract holds (`send` is locked, L286-291). Costs: an ack timer thread, ~2-byte-plus overhead per ping, and no forced disconnect (FD may linger). Works with unmodified browsers. Non-browser clients that ignore Pings just get throttled (safe default). Estimate: ~150-250 lines plus tests. Does not add visibility into mummy's real queue (the app's window bounds it instead). + +### Option B: fork mummy at the pin and add a small hook set +Needed changes (all in `src/mummy.nim`): +- Per-socket pending-bytes counter, updated on enqueue (L286-291, L306-311) and on fully-sent in `afterSend` (L1091-1110). Expose `pendingBytes(ws)`. +- `send` returns `bool` or drops above `maxPendingBytes`. +- `forceClose(ws)`: enqueue an IO-thread event (same pattern as `sendQueued`) that sets `needClosing` for that socket. CloseEvent already fires from the teardown path (L1393-1404). +- Optional: inbound cap per socket (L551-573). + +Trade-offs: fixes the real gaps (forced close, visible depth, hard cap). Costs: changes the IO loop (L1150-1410), the riskiest code in the library; fork maintenance and a nimble URL pin in place of a bare commit; a regression surface for everything mummy does. Upstream PR #146 shows writable-backpressure is acceptable upstream for streams, but WebSockets were left out on purpose, so upstream acceptance is uncertain. Estimate: ~100-200 lines plus tests. Use Option A's `connId`/outbox API so the patch can be swapped in later. + +### Option C: rely on a front proxy for slow-client enforcement +Upstream's position (issue #141) assumes a reverse proxy handles timeouts. A proxy with per-client write/send timeouts could close stuck clients. Not evaluated here: no nginx WebSocket config was read, and whether the WS path goes through nginx is an open question (DESIGN has nginx for static and tiles only). Needs its own research. + +### Option D: switch WebSocket library +Not evaluated. Would need a separate research pass against each candidate's pinned source. Not recommended before A is tried, because A removes the risk that motivates the switch. + +### Option E: caps only (DESIGN v1 mitigations, no slow-client logic) +Connection cap, size limits, pong timeout detection without enforcement. Memory per stuck client grows until the process restarts or the kernel errors the socket. Illustrative arithmetic only: the prototype's ~3.4-3.7 KB per vision delivery (`prototype-server-vision/HANDOFF.md`, README) at an assumed 10 deliveries/s is ~2 MB per minute per stuck client. The 10/s is an assumption, not measured. + +## Recommendation + +Option A for M5, with a `connId` + outbox module behind a narrow interface. Move to Option B only if forced disconnect or visible depth proves necessary in load tests (the prototype's leak harness can measure `outgoingBuffers` growth via RSS). Update DESIGN H18/L192 and the HANDOFF/README wording per Corrections. Do not patch mummy before measuring A. + +## Not verified / open + +- No code was compiled or run against mummy. Claims come from reading the pinned source, the Nim 2.2.12 stdlib, and the RFC/WHATWG text. +- Browser behaviour (automatic Pong) is taken from RFC 6455 and the WHATWG text, not tested in a browser. +- TCP error timing for dead peers (kernel retransmit limits) not measured. +- Option C (nginx) and D (other libraries) not researched. +- Upstream issues/PRs were searched via `gh api` for "backpressure", "slow client", "ping", "send queue", "timeout websocket". Results listed above; not exhaustive. +- Not committed, not pushed, DESIGN.md not edited. diff --git a/docs/research/q20-nix-packaging.md b/docs/research/q20-nix-packaging.md new file mode 100644 index 0000000..398c3a0 --- /dev/null +++ b/docs/research/q20-nix-packaging.md @@ -0,0 +1,143 @@ +# Q20: Nix packaging of the Nim server + NixOS module + +Date: 2026-11-08. Scope: research only. No repo code changed. Refs: `docs/DESIGN.md` Q20 (line 563) and §11.1 (line 445). + +Source pins: +- NP = nixpkgs `c56a87d8e41ce69bd2af57eb35dcc117a9dfca33` (26.05.20261105). This is the owner's system nixpkgs (`nixos-version --json`). Links below use this commit. Local store copy: `/nix/store/qyccs9pc22b3fvl2lxia3jagcg97dn48-source` (nim 2.2.4). +- MUM = mummy commit `01deb1ff694988635c7bf0f24f6088a0bdf6db5d`. +- DEV = `devbox.lock` (local, `/home/davide/Projects/GDR/FFF_vtt/devbox.lock`): nixpkgs `55ba7f49ef2962b42cbd126522b7df5f95037679`, nim 2.2.12, nimble 0.24.1. + +## 1. Summary + +1. nixpkgs has a documented Nim builder: `buildNimPackage` plus a JSON `lockFile`, generated by `nim_lk`. The owner's system nixpkgs (NP) has it. [S1][S2] +2. Lock entries carry the source fetch: `method` `fetchzip` (tarball) or `git` (`url`, `rev`, `sha256`, `srcDir`, `fetchSubmodules`). The builder turns each into a fixed-output fetch plus `--path:` flag. Git-commit deps are fetched with `fetchgit` at the exact `rev`. [S1][S7][S8] +3. nim_builder ignores `requires` in the .nimble. Deps come only from the lock. The lock must list the full transitive closure. [S5][S1] +4. Not in nixpkgs: `mummy`, `db_connector`, `zippy`, `webby`, `crunchy`, `nimsimd` (no `by-name` entry, no `nimPackages`). They enter via the lock. [checked NP tree] +5. Nim 2.2.4 stdlib has no `db_*` module. `db_connector` must be a separate lock entry. [local stdlib] +6. Upstream now HAS tag `0.4.8` on mummy. DESIGN says "no tags" (stale). Tag `0.4.8` = `77a7563e`. MUM is 7 commits ahead; only `.github/workflows/*` differ. Library code is identical. [S13][S14] +7. nim_builder builds only nimble `bin` entries. Root `fff_vtt.nimble` has none and `server/` has no entrypoint yet (only `geometry.nim`). The Nix build would produce an empty package until a `bin` is declared. [S5][local] +8. Devbox pins nim 2.2.12. NP's nim-2_2 is 2.2.4. Version drift must be handled by pinning the nixpkgs input, not by hoping. [DEV][S10] +9. `.gitignore` already excludes `nix/`. DESIGN M6 plans `nix/`. Either remove that line or use another dir name before committing packaging. [local `.gitignore`] +10. Recommended: `buildNimPackage` + committed `nix/lock.json` (from `nim_lk`) + `nix/module.nix` modeled on nitter's systemd unit. Devbox stays the dev shell and is untouched. + +## 2. Findings with sources + +### 2.1 buildNimPackage (NP) +- Builder: `pkgs/build-support/build-nim-package.nix`. Phases delegate to `nim_builder --phase:{configure,build,check,install}`. `doCheck = true` by default. [S1] +- `lockFile` is read with `builtins.fromJSON`. Each `depends` entry becomes `--path:"/"` in `nimFlags`. Methods: `fetchzip` -> `fetchzip {url,sha256}`; `git` -> `fetchgit {url,rev,sha256,fetchSubmodules,leaveDotGit}`. `path` in the lock is ignored. [S1] +- `nimOverrides` maps a dep name to a function of (lockAttrs, prevAttrs) to add buildInputs etc. Mummy needs none (pure Nim). [S3][S2] +- `overrideNimAttrs` exists to change `src`/`lockFile` before lock flags are generated. [S2][S1] +- Nim: `nim2 = nim-2_2` (NP `pkgs/top-level/all-packages.nix` L4248). Nim 2.2.4 in NP. [S10][all-packages] +- Doc for the example and lock regeneration: `nix run -f . nim_lk ./result | jq --sort-keys > pkgs/by-name/.../lock.json`. The doc says run `nim_lk` on the source directory. [S2] + +### 2.2 nim_builder behavior that matters +- `configurePhase`: writes `config.nims` (backend, nimcache, `-d:release`, `nimDefines`). It also adds `path` switches from `NIX_NIM_BUILD_INPUTS` *nimble files*, not from `requires`. [S5] +- `buildPhase`: `nim compile --outdir:$out/bin /` for each `bin` in the root .nimble. No `bin` = nothing built. [S5] +- `checkPhase`: `nim r tests/t*.nim` (top-level `tests/` only). Root has `tests/tgeometry.nim`, which matches. [S5][local] +- Root `nim.cfg` has `--mm:orc` and `--path:"server"`; no `--threads:on`. Nim 2.2 stdlib config defaults `threads:on` (local `.../nim/config/nim.cfg` L23). Mummy needs threads on. Keep it explicit in `nimFlags` anyway. [local stdlib][MUM README] + +### 2.3 Lock file format (NP) +- Generator: `nim_lk` (sourcehut `~ehmry/nim_lk`; NP `pkgs/by-name/ni/nim_lk/package.nix`). It reads Nimble metadata and emits `{"depends":[...]}`. [S4][S2] +- Entry fields seen: `method`, `packages`, `path`, `ref`, `rev`, `sha256`, `srcDir`, `url`; git entries also `subDir`, `fetchSubmodules`, `leaveDotGit`. [S7][S8] +- Example git entry: `pkgs/by-name/ni/nimlangserver/lock.json`. Example fetchzip entry: `pkgs/by-name/ni/nimdow/lock.json`. [S7][S8] +- nim_lk README: sourcehut is bot-walled from my environment. I could NOT read the README. Whether `nim_lk` accepts `requires "pkg#"` and whether it reads `nimble.lock` is UNVERIFIED. Test it. + +### 2.4 Dependency graph and revisions +Pinned in the owner's devbox nimble cache (`prototype-server-vision/.devbox/nimble/pkgs2/*/nimblemeta.json`, `vcsRevision`). Use as the first lock target, then compare with nim_lk output. + +| dep | constraint in mummy/registry | devbox-resolved vcsRevision | upstream tag check | +|---|---|---|---| +| mummy | `requires "mummy#01deb1ff..."` (servervision.nimble) | `01deb1ff694988635c7bf0f24f6088a0bdf6db5d` | tag `0.4.8` = `77a7563e` [S13][S14] | +| zippy | mummy: `>= 0.10.9` | `cd562ba43ae8904a4d1ba55611b8a521ef4a179e` (0.10.20) | tag exists [API] | +| webby | mummy: `>= 0.2.1` | `325d6ade0970562bee7d7d53961a2c3287f0c4bc` (0.2.1); repo `treeform/webby` | no tags via API | +| crunchy | mummy: `>= 0.1.11` | `98eb6526982bb8aae8eec6e8781f4539fa19e049` (0.1.11) | tag exists [API] | +| nimsimd | crunchy dep | `3f6b2668ffb0867d0bf786a658b817763e611350` (1.3.2) | tag exists [API] | +| db_connector | fff: `requires "db_connector"` (unpinned) | `29450a2063970712422e1ab857695c12d80112a6` (0.1.0) | no tags via API [S15] | + +- mummy nimble (at MUM): `requires nim >= 1.6.8`, `zippy >= 0.10.9`, `webby >= 0.2.1`, `crunchy >= 0.1.11`. [S12] +- db_connector nimble: `requires nim >= 1.7.3`, no other deps. [S15] +- Mummy commit diff vs tag 0.4.8: only `.github/workflows/build.yml` and `docs.yml`. [S13] +- Mummy README: needs `--threads:on` and `--mm:orc` or `--mm:arc`. [MUM README] + +### 2.5 Are the deps in nixpkgs? +- Checked NP tree: `pkgs/by-name` has no `mummy`, `db_connector`, `zippy`, `webby`, `crunchy`, `nimsimd` directories. Grep of `pkgs/` for `mummy|db_connector` only hits unrelated files. No Nim package set (`nimPackages` is empty). [NP tree] +- Conclusion: all deps go through the lock. No nixpkgs package to reuse. + +### 2.6 Alternatives +- **nimble.lock (Nimble native)**: `nimble.lock`, version 2, fields `vcsRevision`, `url`, `downloadMethod`, `checksums.sha1`. Written by `src/nimblepkg/lockfile.nim`. No nixpkgs builder consumes it. Converting it would be a custom script. [S18] +- **atlas**: documents `atlas.lock` via `pin` / `rep` commands. nixpkgs `nim-atlas` is pinned to `unstable-2023-09-22` (`ab22f997`). No nixpkgs builder reads `atlas.lock`. [S17][S11] +- **Vendored deps** (no lock tool): drop `lockFile`, commit deps (or `fetchFromGitHub` each) and pass `nimFlags = ["--path:..." ...]`. `buildNimPackage` makes `lockFile` optional (`optionalAttrs (hasAttr "lockFile")`). Simplest, zero tooling, but every bump is manual. [S1] + +### 2.7 NixOS module precedent +- nitter: `nixos/modules/services/misc/nitter.nix` at NP, lines ~369-420. Unit: `DynamicUser`, `StateDirectory`, `LoadCredential`, `ProtectSystem`-style hardening block: `ProtectHome`, `PrivateDevices`, `ProtectKernel*`, `RestrictAddressFamilies = [AF_INET AF_INET6]`, `SystemCallFilter`, `UMask = 0077`. [S9] +- Nitter package: `pkgs/by-name/ni/nitter/package.nix`, `lockFile = ./lock.json`, `nixosTests`. [S-nitter-pkg] +- Note: nitter's `RestrictAddressFamilies` excludes `AF_UNIX`. DESIGN §11.1 includes `AF_UNIX`; keep it only if the FFF sidecar (Q18/Q19 option b) is chosen. [DESIGN L447] + +### 2.8 Owner's host config +- `/home/davide/Projects/server_nixos_configuration/configuration.nix`: channel-style (``), not flake. Imports per-service files (`gitea.nix`, `foundryvtt.nix`). [local] +- Precedent for a service module file imported from `imports = [...]`. [local `configuration.nix` L13-23] + +### 2.9 Devbox coexistence +- `devbox.json`: `nim: "2"`, `nimble: "latest"`, `NIMBLE_DIR=$DEVBOX_PROJECT_ROOT/.devbox/nimble`; scripts `test` = `nimble test`, `mutation`. [local devbox.json] +- `devbox.lock` resolves nim `2.2.12` (nixpkgs `55ba7f49`), nimble `0.24.1`. [DEV] +- Nix build uses NP nim `2.2.4` unless the flake pins a nixpkgs with 2.2.12. Mismatch risk. +- `nimble test` resolves deps from `requires` (registry + `#commit` pin). The Nix build resolves from the lock. Two resolution paths. Keep revs equal; check `vcsRevision` values above after lock generation. +- `.devbox/` is gitignored; Nix never sees it. No interference, provided the Nix package source does not depend on `.devbox/`. + +## 3. Recommendation + +Use `buildNimPackage` + committed `lock.json` generated by `nim_lk`, pinned to the same nixpkgs as devbox (or a nixpkgs with nim 2.2.12). Package and module live in-repo under `nix/`. Devbox stays the dev shell only. + +Steps (sketch, no files written): +1. Un-ignore the packaging dir: remove `nix/` from `.gitignore` (or name it `packaging/nix/`). [local] +2. Declare a `bin` in `fff_vtt.nimble` once the entrypoint exists (for example `bin = @["main"]`, `srcDir` `server`). Until then the package is empty. Alternative: override `buildPhase`. [S5] +3. Decide mummy ref: keep `01deb1ff` (identical code to 0.4.8 except CI) or move both nimble and Nix to tag `0.4.8`. Fix the DESIGN "no tags" note either way. [S13] +4. Add `db_connector` pin to the lock (no tags upstream; pin the devbox `vcsRevision`). [S15] +5. Generate lock: `nix run #nim_lk -- | jq --sort-keys > nix/lock.json`. Diff `rev`s against the devbox table in §2.4. [S2] +6. `nix/package.nix`: `buildNimPackage (finalAttrs: { pname = "fff-vtt-server"; version; src = lib.cleanSource ../.; lockFile = ./lock.json; nimFlags = ["--threads:on" "--mm:orc"]; ... })`. Let doCheck run `tests/t*.nim`. [S1][S5] +7. `nix/module.nix`: `options.services.fffVtt = { enable; package; port (127.0.0.1 only); publicOrigin; stateDir }`. `systemd.services.fff-vtt`: `wantedBy multi-user.target`, `DynamicUser`, `StateDirectory`, `ExecStart = ${cfg.package}/bin/`, hardening copied from nitter (§2.7), `AF_UNIX` only with sidecar. [S9][DESIGN L447] +8. Host: add `nix/module.nix` to `imports` in `server_nixos_configuration/configuration.nix` (path import or `builtins.fetchGit` pinned to a commit). Mirror `foundryvtt.nix` pattern. [local] +9. Smoke check: `nix build` the package; `nix-build` runs `nim r tests/t*.nim` via doCheck. Optional `nixosTests` VM test as nitter does. [S1][S9] + +Fallback if `nim_lk` cannot resolve `mummy#` or db_connector: vendored deps with `nimFlags --path:` (§2.6). Nothing else changes. + +## 4. Not checked / risks +- nim_lk CLI and its handling of `#commit` requires: unverified (sourcehut blocked). +- No `nix build` run; no lock generated; no fetch hashes computed. Hashes will come from `nim_lk`. +- Devbox nim 2.2.12 vs NP 2.2.4: pinned nixpkgs revision for the build not chosen yet. +- webby tags: none found via API. Pinned rev `325d6ade` is what the devbox resolved; upstream version list not checked. +- `nim_builder`'s `bin` handling assumes the root .nimble lists binaries; checked only the code, not a built example. +- atlas `atlas.lock` format not read in full; only the doc summary. + +## 5. Sources + +NixOS/nixpkgs @ c56a87d8e41ce69bd2af57eb35dcc117a9dfca33 (owner's system nixpkgs): +- [S1] https://github.com/NixOS/nixpkgs/blob/c56a87d8e41ce69bd2af57eb35dcc117a9dfca33/pkgs/build-support/build-nim-package.nix +- [S2] https://github.com/NixOS/nixpkgs/blob/c56a87d8e41ce69bd2af57eb35dcc117a9dfca33/doc/languages-frameworks/nim.section.md +- [S3] https://github.com/NixOS/nixpkgs/blob/c56a87d8e41ce69bd2af57eb35dcc117a9dfca33/pkgs/top-level/nim-overrides.nix +- [S4] https://github.com/NixOS/nixpkgs/blob/c56a87d8e41ce69bd2af57eb35dcc117a9dfca33/pkgs/by-name/ni/nim_lk/package.nix +- [S5] https://github.com/NixOS/nixpkgs/blob/c56a87d8e41ce69bd2af57eb35dcc117a9dfca33/pkgs/by-name/ni/nim_builder/nim_builder.nim +- [S7] https://github.com/NixOS/nixpkgs/blob/c56a87d8e41ce69bd2af57eb35dcc117a9dfca33/pkgs/by-name/ni/nimdow/lock.json +- [S8] https://github.com/NixOS/nixpkgs/blob/c56a87d8e41ce69bd2af57eb35dcc117a9dfca33/pkgs/by-name/ni/nimlangserver/lock.json +- [S9] https://github.com/NixOS/nixpkgs/blob/c56a87d8e41ce69bd2af57eb35dcc117a9dfca33/nixos/modules/services/misc/nitter.nix +- [S-nitter-pkg] https://github.com/NixOS/nixpkgs/blob/c56a87d8e41ce69bd2af57eb35dcc117a9dfca33/pkgs/by-name/ni/nitter/package.nix +- [S10] https://github.com/NixOS/nixpkgs/blob/c56a87d8e41ce69bd2af57eb35dcc117a9dfca33/pkgs/by-name/ni/nim-2_2/package.nix +- [S11] https://github.com/NixOS/nixpkgs/blob/c56a87d8e41ce69bd2af57eb35dcc117a9dfca33/pkgs/by-name/ni/nim-atlas/package.nix +- [all-packages] https://github.com/NixOS/nixpkgs/blob/c56a87d8e41ce69bd2af57eb35dcc117a9dfca33/pkgs/top-level/all-packages.nix (L4246-4255: nim, nim1, nim2, buildNimPackage, nimOverrides) + +Upstream: +- [S12] mummy nimble @ pin: https://github.com/guzba/mummy/blob/01deb1ff694988635c7bf0f24f6088a0bdf6db5d/mummy.nimble +- [MUM README] https://github.com/guzba/mummy/blob/01deb1ff694988635c7bf0f24f6088a0bdf6db5d/README.md +- [S13] tag compare: https://api.github.com/repos/guzba/mummy/compare/77a7563e87a1045e4e407a3a68731e299fa3507e...01deb1ff694988635c7bf0f24f6088a0bdf6db5d +- [S14] mummy tags: https://api.github.com/repos/guzba/mummy/tags +- [S15] db_connector nimble: https://github.com/nim-lang/db_connector/blob/master/db_connector.nimble +- [S17] atlas doc: https://github.com/nim-lang/atlas/blob/master/doc/atlas.md +- [S18] nimble lockfile impl: https://github.com/nim-lang/nimble/blob/master/src/nimblepkg/lockfile.nim +- [API] zippy/crunchy/nimsimd tags: https://api.github.com/repos/guzba/zippy/tags , https://api.github.com/repos/guzba/crunchy/tags , https://api.github.com/repos/guzba/nimsimd/tags + +Local (read-only): +- devbox.json / devbox.lock: /home/davide/Projects/GDR/FFF_vtt/devbox.json, /home/davide/Projects/GDR/FFF_vtt/devbox.lock +- devbox nimble cache (vcsRevision): /home/davide/Projects/GDR/FFF_vtt/prototype-server-vision/.devbox/nimble/pkgs2/*/nimblemeta.json +- nim 2.2.4 stdlib (threads default, no db_* modules): /nix/store/aa4fgarndnvq417l50imvqx5fdrrx9sn-nim-unwrapped-2.2.4/nim/config/nim.cfg, /nix/store/aa4fgarndnvq417l50imvqx5fdrrx9sn-nim-unwrapped-2.2.4/nim/lib +- owner config: /home/davide/Projects/server_nixos_configuration/configuration.nix, foundryvtt.nix +- repo .gitignore: /home/davide/Projects/GDR/FFF_vtt/.gitignore