## fff-vtt entrypoint. M3 slice 2 (#17): getting in - config, state dir + data-dir lock, SQLite ## migrations, `fff-vtt gm-key`, `POST /join`, session cookies, the authenticated `/ws` upgrade ## with connection caps and key/player revocation. ## M3 slice 3 (#18): the WS protocol shell - `hello`, the per-connection `n` counter, exactly one ## `ack` per intent, `error` frames, the intent rate limit, the malformed-flood close, the proto ## version check, the oversize frame limit (mummy's 64 KB) and the server Ping heartbeat. ## M3 slice 4 (#19): walls and doors - the one scene loaded at startup, `wall.add`, `wall.update`, ## `wall.remove` and `door.set` (GM only), the GM `walls` snapshot on connect, `wall`/`wall_gone` ## to every GM connection, and nothing about walls ever reaching a player (DESIGN 3.1, 6.1, 8). ## M3 slice 5 (#20): tokens and sight - `token.create`/`token.update`/`token.remove`/`token.move` ## through server/moverules.nim, one vision polygon per controlled token with the `vision` flag, the ## per-player explored set, and per-recipient egress: every state frame a socket receives is built by ## server/views.nim from a typed `GmView`/`PlayerView`, so raw world state has no other path out. ## M3 slice 6 (#21): explored persistence - the per-player explored grid is stored as 64x64-cell ## bitmaps (server/explored.nim, migration step 5), loaded at startup and upserted per mutation with ## only the chunks that mutation dirtied (DESIGN 4.2 step 6, 4.4). ## M3 slice 7 (#22): token details - `token.resize` (5.6, grow push or squeeze), `status.set` / ## `status.clear` with the `walls`|`GM` sources of 5.5 (`source` is GM-only on the wire), `prop.set` / ## `prop.unset` under the bucket caps of server/props.nim, and the per-token radius, props and status ## effects on `token.create`, `token.move`, `wall.*` and `door.set`. ## M3 slice 8 (#23): characters and names - `character.create`/`update`/`remove`/`reassign`, the ## per-player reveal of an actual name (`name.reveal`, `name.reveal_all`), the per-player encountered ## list (`encountered.remove`, recorded on every sighting), character props through `prop.*`, and the ## players/keys half that names a player: `player.setname`, `player.rename`, `key.show` and the ## `roster` frame. The token link (`token.create`/`token.update` `character_id`) lands here too. ## M3 slice 9 (#24): map tiles - `GET /tiles//v/_.png` in ## server/tiles.nim: a strict canonical URL, the player's explored rule (the GM always), `404` for a ## tile that does not exist and a bodyless `200` with `X-Accel-Redirect` to the internal `/_tiles/` ## location, which nginx alone can serve (DESIGN 3.3, 6.6, 11.1). ## M3 slice 10 (#25): the finish line - `scene.set` (the 29th catalogue intent: the settable scene ## fields, the token-radius-default resize through 5.6, and a hello + full resync of every ## connection), plus the restart and logs acceptance groups and the group checklist. ## Close reasons (FIXED, owner decision #18): mummy 0.4.8 cannot put a code in the close frame, so ## every server-initiated close is preceded by a `closing {reason, code}` message and the client ## reads 1005 + that message (DESIGN 6.5). ## The listen address is the constant config.BindAddress (127.0.0.1): nginx is the only public face. import std/[atomics, json, locks, options, os, sequtils, sets, strutils, tables] import std/typedthreads import db_connector/db_sqlite import mummy, mummy/routers import config, db, eventlog, crypto, auth, conns, instancelock, protocol, world, jsonbound import characters, geometry, markers, props, text, tiles, tokens, vision, views, explored, worldmap, faults, moverules const CookieName* = "fff_session" ## FIXED (owner-delegated, #17); DESIGN 6.6 had it PROPOSED. MaxJoinBody* = 1024 ## DESIGN 6.6: the sign-in body is at most 1 KB. WorkerThreads* = 4 ## mummy defaults to 10x cores (160 on a 16-core box) for a table of at most seven people; every ## mutation takes one global lock, so more workers only queue. Four leave room for HTTP/WS/tiles. type App = ref object cfg: Config lg: Logger db: DbConn dbLock: Lock ## The one global lock (DESIGN 4.3): it serializes every mutation, the DB, and the world below. conns: Conns instanceLock: InstanceLock scene: SceneRec ## The single v1 scene with its walls, loaded at startup and never re-read (4.1). tokens: seq[TokenRec] ## Every token of the scene, in creation order, loaded at startup (4.1). visions: Table[int, PlayerVision] ## Per-player sight state (4.1 PlayerState): polygons, explored cells, fresh cells. Created on ## a player's first connection; the GM has no entry (the GM sees everything, 6.1). characters: seq[CharacterRec] ## Every character, in creation order, loaded at startup (8; slice 8 / #23). reveals: Reveals ## Per-player name reveals, `(player, subject)` rows (8; slice 8). encountered: Encountered ## Per-player encountered lists, player id -> token id -> snapshot (8; slice 8). known: Table[int, views.Known] ## Per-connection egress diff state (4.1 `known`), keyed by the app connId (H19). Pruned on ## every egress pass, so a closed connection leaves nothing behind. gmPlayerId: int ## The GM's player id. A `controller` naming it means "the GM", i.e. `GmControlled`. registry: props.Registry ## The property-schema registry (DESIGN 8/9): empty in v1, permissive fallback. One copy for ## the whole process, so the wire layer and the egress cannot disagree about it. var appHandle: pointer ## The one App for the process. A plain pointer keeps worker-thread handlers `{.gcsafe.}` ## (mummy's handler types are non-closure procs, so the state cannot be captured). template app(): App = cast[App](appHandle) var heartbeatThread: Thread[void] ## The ping thread's handle must outlive the process (a global, not a stack local). var pingCounter: Atomic[int64] ## Payload of the last server Ping; the client echoes it in its Pong (4.3). Atomic because the ## heartbeat thread and the upgrade handler (a worker thread) both send pings. var ackedReqId {.threadvar.}: int ## #32: the reqId whose ack this handler invocation already enqueued, or -1. A threadvar is enough ## because it is written and read entirely inside one `handleText` call on the thread that serves ## the frame, even when that call unwinds through the dispatch guard. proc nextPingSeq(): int64 = pingCounter.fetchAdd(1) + 1 # --------------------------------------------------------------------------------------------------- # Frame senders. `n` is the per-connection counter (DESIGN 6): it is allocated under the registry # lock, so two threads sending to one connection never collide, and a frame is dropped for a # connection that is gone (nextFrameNo answers 0). proc nextN(conn: Conn): int = ## 0 = the connection is gone: the frame is dropped. app.conns.nextFrameNo(conn.id) proc ackOk(conn: Conn, reqId: int, extra: JsonNode = nil) = ackedReqId = reqId let n = nextN(conn) if n > 0: conn.ws.send($ackFrame(reqId, n, extra)) proc ackErr(conn: Conn, reqId: int, code: string) = ackedReqId = reqId let n = nextN(conn) if n > 0: conn.ws.send($nackFrame(reqId, n, code)) proc sendError(conn: Conn, code: string) = ## Only for frames that cannot be acked (DESIGN 6.5). let n = nextN(conn) if n > 0: conn.ws.send($errorFrame(code, n)) proc closeRegistered(conn: Conn, reason: string, code: int) = ## A server-initiated close of a live connection: `closing` first (FIXED #18), then the close ## frame. The registry entry goes first so nothing else can be enqueued behind the reason. let n = nextN(conn) app.conns.remove(conn.id) if n > 0: conn.ws.send($closingFrame(reason, code, n)) conn.ws.close() proc closeGone(conn: Conn, reason: string, code: int) = ## Same, for a connection the registry already dropped (eviction, revocation). The snapshot's ## frame number still closes the sequence correctly. conn.ws.send($closingFrame(reason, code, conn.frameNo)) conn.ws.close() # --------------------------------------------------------------------------------------------------- # Wall fan-out (DESIGN 3.1: walls are GM-only data; a player never receives one, in any message). # Walls are not part of the egress view: they are GM-only by construction, so they bypass # views.egressFrames and never enter a PlayerView at all. proc wallObjectOf(w: WallRec): JsonNode = ## The GM's typed wall (DESIGN 6.1 proto 2): every stored field plus the derived shape label. wallObject(WallView(id: w.id, a: w.a, b: w.b, thickness: w.thickness, position: $w.position, blocksSight: w.blocksSight, blocksMovement: w.blocksMovement, sightDir: $w.sightDir, playerMarker: w.playerMarker, door: w.door, open: w.open, secret: w.secret, locked: w.locked, height: (if w.height.isSome: w.height.get else: 0.0), hasHeight: w.height.isSome, label: (if w.label.isSome: w.label.get else: ""), hasLabel: w.label.isSome, kind: derivedKind(w), flags: w.flags)) proc wallsSnapshot(sc: SceneRec): JsonNode = var walls: seq[JsonNode] for w in sc.walls: walls.add wallObjectOf(w) wallsFrame(sc.id, walls) proc sendToGms(frame: JsonNode) = ## Every GM connection, each with its own `n` (DESIGN 6.1 `wall`/`wall_gone`, 6). The loop is ## sequential on this thread, so reusing one frame object while stamping `n` is safe. ## `LEAK_FAULT=walls` (a -d:leakfault build only) also sends it to players: the negative control ## for the WALLDATA class (DESIGN 10.3). let leakToPlayers = faultActive("walls") for c in app.conns.snapshot(): if c.role != prGm and not leakToPlayers: continue let n = nextN(c) if n > 0: c.ws.send($withN(frame, n)) # --------------------------------------------------------------------------------------------------- # Egress (DESIGN 2 single egress rule, 4.2 step 7). Everything a recipient learns about tokens, # vision and explored goes through views.egressFrames; this section only moves the bytes. proc allIds(): seq[string] = ## Every id already in use, tokens and characters together: they share one namespace (8), so a new ## character cannot collide with a token and a reveal subject is never ambiguous. app.tokens.mapIt(it.id) & app.characters.mapIt(it.id) proc egressContext(): views.Context = ## Six addresses, no copies (#28): the App owns the world and every player's sight state, and the ## egress borrows them for the pass. Building this used to copy `visions` (a whole explored ## `HashSet` per player) and the two-level `encountered` table on every mutation, under the global ## lock; now it cannot depend on how much a player has explored. Caller holds the lock (4.3), so ## the borrow is one consistent state for the whole fan-out. views.contextOf(app.scene, app.tokens, app.characters, app.reveals, app.encountered, app.visions) proc pruneKnown() = ## A closed connection's `known` table must not outlive it. var live = initHashSet[int]() for c in app.conns.snapshot(): live.incl c.id for id in app.known.keys.toSeq: if id notin live: app.known.del id proc refreshPlayer(pid: int) = ## Recompute one player's polygons and explored cells (4.2 step 5). Caller holds the lock. The ## sight state is created on first use, so a player who never connected still gets one the moment ## they do (nothing is stale from startup, 4.1). The table entry is passed by reference: reading it ## into a `var` would copy it and the update would be lost. The same refresh mints the player's ## markers (5.8): the polygon is the gate, so it must run after `refresh`. if pid == GmControlled: return app.visions.mgetOrPut(pid, PlayerVision()).refresh(app.scene, app.tokens, pid) discard markers.syncMarkers(app.visions.mgetOrPut(pid, PlayerVision()), app.scene) proc refreshAll() = ## A wall or door changed: every player's sight changes (4.2 step 5). for pid in app.visions.keys.toSeq: refreshPlayer(pid) # --------------------------------------------------------------------------------------------------- # The encountered list (DESIGN 8, 6.1; slice 8 / #23). One rule: a token that a player can see is in # that player's list from then on, under the name that player knows at that moment. It is recorded # before the ack (like explored cells) and only ever grows except for `encountered.remove`. proc recordEncounters() = ## Adds every token now visible to a player that is not in that player's list yet. Cheap in the ## steady state: a token already in the list costs one table lookup, and only an unknown token ## runs the visibility rule. A player without sight state has no polygons and so sees only the ## tokens it controls, which is the same rule `vision.visibleTo` applies. var fresh: seq[(int, characters.EncounteredEntry)] for pid in app.visions.keys.toSeq: if pid == GmControlled: continue let hasList = app.encountered.hasKey(pid) for t in app.tokens: if hasList and app.encountered[pid].hasKey(t.id): continue if not app.visions[pid].visibleTo(t, pid): continue let names = subjectNamesOf(t, app.characters) let knows = knowsActual(names.owner == pid and names.owner > 0, names.revealAll, app.reveals.isRevealed(pid, names.id)) fresh.add (pid, newEntry(t.id, names, knows)) if fresh.len == 0: return # NORMAL durability: a snapshot of where somebody has been is derived data, like explored cells # (Q12), and the ack is sent after this commit (4.2 step 7). app.db.withTransaction: for (pid, e) in fresh: writeEncountered(app.db, pid, e) for (pid, e) in fresh: app.encountered.mgetOrPut(pid, initTable[string, characters.EncounteredEntry]())[e.entityId] = e # --------------------------------------------------------------------------------------------------- # Derived player memory persistence: explored cells and player markers (DESIGN 4.2 step 6, 4.4, 5.8; # M3 slice 6 / #21, #59). Both live in memory and reach the DB here, except a marker cause-change # delete, which `world.updateWall` commits with the wall row (5.8, #60). One rule: a mutation writes # exactly the explored chunks its refresh dirtied and the markers it minted, never the whole state, # and the write rides in the mutation's transaction so an ack cannot precede what it reports. NORMAL # durability (Q12): both are derived (explored only grows; a marker is minted and retracted by the # GM's causes), never GM-authored. proc dirtyExplored(pids: openArray[int]): seq[explored.Chunk] = ## The chunks the last refresh dirtied, for the named players. Caller holds the lock and has ## already refreshed those players, so `fresh` is current. A player with nothing fresh costs one ## table lookup and is skipped. for pid in pids: if pid == GmControlled: continue let fresh = app.visions.mgetOrPut(pid, PlayerVision()).fresh if fresh.len == 0: continue for c in explored.dirtyChunks(app.scene, pid, app.visions.mgetOrPut(pid, PlayerVision()).explored, fresh): result.add c proc persistMarkers(pids: openArray[int]) = ## The marker half alone, for a connect where the explored grid must stay exactly as it was (a ## schema-4/7 database rebuilds its grid on connect and stores nothing until a mutation): a marker ## minted at the resync is still durable before it is sent (5.8, 4.2 step 6). The deletes run ## before the inserts: a moved wall's old rows are already gone (the wall transaction took them), ## and a fresh one is stored after them, so one id can never be set and deleted in one refresh. for pid in pids: if pid == GmControlled: continue discard markers.writeDead(app.db, pid, app.visions.mgetOrPut(pid, PlayerVision()).markerDead) discard markers.writeNew(app.db, app.scene.id, pid, app.visions.mgetOrPut(pid, PlayerVision()).markerFresh) proc persistDerived(pids: openArray[int]) = ## Writes the dirtied explored chunks and the markers the same refresh minted (5.8: marker inserts ## ride the same derived-memory transaction as the explored chunks, after the wall row committed; ## a cause-change delete already committed with that row). No transaction of its own: the caller ## wraps it together with the mutation's row writes. let chunks = dirtyExplored(pids) if chunks.len > 0: discard explored.writeChunks(app.db, app.scene.id, chunks) persistMarkers(pids) proc persistAllDerived() = ## After `refreshAll` (a wall or door changed): every player whose grid grew or markers changed. app.db.withTransaction: persistDerived(app.visions.keys.toSeq) proc egressAll() = ## One pass over every live connection: build that recipient's view, diff it against what the ## connection already knows, send the difference. 4.2 step 8: the fresh cells are cleared here, ## after every connection of every player has been offered them. let ctx = egressContext() for c in app.conns.snapshot(): if c.role != prGm and not c.named: continue # 6.3: an unnamed player gets `hello` and nothing else until it is named let recipient = views.Recipient(isGm: c.role == prGm, playerId: c.playerId) let frames = egressFrames(recipient, ctx, app.known.mgetOrPut(c.id, views.Known())) for f in frames: let n = nextN(c) if n > 0: c.ws.send($withN(f, n)) for pid in app.visions.keys.toSeq: app.visions[pid].clearFresh() pruneKnown() # --------------------------------------------------------------------------------------------------- # The player roster (DESIGN 3.1, 6.1; Q9 FIXED: players see each other's names). Two variants are # built once per fan-out: the GM sees every player (`name: null` for an unused key), a player sees # named players only, so an unused key or the number of keys is not visible (6.1 leak note 4). proc rosterFrames(): tuple[everyone: JsonNode, namedOnly: JsonNode] = var everyone: seq[JsonNode] var named: seq[JsonNode] for p in allPlayers(app.db): let connected = app.conns.activeCountFor(p.id) > 0 let nameJson = if p.name.isSome: %p.name.get else: newJNull() everyone.add rosterEntry(p.id, nameJson, $p.role, p.colour, connected) if p.name.isSome: named.add rosterEntry(p.id, nameJson, $p.role, p.colour, connected) (rosterFrame(everyone), rosterFrame(named)) proc sendRoster() = ## To every connection, each with its own `n` (a frame taking `n` is built per recipient here). let frames = rosterFrames() for c in app.conns.snapshot(): if c.role != prGm and not c.named: continue # 6.3: an unnamed player gets `hello` only let n = nextN(c) if n > 0: c.ws.send($withN(if c.role == prGm: frames.everyone else: frames.namedOnly, n)) proc sendHello(connId: int, player: Player) = ## The `hello` frame (6.1): the first frame on a connection, and again after `player.setname` ## (which is why it lives in a proc both paths call). Keyed by the app connId so a caller holding ## only the id (the upgrade handler) and one holding the record (the fan-out) share it. ## A `hello` tells the client to reset everything (6.1), so the server's diff base for that ## connection resets with it: without this, a `scene.set` resync would skip every unchanged token ## and the client would hold an empty world. `resync` runs right after every `hello`. let named = player.name.isSome let me = if named: %player.name.get else: newJNull() var sceneJson: JsonNode if player.role == prGm or named: sceneJson = sceneBlock(app.scene) var extraJson: JsonNode if player.role == prGm: extraJson = app.scene.extra let helloN = app.conns.nextFrameNo(connId) let found = app.conns.connById(connId) if helloN <= 0 or found.isNone: return app.known.del connId found.get.ws.send($helloFrame(ProtoVersion, helloN, $player.role, player.id, me, sceneJson, extraJson)) proc resync(connId: int, named: bool, player: Player) = ## The 6.3 sequence after `hello`: `roster` first; GM gets `walls`, `character` for all, ## `encountered` per player, then every token; a named player gets its own `character` records, ## its `encountered` list, `vision`, `explored` (full) then every token it may see. An unnamed ## player gets nothing beyond `hello`. `egressFrames` emits the character/encountered half in that ## order, so this proc only has to put `roster` and the wall snapshot in front of it. The caller ## holds the global lock (4.3), which is also why `recordEncounters` can write here. let isGm = player.role == prGm let found = app.conns.connById(connId) if found.isNone: return let conn = found.get # This is the moment a connection starts receiving state, so the player's own sight is computed # here: a connection opened while unnamed never had a refresh, and `player.setname` resyncs on the # same socket (6.1). Idempotent: a refresh that changes nothing only costs the polygon pass. if not isGm and named: refreshPlayer(player.id) # A marker minted here (a window the player had not seen before connecting) must be durable like # any other derived memory before the resync sends it (5.8, 4.2 step 6). Only markers: the # explored grid keeps its own existing connect behaviour (nothing is stored here). No # transaction when there is nothing to write: the common connect must not open one. if app.visions.mgetOrPut(player.id, PlayerVision()).markerDead.len > 0 or app.visions.mgetOrPut(player.id, PlayerVision()).markerFresh.len > 0: app.db.withTransaction: persistMarkers(@[player.id]) # A token visible right now is a sighting: record it before the `encountered` list is built (the # player may have been offline while something walked into their sight). recordEncounters() if isGm or named: let frames = rosterFrames() let n = nextN(conn) if n > 0: conn.ws.send($withN(if isGm: frames.everyone else: frames.namedOnly, n)) if isGm or faultActive("walls"): let snap = wallsSnapshot(app.scene) let n = nextN(conn) if n > 0: conn.ws.send($withN(snap, n)) if not isGm and not named: return let recipient = views.Recipient(isGm: isGm, playerId: player.id) # The diff state is passed by reference straight out of the table: `var known = ...mgetOrPut(...)` # would COPY the entry and the connection would forget everything it learnt on connect. for f in egressFrames(recipient, egressContext(), app.known.mgetOrPut(conn.id, views.Known()), resync = true): let n = nextN(conn) if n > 0: conn.ws.send($withN(f, n)) proc resyncEveryone() = ## `scene.set` (6.1): `hello` plus a full resync to every connection, unnamed players included ## (they get `hello` and nothing else, 6.3). The scene block in `hello` may have changed, so even ## a connection that has no state yet is told. Caller holds the global lock. for c in app.conns.snapshot(): let p = playerById(app.db, c.playerId) if p.isSome: sendHello(c.id, p.get) resync(c.id, c.named, p.get) proc settleSetNameLocked(conn: Conn, reqId: int, named: Player, ackFirst = true) = ## `player.setname`'s effects (6.1, 6.3): every connection of that player gets `hello` with ## `me.name`, then the full resync; `roster` to all. The ack is enqueued first, after the durable ## write and before any effect (#33); the effects keep their own order. Caller holds the lock and ## has already committed the name. if ackFirst: ackOk(conn, reqId) for c in app.conns.connectionsOf(named.id): sendHello(c.id, named) resync(c.id, true, named) sendRoster() if not ackFirst: ackOk(conn, reqId) proc settleLocked(conn: Conn, reqId: int, extra: JsonNode = nil, roster = false) = ## 4.2 step 7 for a mutation: the ack and then every recipient's diff are enqueued under the global ## lock, so no two threads touch a connection's `known` table at once and the ack always precedes ## the effects that mutation caused. Every frame is built from the state at enqueue time, so a ## mutation that runs between another mutation's transaction and its settle cannot send stale ## state; the exact per-connection ordering of two concurrent mutations, and the coalescing that ## makes it cheap, are the M5 outbox (4.3). ## `recordEncounters` runs before the ack: a sighting is durable before the client is told about it ## (the same rule explored cells follow, 4.2 step 6). `roster` = the player list changed. ## Caller holds `app.dbLock` (ANALYSIS 4.1: every frame that references world state is built here). recordEncounters() ackOk(conn, reqId, extra) faults.injectAfterAck() if roster: sendRoster() egressAll() proc settle(conn: Conn, reqId: int, extra: JsonNode = nil, roster = false) = ## The general form: takes the lock itself. `extra` must not reference world state (ints, floats ## and freshly allocated strings only); a handler that has a world record in hand calls ## `settleLocked` inside its own critical section instead. withLock app.dbLock: settleLocked(conn, reqId, extra, roster) proc settleWorldLocked(conn: Conn, reqId: int, wallEffect: JsonNode, extra: JsonNode = nil, roster = false) = ## The same for a wall/door write: ack, the GM-only wall effect, then the per-recipient egress ## (a wall change can reveal or hide tokens and always changes vision). `wallEffect` references a ## wall record, so it is built by the caller *inside* the same critical section; the frame and the ## last reference to the record both die here, under the lock. recordEncounters() ackOk(conn, reqId, extra) sendToGms(wallEffect) if roster: sendRoster() egressAll() # --------------------------------------------------------------------------------------------------- # Applying a move-rules outcome (DESIGN 5.5, 5.6). Every wall/door edit and every resize runs the # pure rules on a snapshot of the tokens (`worldmap.moveScene`), then the DB write, then this: the # new positions (door push, grow push) and the walls-sourced statuses that the event changed are # persisted and copied into memory. Nothing is applied when the write failed, so memory and DB stay # identical. Positions and derived statuses use one NORMAL transaction (Q12): neither is authored. proc applyRuleOutcome(mr: moverules.Scene): int = ## Persists every token the rules changed and then copies it into memory. Caller holds the lock and ## has already committed the wall/door/resize row, so a failing write here leaves the DB without the ## new positions and memory untouched (4.2 step 6). `refreshAll` runs afterwards by the caller. var changes: seq[(int, TokenRec)] for i in 0 ..< min(mr.tokens.len, app.tokens.len): var rec = app.tokens[i] # object copy; the JsonNode refs are shared and never mutated let outcome = rec.applyOutcome(mr.tokens[i]) if outcome.moved or outcome.statuses: changes.add (i, rec) if changes.len == 0: return 0 app.db.withTransaction: for (_, rec) in changes: discard writePosition(app.db, rec) writeStatuses(app.db, rec) for (i, rec) in changes: app.tokens[i] = rec changes.len # --------------------------------------------------------------------------------------------------- # Intent field helpers (DESIGN 6.1, 6.5 steps 7-8): shape first, then lookup. type SetNameOutcome = enum snOk snTaken snNotAllowed RenameOutcome = enum rnOk rnNotFound rnTaken RevealOutcome = enum nrOk nrNotFound nrInvalid ## a token that has a character: reveal through the character (6.1) type SceneCheck = enum scOk scInvalid ## `scene` missing or not an integer -> `invalid` scNotFound ## an integer, but not the one scene of v1 -> `not-found` proc checkScene(env: Envelope): SceneCheck = ## `scene` is the id of the single v1 scene (DESIGN 6.1, 6.5 step 8: a GM's missing target is ## `not-found`; a wrongly typed field is `invalid`). The id is read under the global lock: the ## scene record is swapped there, never mutated in place (#31), and this handler thread must not ## read the field while `scene.set` assigns it. let node = env.node{"scene"} if node.isNil or node.kind != JInt: return scInvalid var sceneId = 0 withLock app.dbLock: sceneId = app.scene.id if node.getInt != sceneId: return scNotFound scOk proc intField(env: Envelope, key: string, dest: var int): bool = let node = env.node{key} if node.isNil or node.kind != JInt: return false dest = node.getInt true proc sceneOk(conn: Conn, env: Envelope): bool = ## Sends the refusal itself (6.5 steps 7-8); true = the intent names the one v1 scene. case checkScene(env) of scInvalid: ackErr(conn, env.reqId, CodeInvalid) of scNotFound: ackErr(conn, env.reqId, CodeNotFound) of scOk: return true proc stringField(env: Envelope, key: string, dest: var string): bool = let node = env.node{key} if node.isNil or node.kind != JString: return false dest = node.getStr true proc boolField(env: Envelope, key: string, dest: var bool): bool = let node = env.node{key} if node.isNil or node.kind != JBool: return false dest = node.getBool true proc present(env: Envelope, key: string): bool = ## The field exists and is not JSON null (DESIGN 6.1: absent and null are the same for these ## payloads, except where a null has its own meaning, e.g. `controller` and `vision_radius`). not fieldOrNull(env.node, key).isNil proc declared(env: Envelope, key: string): bool = ## The field is there, JSON null included: `controller: null` means "the GM" and ## `vision_radius: null` means "the scene default" (6.1), so both are real patch fields. not env.node.isNil and env.node.hasKey(key) proc opaqueRefused(field: string, node: JsonNode) = ## #35: one structured line naming the field and the limit it broke, never the contents. let limit = props.checkOpaqueObject(node) if limit != props.olOk: app.lg.log(lvInfo, "opaque_refused", [("field", field), ("limit", props.limitName(limit))]) # Wall payload fields (DESIGN 6.1, proto 2, #54). `kind` and (in an update) `open` are never read: # they are unknown fields and ignored (6.2). Absent and JSON null are the same field-absent for # every wall field except `height` and `label`, where an explicit null means "clear it". proc parseWallGeometryAndLabel(env: Envelope, patch: var WallPatch): bool = ## THE one parser for the geometry and label fields of `wall.add` and `wall.update` (6.1). ## One rule for both payloads: `a`, `b`, `thickness` and `position` treat absent and JSON null as ## the same field-absent, while `height` and `label` treat an explicit null as a real patch ## ("clear it"), carried by `clearHeight`/`clearLabel`. Ranges and the 6.5 text rule are checked ## once on the resulting wall by `validWall`. if present(env, "a"): let v = parseVec(env.node{"a"}) if v.isNone: return false patch.a = v if present(env, "b"): let v = parseVec(env.node{"b"}) if v.isNone: return false patch.b = v if present(env, "thickness"): let v = parseFinite(fieldOrNull(env.node, "thickness")) if v.isNone: return false patch.thickness = v if present(env, "position"): let node = env.node{"position"} if node.kind != JString: return false let p = parsePosition(node.getStr) if p.isNone: return false patch.position = p if declared(env, "height"): let node = env.node{"height"} if node.kind == JNull: patch.clearHeight = true else: let v = parseFinite(node) if v.isNone: return false patch.height = v if declared(env, "label"): let node = env.node{"label"} if node.kind == JNull: patch.clearLabel = true elif node.kind == JString: patch.label = some(node.getStr) else: return false true proc parseWallPreset(env: Envelope, dest: var Option[Preset]): bool = ## `preset` is a 5.8 name, never JSON null; anything else is `invalid`. if not declared(env, "preset"): return true let node = env.node{"preset"} if node.kind != JString: return false let p = parsePreset(node.getStr) if p.isNone: return false dest = p true proc parseWallSetting(env: Envelope, key: string, dest: var Option[bool]): bool = ## One raw setting: absent = not patched; a non-boolean is `invalid`. if not present(env, key): return true var bit: bool if not boolField(env, key, bit): return false dest = some(bit) true proc parseWallSettings(env: Envelope, sw: var WallSettings, allowOpen: bool): bool = ## Collects the raw 5.8 settings the payload names. `open` is collected only on a create; in an ## update it is an unknown field and is ignored (`door.set` owns it, DESIGN 6.1). if not parseWallSetting(env, "blocks_sight", sw.blocksSight): return false if not parseWallSetting(env, "blocks_movement", sw.blocksMovement): return false if not parseWallSetting(env, "player_marker", sw.playerMarker): return false if not parseWallSetting(env, "door", sw.door): return false if allowOpen and not parseWallSetting(env, "open", sw.open): return false if not parseWallSetting(env, "secret", sw.secret): return false if not parseWallSetting(env, "locked", sw.locked): return false if present(env, "sight_dir"): let node = env.node{"sight_dir"} if node.kind != JString: return false let d = parseSightDir(node.getStr) if d.isNone: return false sw.sightDir = d true proc parseWallPatch(env: Envelope, patch: var WallPatch, allowOpen = false): bool = ## The one wall-field parser: `wall.update` and, with `allowOpen`, `wall.add`. `open` and `kind` ## are unknown on an update and are ignored: a door's open state changes only through `door.set` ## (DESIGN 6.1, #54). A preset replaces the whole setting set and may not appear with any raw ## setting, `open` included (`open:false` too, #55). if not parseWallGeometryAndLabel(env, patch): return false if not parseWallPreset(env, patch.preset): return false if not parseWallSettings(env, patch.settings, allowOpen): return false if patch.preset.isSome and (patch.settings.hasAnySetting or declared(env, "open")): # preset xor raw settings; an `open` field alongside a preset is `invalid` even though open is # otherwise an ignored unknown field on an update (DESIGN 6.1, #55). return false if present(env, "flags"): let f = parseFlags(env.node{"flags"}) if f.isNone: return false # #35: wall `flags` is opaque but bounded (token `flags` keeps its old, uncapped path). if props.checkOpaqueObject(f.get) != props.olOk: return false patch.flags = f true proc wallPatchHasField(patch: WallPatch): bool = patch.a.isSome or patch.b.isSome or patch.thickness.isSome or patch.position.isSome or patch.height.isSome or patch.clearHeight or patch.label.isSome or patch.clearLabel or patch.preset.isSome or patch.settings.hasAnySetting or patch.flags.isSome type ControllerCheck = enum ccOk ccInvalid ccNotFound proc resolveController(raw: JsonNode, dest: var int): ControllerCheck = ## `controller`: a player id, or null = the GM (DESIGN 6.1). The GM's own player id is stored as ## GM-controlled, so "the GM controls it" has one representation in memory and on the wire. ## Reads the DB (6.5 step 8): the caller holds the lock. if raw.isNil or raw.kind == JNull: dest = GmControlled return ccOk if raw.kind != JInt: return ccInvalid let id = raw.getInt if id == app.gmPlayerId: dest = GmControlled return ccOk if playerById(app.db, id).isNone: return ccNotFound dest = id ccOk # --------------------------------------------------------------------------------------------------- # HTTP helpers proc formValue(body, name: string): string = ## application/x-www-form-urlencoded: first value of `name`, percent-decoded, '+' = space. for pair in body.split('&'): let eq = pair.find('=') let rawName = if eq >= 0: pair[0 ..< eq] else: pair if rawName != name: continue let raw = if eq >= 0: pair[eq + 1 .. ^1] else: "" result = "" var i = 0 while i < raw.len: if raw[i] == '+': result.add ' ' inc i elif raw[i] == '%' and i + 2 < raw.len: let hex = raw[i + 1 .. i + 2] try: result.add char(parseHexInt(hex)) except ValueError: result.add raw[i] inc i continue i += 3 else: result.add raw[i] inc i return proc sessionCookie(request: Request): string = ## First `fff_session` cookie across all Cookie headers (mummy's [] returns only the first header). for (name, value) in request.headers: if name.toLowerAscii != "cookie": continue for part in value.split(';'): let p = part.strip if p.startsWith(CookieName & "="): return p[CookieName.len + 1 .. ^1] proc protoQuery(request: Request): int = ## `/ws?proto=N` (DESIGN 6.2). -1 = absent or not a plain integer: HTTP 400, no upgrade (6.5 row 3). let raw = request.queryParams["proto"] if raw.len == 0 or raw.len > 9 or not raw.allCharsInSet(Digits): return -1 try: result = parseInt(raw) except ValueError: return -1 # --------------------------------------------------------------------------------------------------- # HTTP handlers proc healthz(request: Request) {.gcsafe.} = ## Liveness only in this slice. M5 makes it report the global lock as well (DESIGN 11.3). var headers: HttpHeaders headers["Content-Type"] = "application/json" request.respond(200, headers, """{"status":"ok"}""") proc join(request: Request) {.gcsafe.} = ## POST /join: the only way to get a session (DESIGN 3.2, 6.6). The key travels in the body only. let contentType = request.headers["Content-Type"].toLowerAscii if not contentType.startsWith("application/x-www-form-urlencoded"): request.respond(400, body = "") return if request.body.len > MaxJoinBody: request.respond(400, body = "") return let key = formValue(request.body, "key") if key.len == 0 or key.len > MaxJoinBody: request.respond(400, body = "") return var player: Option[Player] var token = "" withLock app.dbLock: player = findPlayerByKey(app.db, key) if player.isSome: token = randomSessionToken() createSession(app.db, player.get.id, sha256Hex(token)) if player.isNone: # No key, no body, no detail: a wrong key and an unknown key look the same (T9 discipline). app.lg.log(lvInfo, "join_refused") request.respond(401, body = "") return if faultActive("keylog"): # Test-only negative control for the "logs" acceptance group (#25): write the raw secret to # stdout, bypassing `eventlog` on purpose, so the group's grep must find it in a fault build. # Compiled out of the shipped binary (faults.nim). stdout.write("FAULT keylog key=" & key & "\n") stdout.flushFile() # The token is deliberately never registered for redaction: sessions never expire, so a value # registry would grow without bound. It is only ever written to the Set-Cookie header; if a future # call site passes it to the logger, the `cookie`/`session` field-name mask is the net (11.3). app.lg.log(lvInfo, "join_ok", [("player", $player.get.id)]) var headers: HttpHeaders headers["Location"] = "/" headers["Set-Cookie"] = CookieName & "=" & token & "; HttpOnly; Secure; SameSite=Strict; Path=/" headers["Referrer-Policy"] = "no-referrer" request.respond(303, headers) proc tileGate(request: Request) {.gcsafe.} = ## GET /tiles//v/_.png (DESIGN 3.3, 6.6; slice 9 / #24). Order: parse ## the URL (malformed, out of range, another scene, stale art version -> 404 whatever the session), ## then the session (missing or unknown -> 403), then the explored grid (unexplored -> 403). ## The GM is always allowed. Nim never opens a tile file: a `200` carries `X-Accel-Redirect` to ## the internal `/_tiles/` location and `Cache-Control: private` (Q4), and nginx serves the bytes. ## ## The scene is read exactly once, under the global lock (#31): `scene.set` reassigns `app.scene` ## under that same lock, so this request parses the URL, checks the explored grid and builds the ## redirect from ONE record. A second read could see a swapped scene whose `walls`/`artVersion` ## disagree with the parse (the old code read it three times, twice outside the lock). let token = sessionCookie(request) var parsed: tuple[outcome: TileOutcome, req: TileRequest] var player: Option[Player] var allowed = false var redirect = "" withLock app.dbLock: let sc = app.scene # the one read of the request parsed = parseTileRequest(request.pathParams["scene"], request.pathParams["version"], request.pathParams["file"], sc) if parsed.outcome == toTileOk: if token.len > 0: player = sessionPlayer(app.db, sha256Hex(token)) if player.isSome: allowed = player.get.role == prGm if not allowed and app.visions.hasKey(player.get.id): allowed = tileCoveredByExplored(sc, app.visions[player.get.id].explored, parsed.req.x, parsed.req.y) if allowed: redirect = tilePath(sc, parsed.req.x, parsed.req.y) if parsed.outcome != toTileOk: request.respond(404, body = "") return if player.isNone or not allowed: request.respond(403, body = "") return var headers: HttpHeaders headers["X-Accel-Redirect"] = redirect headers["Cache-Control"] = "private" request.respond(200, headers) proc wsUpgrade(request: Request) {.gcsafe.} = ## GET /ws: Origin, session, proto, total cap, then the upgrade (DESIGN 6.5 rows 1-5). if request.headers["Origin"] != app.cfg.publicOrigin: request.respond(403, body = "") return let token = sessionCookie(request) if token.len == 0: request.respond(401, body = "") return var player: Option[Player] withLock app.dbLock: player = sessionPlayer(app.db, sha256Hex(token)) if player.isNone: request.respond(401, body = "") return let proto = protoQuery(request) if proto < 0: request.respond(400, body = "") return if not app.conns.reserve(): var headers: HttpHeaders headers["Retry-After"] = "5" app.lg.log(lvInfo, "conn_refused_total", [("player", $player.get.id)]) request.respond(503, headers, body = "") return var ws: WebSocket try: ws = request.upgradeToWebSocket() except MummyError: app.conns.cancelReserve() request.respond(400, body = "") return if proto != ProtoVersion: # Row 5: a browser cannot read an HTTP status from a WebSocket, so the upgrade completes and # the reason arrives as a `closing` message; no `hello`, no state (FIXED #18). app.conns.cancelReserve() ws.send($closingFrame(ReasonProtoMismatch, CloseProtoMismatch, 1)) ws.close() app.lg.log(lvInfo, "conn_refused_proto", [("player", $player.get.id), ("proto", $proto)]) return let pid = player.get.id let role = player.get.role let named = player.get.name.isSome let playerRec = player.get var activated: Activation # The activation, `hello` and the 6.3 resync run under the global lock: a mutation must not slip # in between the registry entry and `hello` (which would put a state frame before the first frame, # 6.1) nor between `hello` and the resync (the resync's `known` table is the diff base). withLock app.dbLock: activated = app.conns.activate(pid, role, ws, named) # Close the replacement race: a key.replace between the lookup and the activation must not # leave a live connection on a revoked session. if sessionPlayer(app.db, sha256Hex(token)).isNone: if app.conns.connById(activated.id).isSome: closeRegistered(app.conns.connById(activated.id).get, ReasonRevoked, CloseRevoked) return if activated.evicted.isSome: let doomed = activated.evicted.get closeGone(doomed, ReasonEvicted, CloseEvicted) app.lg.log(lvInfo, "conn_evicted", [("player", $pid), ("evicted_conn", $doomed.id)]) app.lg.log(lvInfo, "conn_open", [("player", $pid), ("role", $role), ("conn", $activated.id), ("total", $app.conns.activeCount)]) # `hello` is the first frame on the connection (n = 1). An unnamed player gets `proto, role, me` # and nothing else; a named player and the GM get the scene block (6.1: no counts, no wall data, # no owned ids; `mine` travels on `token`, `roster` carries the player list). sendHello(activated.id, playerRec) # One Ping right away, then one every PingIntervalMs: the browser answers without JS (4.3). ws.send($nextPingSeq(), Ping) # The 6.3 order: `roster`, walls (GM), characters, encountered, then vision/explored and the # tokens. Players never receive wall data (3.1, T2); `resync` refreshes the player's sight. resync(activated.id, named, playerRec) # --------------------------------------------------------------------------------------------------- # Intent pipeline (DESIGN 6.5). Order: parse, rate limit, unknown type, unnamed player, role, # fields, lookup, semantics. Every readable intent gets exactly one `ack`; an unreadable frame gets # exactly one `error`. proc dispatch(conn: Conn, env: Envelope) {.gcsafe.} = if not isCatalogueIntent(env.t): ackErr(conn, env.reqId, CodeUnknownType) return if not conn.named and conn.role != prGm and env.t notin ["conn.ping", "player.setname"]: # An unnamed player may only ping and set their name (DESIGN 6.1 Roles). ackErr(conn, env.reqId, CodeNotAllowed) return if conn.role != prGm and isGmOnlyIntent(env.t): ackErr(conn, env.reqId, CodeNotAllowed) return case env.t of "conn.ping": let ts = env.node{"ts"} if ts.isNil or ts.kind != JInt: ackErr(conn, env.reqId, CodeInvalid) return ackOk(conn, env.reqId, %*{"ts": ts.getInt}) return of "act.do": # Reserved for the FFF hook (DESIGN 9): always refused, never ok. Its fields are not validated # in M3 because the answer is the same for every readable envelope; the hook's field schema is # part of the FFF work (9). ackErr(conn, env.reqId, CodeNoRules) return of "player.setname": # 6.1: a player fills their own name once. Their `hello` (with `me.name`), a full resync of every # connection of that player, and a `roster` to everyone follow (6.3, 3.1 Q9). if conn.role == prGm: ackErr(conn, env.reqId, CodeNotAllowed) # the GM's name is set by the CLI, not the wire return var raw: string if not stringField(env, "name", raw): ackErr(conn, env.reqId, CodeInvalid) return let name = normalizedPlayerName(raw) if not validPlayerName(name): ackErr(conn, env.reqId, CodeInvalid) return var outcome = snOk withLock app.dbLock: let current = playerById(app.db, conn.playerId) if current.isNone: outcome = snNotAllowed elif current.get.name.isSome: outcome = snNotAllowed # 6.1: only while own name is null elif nameTaken(app.db, name): outcome = snTaken elif setName(app.db, conn.playerId, name): let named = playerById(app.db, conn.playerId) outcome = snOk app.conns.markNamed(conn.playerId) # 6.1: the name is durable here; the ack is enqueued first, then every connection of that # player gets `hello` with `me.name` set and the full resync (6.3), then `roster` to all. settleSetNameLocked(conn, env.reqId, named.get) else: outcome = snNotAllowed if outcome == snTaken: ackErr(conn, env.reqId, CodeNameTaken) return if outcome != snOk: ackErr(conn, env.reqId, CodeNotAllowed) return app.lg.log(lvInfo, "player_setname", [("player", $conn.playerId)]) return of "player.rename": # 6.1 (G): a named or unnamed player takes a new name; `roster` to all (3.1 Q9). var id = 0 if not intField(env, "id", id): ackErr(conn, env.reqId, CodeInvalid) return var raw: string if not stringField(env, "name", raw): ackErr(conn, env.reqId, CodeInvalid) return let name = normalizedPlayerName(raw) if not validPlayerName(name): ackErr(conn, env.reqId, CodeInvalid) return var outcome = rnOk withLock app.dbLock: if playerById(app.db, id).isNone: outcome = rnNotFound elif nameTaken(app.db, name, exceptId = id): outcome = rnTaken elif not renamePlayer(app.db, id, name): outcome = rnNotFound if outcome == rnNotFound: ackErr(conn, env.reqId, CodeNotFound) return if outcome == rnTaken: ackErr(conn, env.reqId, CodeNameTaken) return app.lg.log(lvInfo, "player_rename", [("player", $id)]) settle(conn, env.reqId, roster = true) return of "key.show": # 6.1 (G): re-show a player key (Q11 FIXED: keys are stored plaintext so they can be re-shown). var id = 0 if not intField(env, "id", id): ackErr(conn, env.reqId, CodeInvalid) return var key: Option[string] var gmKey = false withLock app.dbLock: let target = playerById(app.db, id) if target.isNone: key = none(string) elif target.get.role == prGm: gmKey = true # the GM's key is CLI-only (3.2) else: key = keyOf(app.db, id) if gmKey: ackErr(conn, env.reqId, CodeNotAllowed) return if key.isNone: ackErr(conn, env.reqId, CodeNotFound) return ackOk(conn, env.reqId, %*{"key": key.get}) return of "key.create": var created: tuple[id: int, key: string] var capped = false withLock app.dbLock: capped = playerCount(app.db) >= MaxPlayers if not capped: created = createPlayerWithKey(app.db) if capped: ackErr(conn, env.reqId, CodeCapReached) return app.lg.addSecret(created.key) app.lg.log(lvInfo, "key_created", [("player", $created.id)]) withLock app.dbLock: ackOk(conn, env.reqId, %*{"id": created.id, "key": created.key}) sendRoster() # 6.1: the GM's roster gains the new (unnamed) entry return of "key.replace": let idNode = env.node{"id"} if idNode.isNil or idNode.kind != JInt: ackErr(conn, env.reqId, CodeInvalid) return let id = idNode.getInt var key: Option[string] var notFound = false var notAllowed = false withLock app.dbLock: let target = playerById(app.db, id) if target.isNone: notFound = true elif target.get.role == prGm: notAllowed = true # the GM's own key rotates only through the CLI (DESIGN 3.2) else: key = replacePlayerKey(app.db, id) if notFound: ackErr(conn, env.reqId, CodeNotFound) return if notAllowed: ackErr(conn, env.reqId, CodeNotAllowed) return if key.isNone: ackErr(conn, env.reqId, CodeNotFound) return let closed = app.conns.revokePlayer(id) for doomed in closed: closeGone(doomed, ReasonRevoked, CloseRevoked) app.lg.addSecret(key.get) app.lg.log(lvInfo, "key_replaced", [("player", $id), ("conns_closed", $closed.len)]) withLock app.dbLock: ackOk(conn, env.reqId, %*{"key": key.get}) sendRoster() # 6.1: `connected` flags change return of "player.remove": let idNode = env.node{"id"} if idNode.isNil or idNode.kind != JInt: ackErr(conn, env.reqId, CodeInvalid) return let id = idNode.getInt var removed = false var notFound = false var notAllowed = false withLock app.dbLock: let target = playerById(app.db, id) if target.isNone: notFound = true elif target.get.role == prGm: notAllowed = true else: # DESIGN 3.2: that player's characters pass to the GM before the DELETE, because # `character.owner_player_id` refuses to dangle (no cascade on purpose); their reveal rows # and encountered list go with them through the FK cascade (6.1). A server without a GM row # cannot have players (key.create needs the GM role), so the guard is belt and braces. if app.gmPlayerId > 0: app.db.withTransaction: characters.transferToGm(app.db, id, app.gmPlayerId) removed = removePlayer(app.db, id) else: removed = removePlayer(app.db, id) if notFound: ackErr(conn, env.reqId, CodeNotFound) return if notAllowed: ackErr(conn, env.reqId, CodeNotAllowed) return if not removed: ackErr(conn, env.reqId, CodeNotFound) return let closed = app.conns.revokePlayer(id) for doomed in closed: closeGone(doomed, ReasonRevoked, CloseRevoked) # DESIGN 3.2: that player's controlled tokens pass to the GM. The FK's ON DELETE SET NULL did # the row; memory (and the `controller: null` the GM sees) follows here. Every in-memory table # that holds refcounted strings is touched only under the lock (ANALYSIS 4.1). withLock app.dbLock: for t in app.tokens.mitems: if t.owner == id: t.owner = GmControlled for c in app.characters.mitems: if c.owner == id: c.owner = app.gmPlayerId app.visions.del id app.reveals.withoutRevealsOf(id) app.encountered.del id app.lg.log(lvInfo, "player_removed", [("player", $id), ("conns_closed", $closed.len)]) settle(conn, env.reqId, roster = true) return of "token.create": if not sceneOk(conn, env): return var kind, dname, aname: string if not stringField(env, "kind", kind) or not validKind(kind): ackErr(conn, env.reqId, CodeInvalid) return let pos = parseVec(fieldOrNull(env.node, "pos")) if pos.isNone: ackErr(conn, env.reqId, CodeInvalid) return # 6.1: a plain token carries its own two names; a token linked to a character carries none (the # character has them). Both or neither, so a GM's field is never silently dropped. var characterId: Option[string] let charNode = fieldOrNull(env.node, "character_id") if not charNode.isNil: if charNode.kind != JString: ackErr(conn, env.reqId, CodeInvalid) return characterId = some(charNode.getStr) if characterId.isNone: if not stringField(env, "descriptive_name", dname) or not validName(dname): ackErr(conn, env.reqId, CodeInvalid) return if not stringField(env, "actual_name", aname) or not validName(aname): ackErr(conn, env.reqId, CodeInvalid) return elif present(env, "descriptive_name") or present(env, "actual_name"): ackErr(conn, env.reqId, CodeInvalid) return var gmOnly = false if present(env, "gm_only") and not boolField(env, "gm_only", gmOnly): ackErr(conn, env.reqId, CodeInvalid) return let flags = parseFlags(fieldOrNull(env.node, "flags")) if flags.isNone: ackErr(conn, env.reqId, CodeInvalid) return let vr = parseVisionRadius(fieldOrNull(env.node, "vision_radius")) if vr.isNone: ackErr(conn, env.reqId, CodeInvalid) return let radius = parseRadius(fieldOrNull(env.node, "radius")) # 5.6, #4 (slice 7) if radius.isNone: ackErr(conn, env.reqId, CodeInvalid) return let tokenProps = props.parseProps(app.registry, fieldOrNull(env.node, "props")) if tokenProps.isNone: ackErr(conn, env.reqId, CodeInvalid) return var tokenOutcome = toInvalid var createdId = "" var createdScene = 0 var controllerCheck = ccOk var characterMissing = false withLock app.dbLock: # Every intent value is detached here: `flags`, `props`, the two names, `kind` and the # `character_id` string must not share a node or a string payload with `env` (ANALYSIS 4.1). var candidate = TokenRec(kind: detachedString(kind), descriptiveName: detachedString(dname), actualName: detachedString(aname), pos: pos.get, gmOnly: gmOnly, flags: detachedJson(flags.get), visionRadius: vr.get, radius: radius.get, props: detachedProps(tokenProps.get), characterId: (if characterId.isSome: some(detachedString(characterId.get)) else: none(string))) if characterId.isSome: # 6.1: the default controller of a linked token is the character's owner; the GM's own id is # stored as GM-controlled like everywhere else. A missing character is `not-found`. let ch = characterById(app.characters, characterId.get) if ch.isNone: characterMissing = true else: candidate.owner = (if ch.get.owner == app.gmPlayerId: GmControlled else: ch.get.owner) # `controller` absent keeps the default (the character's owner for a linked token, the GM # otherwise); `null` is the GM and an integer is that player (6.1). if not characterMissing and env.node.hasKey("controller"): controllerCheck = resolveController(env.node{"controller"}, candidate.owner) if controllerCheck == ccOk and not characterMissing: # 5.5 SET: a GM placement ignores walls, but a position overlapping a blocking wall gives the # new token `stuck(walls)` right away. The rules compute it on a snapshot that already holds # the candidate as its last token, so the row is written once with its statuses. var mr = moveScene(app.scene, app.tokens & @[candidate]) moverules.placeToken(mr, app.tokens.len) candidate.statuses = wallsStatuses(candidate.statuses, mr.tokens[app.tokens.len]) let created = addToken(app.db, app.scene, candidate, app.tokens.mapIt(it.id)) tokenOutcome = created.outcome if created.outcome == toOk: app.tokens.add created.token refreshPlayer(created.token.owner) app.db.withTransaction: persistDerived(@[created.token.owner]) # The record copy (`created`, and the world's own) must die under this lock, and so must # the ack's `id`: settle inside the critical section, then carry only fresh scalars out. createdId = detachedString(created.token.id) createdScene = created.token.scene settleLocked(conn, env.reqId, %*{"id": created.token.id}) if characterMissing: ackErr(conn, env.reqId, CodeNotFound) # no such character return if controllerCheck == ccInvalid: ackErr(conn, env.reqId, CodeInvalid) return if controllerCheck == ccNotFound: ackErr(conn, env.reqId, CodeNotFound) # no such controller player return if tokenOutcome != toOk: ackErr(conn, env.reqId, CodeInvalid) return app.lg.log(lvInfo, "token_create", [("token", createdId), ("scene", $createdScene)]) return of "token.update": var id: string if not stringField(env, "id", id): ackErr(conn, env.reqId, CodeInvalid) return # 6.1: `character_id` is a string (link) or null (unlink); absent keeps the stored link. var characterDecl: Option[Option[string]] if declared(env, "character_id"): let raw = env.node{"character_id"} if raw.kind == JNull: characterDecl = some(none(string)) elif raw.kind == JString: characterDecl = some(some(raw.getStr)) else: ackErr(conn, env.reqId, CodeInvalid) return var patch: TokenPatch var anyField = false if present(env, "kind"): var kind: string if not stringField(env, "kind", kind) or not validKind(kind): ackErr(conn, env.reqId, CodeInvalid) return patch.kind = some(kind) anyField = true for field in ["descriptive_name", "actual_name"]: if not present(env, field): continue var name: string if not stringField(env, field, name) or not validName(name): ackErr(conn, env.reqId, CodeInvalid) return if field == "descriptive_name": patch.descriptiveName = some(name) else: patch.actualName = some(name) anyField = true if present(env, "gm_only"): var gmOnly: bool if not boolField(env, "gm_only", gmOnly): ackErr(conn, env.reqId, CodeInvalid) return patch.gmOnly = some(gmOnly) anyField = true if present(env, "flags"): let flags = parseFlags(env.node{"flags"}) if flags.isNone: ackErr(conn, env.reqId, CodeInvalid) return patch.flags = flags anyField = true if declared(env, "vision_radius"): let vr = parseVisionRadius(env.node{"vision_radius"}) if vr.isNone: ackErr(conn, env.reqId, CodeInvalid) return patch.visionRadius = vr anyField = true let controllerSeen = declared(env, "controller") if controllerSeen: # null (the GM) or an integer; anything else is a mistyped field (6.5 step 7) let raw = env.node{"controller"} if raw.kind notin {JInt, JNull}: ackErr(conn, env.reqId, CodeInvalid) return anyField = true if characterDecl.isSome: # 6.1: "links with names; unlinking without both names" is `invalid`. The names travel with # the link change because a plain token must always carry its own two names. if characterDecl.get.isSome: if patch.descriptiveName.isSome or patch.actualName.isSome: ackErr(conn, env.reqId, CodeInvalid) return elif patch.descriptiveName.isNone or patch.actualName.isNone: ackErr(conn, env.reqId, CodeInvalid) return patch.characterId = characterDecl anyField = true if not anyField: # `token.update` changes at least one field (6.1); a fieldless update is invalid (6.5 step 7). ackErr(conn, env.reqId, CodeInvalid) return var outcome = toNotFound var controllerCheck = ccOk var controller = GmControlled var characterMissing = false withLock app.dbLock: let current = tokenById(app.tokens, id) if current.isSome: if characterDecl.isSome and characterDecl.get.isSome and characterById(app.characters, characterDecl.get.get).isNone: characterMissing = true # 6.5 step 8: a missing GM target is `not-found` if controllerSeen and not characterMissing: controllerCheck = resolveController(env.node{"controller"}, controller) if controllerCheck == ccOk: patch.controller = some(controller) if controllerCheck == ccOk and not characterMissing: # Detach every patch field that is about to enter the world *here*, so the copies the # world keeps and the locals that carry them all die under this lock (ANALYSIS 4.1). var storedPatch = patch if patch.kind.isSome: storedPatch.kind = some(detachedString(patch.kind.get)) if patch.descriptiveName.isSome: storedPatch.descriptiveName = some(detachedString(patch.descriptiveName.get)) if patch.actualName.isSome: storedPatch.actualName = some(detachedString(patch.actualName.get)) if patch.characterId.isSome: storedPatch.characterId = if patch.characterId.get.isSome: some(some(detachedString(patch.characterId.get.get))) else: some(none(string)) if patch.flags.isSome: storedPatch.flags = some(detachedJson(patch.flags.get)) let candidate = patched(current.get, storedPatch) outcome = storeToken(app.db, app.scene, candidate) if outcome == toOk: let oldOwner = current.get.owner app.tokens[tokenIndex(app.tokens, id).get] = candidate refreshPlayer(oldOwner) refreshPlayer(candidate.owner) app.db.withTransaction: persistDerived(@[oldOwner, candidate.owner]) # A plain-token rename or a link change keeps every encountered snapshot of this token # in step with its subject - the descriptive name, the character link and the actual # name this player may know - in the DB and in memory at once (8; #29, #30). A linked # token's names reach the same helper through `character.update`. if current.get.characterId != candidate.characterId or current.get.descriptiveName != candidate.descriptiveName or current.get.actualName != candidate.actualName: discard rewriteEncountered(app.db, app.encountered, nsToken, id, subjectNamesOf(candidate, app.characters), app.reveals) if characterMissing: ackErr(conn, env.reqId, CodeNotFound) return if controllerCheck == ccInvalid: ackErr(conn, env.reqId, CodeInvalid) return if controllerCheck == ccNotFound: ackErr(conn, env.reqId, CodeNotFound) return if outcome == toNotFound: ackErr(conn, env.reqId, CodeNotFound) return if outcome != toOk: ackErr(conn, env.reqId, CodeInvalid) return app.lg.log(lvInfo, "token_update", [("token", id)]) settle(conn, env.reqId) return of "token.move": var id: string if not stringField(env, "id", id): ackErr(conn, env.reqId, CodeInvalid) return let dest = parseVec(fieldOrNull(env.node, "pos")) if dest.isNone: ackErr(conn, env.reqId, CodeInvalid) return var kind = mkError var resultPos: Vec withLock app.dbLock: let idx = tokenIndex(app.tokens, id) if idx.isNone: # T9: a player gets one code for "unknown" and "not yours" (no existence oracle); a GM's # missing target is not-found (6.5 step 8). Nothing is applied either way. kind = mkError elif conn.role != prGm and app.tokens[idx.get].owner != conn.playerId: kind = mkError else: var mr = moveScene(app.scene, app.tokens) let actor = if conn.role == prGm: Actor(role: roleGM, player: conn.playerId) else: Actor(role: rolePlayer, player: conn.playerId) let moved = moveToken(mr, actor, idx.get, dest.get) kind = moved.kind resultPos = moved.pos if kind == mkAck: # The rules already decided the walls-sourced statuses (`mkAck` may also clear them, for # a GM move to a free spot). Copy position + history + statuses, then persist them with # the explored chunks the move added (4.2 step 6): a position, a derived lock and a grid # are all NORMAL-durability data (Q12). var rec = app.tokens[idx.get] discard rec.applyOutcome(mr.tokens[idx.get]) app.tokens[idx.get] = rec refreshPlayer(app.tokens[idx.get].owner) app.db.withTransaction: faults.injectTxn() discard writePosition(app.db, app.tokens[idx.get]) writeStatuses(app.db, app.tokens[idx.get]) persistDerived(@[app.tokens[idx.get].owner]) case kind of mkError: ackErr(conn, env.reqId, if conn.role == prGm: CodeNotFound else: CodeNotAllowed) return of mkNack: # The uniform move refusal (5.5, T9): the old position and no code, one shape for locked, # over-cap and collision alike. let n = nextN(conn) if n > 0: conn.ws.send($nackMoveFrame(env.reqId, n, resultPos.x, resultPos.y)) return of mkAck: settle(conn, env.reqId, %*{"pos": [resultPos.x, resultPos.y]}) return of "token.remove": var id: string if not stringField(env, "id", id): ackErr(conn, env.reqId, CodeInvalid) return var removed = false withLock app.dbLock: let idx = tokenIndex(app.tokens, id) if idx.isSome: removed = removeToken(app.db, id) if removed: let owner = app.tokens[idx.get].owner app.tokens.delete idx.get refreshPlayer(owner) app.db.withTransaction: persistDerived(@[owner]) if not removed: ackErr(conn, env.reqId, CodeNotFound) return app.lg.log(lvInfo, "token_remove", [("token", id)]) settle(conn, env.reqId) return of "token.resize": # 5.6: `radius` is a positive number or null (= back to the scene default); the field itself is # required, so an absent `radius` is `invalid` (6.5 step 7). GM only (5.6: only the GM sets a size). var id: string if not stringField(env, "id", id): ackErr(conn, env.reqId, CodeInvalid) return if not env.node.hasKey("radius"): ackErr(conn, env.reqId, CodeInvalid) return let radius = parseRadius(env.node{"radius"}) if radius.isNone: ackErr(conn, env.reqId, CodeInvalid) return var outcome = toNotFound withLock app.dbLock: let idx = tokenIndex(app.tokens, id) if idx.isSome: var candidate = app.tokens[idx.get] candidate.radius = radius.get # The rules decide the position effect first (5.6: shrink never pushes, grow pushes or # squeezes), then one FULL transaction writes the size and the position together, so a # crash cannot leave a grown token sitting inside a wall with no status. var mr = moveScene(app.scene, app.tokens) let effect = moverules.resizeToken(mr, idx.get, effectiveRadius(app.scene, candidate)) var rec = candidate # The rules own the `walls` source: a grow push clears it, a failed grow sets `squeezed`, a # shrink clears it only when the overlap ended, and an overlap that stays keeps it as it was. rec.statuses = wallsStatuses(rec.statuses, mr.tokens[idx.get]) if effect == rkPushed: rec.pos = mr.tokens[idx.get].pos rec.prev = mr.tokens[idx.get].prev rec.hasPrev = mr.tokens[idx.get].hasPrev outcome = storeToken(app.db, app.scene, rec) if outcome == toOk: app.tokens[idx.get] = rec refreshPlayer(rec.owner) app.db.withTransaction: persistDerived(@[rec.owner]) if outcome == toNotFound: ackErr(conn, env.reqId, CodeNotFound) return if outcome != toOk: ackErr(conn, env.reqId, CodeInvalid) return app.lg.log(lvInfo, "token_resize", [("token", id), ("radius", if radius.get.isSome: $radius.get.get else: "default")]) settle(conn, env.reqId) return of "status.set": # 5.5: the GM sets `stuck` or `squeezed` by hand, source `GM`; adding an entry twice is a no-op. var id: string if not stringField(env, "id", id): ackErr(conn, env.reqId, CodeInvalid) return var rawStatus: string if not stringField(env, "status", rawStatus): ackErr(conn, env.reqId, CodeInvalid) return let kind = parseStatusKind(rawStatus) if kind.isNone: ackErr(conn, env.reqId, CodeInvalid) return var outcome = toNotFound withLock app.dbLock: let idx = tokenIndex(app.tokens, id) if idx.isSome: var rec = app.tokens[idx.get] rec.addStatus(kind.get, ssGM) outcome = storeToken(app.db, app.scene, rec) if outcome == toOk: app.tokens[idx.get] = rec if outcome == toNotFound: ackErr(conn, env.reqId, CodeNotFound) return if outcome != toOk: ackErr(conn, env.reqId, CodeInvalid) return app.lg.log(lvInfo, "status_set", [("token", id), ("status", $kind.get), ("source", $ssGM)]) settle(conn, env.reqId) return of "status.clear": # 5.5: removes exactly one (status, source) entry. `not-found` covers "no such token" and "no # such entry" alike (6.1). After clearing the `walls` source the player escape rule of 5.5 step 3 # applies unchanged: the token may step out without crossing, destination >= r from every wall. var id: string if not stringField(env, "id", id): ackErr(conn, env.reqId, CodeInvalid) return var rawStatus, rawSource: string if not stringField(env, "status", rawStatus): ackErr(conn, env.reqId, CodeInvalid) return if not stringField(env, "source", rawSource): ackErr(conn, env.reqId, CodeInvalid) return let kind = parseStatusKind(rawStatus) let source = parseStatusSource(rawSource) if kind.isNone or source.isNone: ackErr(conn, env.reqId, CodeInvalid) return var outcome = toNotFound withLock app.dbLock: let idx = tokenIndex(app.tokens, id) if idx.isSome and app.tokens[idx.get].hasStatus(kind.get, source.get): var rec = app.tokens[idx.get] discard rec.removeStatus(kind.get, source.get) outcome = storeToken(app.db, app.scene, rec) if outcome == toOk: app.tokens[idx.get] = rec if outcome == toNotFound: ackErr(conn, env.reqId, CodeNotFound) return if outcome != toOk: ackErr(conn, env.reqId, CodeInvalid) return app.lg.log(lvInfo, "status_clear", [("token", id), ("status", $kind.get), ("source", $source.get)]) settle(conn, env.reqId) return of "prop.set", "prop.unset": # 6.1 prop payload rules + server/props.nim caps. Slice 7 is GM-only (v1: owner-bucket writes by # players come with FFF actions, 9, which is already the role check of 6.5 step 6). `target` is # `token` or `character`; characters do not exist before slice 8 (#23), so a character target is # `not-found` - the honest answer for an id that names nothing. let setting = env.t == "prop.set" var target, id, bucketRaw, key: string if not stringField(env, "target", target): ackErr(conn, env.reqId, CodeInvalid) return if target notin ["token", "character"]: ackErr(conn, env.reqId, CodeInvalid) return if not stringField(env, "id", id): ackErr(conn, env.reqId, CodeInvalid) return if not stringField(env, "bucket", bucketRaw): ackErr(conn, env.reqId, CodeInvalid) return let bucket = props.parseBucket(bucketRaw) if bucket.isNone: ackErr(conn, env.reqId, CodeInvalid) return if not stringField(env, "key", key) or not props.validPropKey(key): ackErr(conn, env.reqId, CodeInvalid) return # The key and the value both enter the world (a props object key and a value node). Detach them # *inside* each critical section: the detached copies are then reachable from the world and must # die under the lock too (ANALYSIS 4.1). var value: JsonNode if setting: value = env.node{"value"} if value.isNil: ackErr(conn, env.reqId, CodeInvalid) return if value.kind == JNull or props.valueBytes(value) > props.MaxPropValueBytes: ackErr(conn, env.reqId, CodeInvalid) return if not app.registry.checkWrite(bucket.get, key, value): ackErr(conn, env.reqId, CodeInvalid) # the registry refuses this key, kind or bucket return if target == "character": # Same caps and registry as a token (6.1): the character holds identity and base values, the # token holds the state of the figure (8), and the wire intents are shared. var charOutcome = coNotFound var capped = false withLock app.dbLock: let storedKey = detachedString(key) let storedValue = if setting: detachedJson(value) else: nil let idx = characterIndex(app.characters, id) if idx.isSome: var rec = app.characters[idx.get] var p = props.clone(rec.props) if setting: if not p.setProp(bucket.get, storedKey, storedValue): capped = true else: rec.props = p else: discard p.unsetProp(bucket.get, storedKey) # unsetting an absent key is ok (6.1) rec.props = p if not capped: charOutcome = storeCharacter(app.db, rec) if charOutcome == coOk: app.characters[idx.get] = rec if capped: ackErr(conn, env.reqId, CodeInvalid) # 64 keys per bucket (6.1, #22) return if charOutcome == coNotFound: ackErr(conn, env.reqId, CodeNotFound) return if charOutcome != coOk: ackErr(conn, env.reqId, CodeInvalid) return app.lg.log(lvInfo, if setting: "prop_set" else: "prop_unset", [("character", id), ("bucket", $bucket.get)]) settle(conn, env.reqId) return var outcome = toNotFound var capped = false withLock app.dbLock: let storedKey = detachedString(key) let storedValue = if setting: detachedJson(value) else: nil let idx = tokenIndex(app.tokens, id) if idx.isSome: var rec = app.tokens[idx.get] var p = props.clone(rec.props) if setting: if not p.setProp(bucket.get, storedKey, storedValue): capped = true else: rec.props = p else: discard p.unsetProp(bucket.get, storedKey) # unsetting an absent key is ok (6.1) rec.props = p if not capped: outcome = storeToken(app.db, app.scene, rec) if outcome == toOk: app.tokens[idx.get] = rec if capped: ackErr(conn, env.reqId, CodeInvalid) # 64 keys per bucket (6.1, #22) return if outcome == toNotFound: ackErr(conn, env.reqId, CodeNotFound) return if outcome != toOk: ackErr(conn, env.reqId, CodeInvalid) return # The key is not logged: it is GM-authored text and the log stays free of player content. app.lg.log(lvInfo, if setting: "prop_set" else: "prop_unset", [("token", id), ("bucket", $bucket.get)]) settle(conn, env.reqId) return # --- characters, names, encountered (DESIGN 8, 6.1; slice 8 / #23) --------------------------- of "character.create": # 6.1 (G): both names, an optional owner (default the GM) and optional props. The id comes from # the shared token/character namespace, so a reveal subject is never ambiguous. var dname, aname: string if not stringField(env, "descriptive_name", dname) or not validCharacterName(dname): ackErr(conn, env.reqId, CodeInvalid) return if not stringField(env, "actual_name", aname) or not validCharacterName(aname): ackErr(conn, env.reqId, CodeInvalid) return var owner = app.gmPlayerId if present(env, "owner") and not intField(env, "owner", owner): ackErr(conn, env.reqId, CodeInvalid) return let charProps = props.parseProps(app.registry, fieldOrNull(env.node, "props")) if charProps.isNone: ackErr(conn, env.reqId, CodeInvalid) return var charOutcome = coInvalid var createdId = "" var createdOwner = 0 var ownerMissing = false withLock app.dbLock: if playerById(app.db, owner).isNone: ownerMissing = true else: let candidate = CharacterRec(owner: owner, descriptiveName: detachedString(dname), actualName: detachedString(aname), props: detachedProps(charProps.get)) let created = addCharacter(app.db, candidate, allIds()) charOutcome = created.outcome if created.outcome == coOk: app.characters.add created.character # Record copy and ack value die under the lock, as for `token.create`. createdId = detachedString(created.character.id) createdOwner = created.character.owner settleLocked(conn, env.reqId, %*{"id": created.character.id}) if ownerMissing: ackErr(conn, env.reqId, CodeNotFound) # 6.5 step 8: no such owner player return if charOutcome != coOk: ackErr(conn, env.reqId, CodeInvalid) return app.lg.log(lvInfo, "character_create", [("character", createdId), ("owner", $createdOwner)]) return of "character.update": # 6.1 (G): the two names only; props go through `prop.set`/`prop.unset`. var id: string if not stringField(env, "id", id): ackErr(conn, env.reqId, CodeInvalid) return var patch = CharacterRec() var anyField = false if present(env, "descriptive_name"): var name: string if not stringField(env, "descriptive_name", name) or not validCharacterName(name): ackErr(conn, env.reqId, CodeInvalid) return patch.descriptiveName = name anyField = true if present(env, "actual_name"): var name: string if not stringField(env, "actual_name", name) or not validCharacterName(name): ackErr(conn, env.reqId, CodeInvalid) return patch.actualName = name anyField = true if not anyField: ackErr(conn, env.reqId, CodeInvalid) return var outcome = coNotFound withLock app.dbLock: let idx = characterIndex(app.characters, id) if idx.isSome: var candidate = app.characters[idx.get] if present(env, "descriptive_name"): candidate.descriptiveName = detachedString(patch.descriptiveName) if present(env, "actual_name"): candidate.actualName = detachedString(patch.actualName) outcome = storeCharacter(app.db, candidate) if outcome == coOk: app.characters[idx.get] = candidate # 6.1: "encountered upserts for players who met it" - every snapshot of this character # follows the new names on the wire and in the DB at once (#30), with the actual name # set only for the players the name rule allows (8). discard rewriteEncountered(app.db, app.encountered, nsCharacter, id, subjectNamesOf(candidate), app.reveals) if outcome == coNotFound: ackErr(conn, env.reqId, CodeNotFound) return if outcome != coOk: ackErr(conn, env.reqId, CodeInvalid) return app.lg.log(lvInfo, "character_update", [("character", id)]) settle(conn, env.reqId) return of "character.remove": # 6.1 (G): `in-use` while a token still links the character (the GM removes or unlinks those # tokens first, 6.5). Reads physically cascade the reveal rows of the subject. var id: string if not stringField(env, "id", id): ackErr(conn, env.reqId, CodeInvalid) return var outcome = coNotFound withLock app.dbLock: let idx = characterIndex(app.characters, id) if idx.isSome: if tokensLinkedTo(app.tokens, id) > 0: outcome = coInUse elif removeCharacter(app.db, id): app.characters.delete idx.get # The reveal rows of a subject that no longer exists; a *token*'s rows are left alone # because a token id is never reused (8). app.db.withTransaction: deleteRevealsFor(app.db, id) outcome = coOk if outcome == coInUse: ackErr(conn, env.reqId, CodeInUse) return if outcome == coNotFound: ackErr(conn, env.reqId, CodeNotFound) return app.lg.log(lvInfo, "character_remove", [("character", id)]) settle(conn, env.reqId) return of "character.reassign": # 6.1 (G): the character changes hands; its tokens keep their controllers untouched (3.1, 8). var id: string if not stringField(env, "id", id): ackErr(conn, env.reqId, CodeInvalid) return var owner = 0 if not intField(env, "owner", owner): ackErr(conn, env.reqId, CodeInvalid) return var outcome = coNotFound var updatedOwner = 0 withLock app.dbLock: let idx = characterIndex(app.characters, id) if idx.isSome and playerById(app.db, owner).isSome: var candidate = app.characters[idx.get] candidate.owner = owner outcome = storeCharacter(app.db, candidate) if outcome == coOk: app.characters[idx.get] = candidate updatedOwner = candidate.owner # A reassignment changes who is told the actual name (8), so the snapshots of everyone # who met the character follow it on the wire and in the DB (#30). discard rewriteEncountered(app.db, app.encountered, nsCharacter, id, subjectNamesOf(candidate), app.reveals) if outcome == coNotFound: ackErr(conn, env.reqId, CodeNotFound) # no such character or owner return if outcome != coOk: ackErr(conn, env.reqId, CodeInvalid) return when defined(leakfault): if faultActive("controllerChange"): # Negative control for the CONTROLLER_CHANGE class (DESIGN 10.3): a character owner change # drags its tokens' controllers along, which 3.1/8 forbid. Compiled out of every shipped # binary, like the other faults. withLock app.dbLock: for i in 0 ..< app.tokens.len: if app.tokens[i].characterId == some(id): var rec = app.tokens[i] rec.owner = (if updatedOwner == app.gmPlayerId: GmControlled else: updatedOwner) if storeToken(app.db, app.scene, rec) == toOk: app.tokens[i] = rec app.lg.log(lvInfo, "character_reassign", [("character", id), ("owner", $updatedOwner)]) settle(conn, env.reqId) return of "name.reveal": # 6.1 (G): reveal one subject's actual name to one player. Never revoked (8): there is no # un-reveal intent in M3. var subjectRaw, id: string if not stringField(env, "subject", subjectRaw): ackErr(conn, env.reqId, CodeInvalid) return let subject = parseSubject(subjectRaw) if subject.isNone: ackErr(conn, env.reqId, CodeInvalid) return if not stringField(env, "id", id): ackErr(conn, env.reqId, CodeInvalid) return var player = 0 if not intField(env, "player", player): ackErr(conn, env.reqId, CodeInvalid) return var outcome = nrNotFound # One lock hold for the lookup, the reveal row and the snapshot rewrite (#27): a rename landing # between a lookup and the write would otherwise persist a name the subject no longer has. withLock app.dbLock: var names: SubjectNames # The reveal set stores the id it is given, so use the *world's* id string, not the intent's # payload: a local holding an intent string past the lock would be freed off-thread # (ANALYSIS 4.1). It lives and dies inside this block. var subjectId = "" if playerById(app.db, player).isNone: outcome = nrNotFound elif subject.get == nsCharacter: let ch = characterById(app.characters, id) if ch.isNone: outcome = nrNotFound else: subjectId = ch.get.id names = subjectNamesOf(ch.get) outcome = nrOk else: let tok = tokenById(app.tokens, id) if tok.isNone: outcome = nrNotFound elif tok.get.characterId.isSome: outcome = nrInvalid # reveal through the character (6.1) else: subjectId = tok.get.id names = subjectNamesOf(tok.get, app.characters) outcome = nrOk if outcome == nrOk: addReveal(app.db, player, subjectId) app.reveals.withReveal(player, subjectId) # 6.1: the player's encountered list learns the actual name too (the snapshot, not a view). # Scoped to this one player (#27): the row of every other player who met the subject is # untouched, which is what makes the live frame and the post-restart frame agree. discard rewriteEncountered(app.db, app.encountered, subject.get, subjectId, names, app.reveals, onlyPlayer = player) if outcome == nrInvalid: ackErr(conn, env.reqId, CodeInvalid) return if outcome == nrNotFound: ackErr(conn, env.reqId, CodeNotFound) return app.lg.log(lvInfo, "name_reveal", [("subject", subjectRaw), ("id", id), ("player", $player)]) settle(conn, env.reqId) return of "name.reveal_all": # 6.1 (G): set the subject's `reveal_all`; as `name.reveal` for every player, idempotent. var subjectRaw, id: string if not stringField(env, "subject", subjectRaw): ackErr(conn, env.reqId, CodeInvalid) return let subject = parseSubject(subjectRaw) if subject.isNone: ackErr(conn, env.reqId, CodeInvalid) return if not stringField(env, "id", id): ackErr(conn, env.reqId, CodeInvalid) return var outcome = coNotFound withLock app.dbLock: var names: SubjectNames # world-owned strings: must die under the lock (ANALYSIS 4.1) if subject.get == nsCharacter: let idx = characterIndex(app.characters, id) if idx.isSome: var candidate = app.characters[idx.get] candidate.revealAll = true outcome = storeCharacter(app.db, candidate) if outcome == coOk: app.characters[idx.get] = candidate names = subjectNamesOf(candidate) else: let idx = tokenIndex(app.tokens, id) if idx.isSome: var candidate = app.tokens[idx.get] candidate.revealAll = true # `reveal_all` on a plain token is the same flag a character carries, so it goes through # the token's own store; the two outcome enums differ only in name here. let stored = storeToken(app.db, app.scene, candidate) outcome = (if stored == toOk: coOk elif stored == toNotFound: coNotFound else: coInvalid) if outcome == coOk: app.tokens[idx.get] = candidate names = subjectNamesOf(candidate, app.characters) if outcome == coOk: # As `name.reveal` for every player who met the subject, live and persisted (#27, #30). discard rewriteEncountered(app.db, app.encountered, subject.get, id, names, app.reveals) if outcome == coNotFound: ackErr(conn, env.reqId, CodeNotFound) return if outcome != coOk: ackErr(conn, env.reqId, CodeInvalid) return app.lg.log(lvInfo, "name_reveal_all", [("subject", subjectRaw), ("id", id)]) settle(conn, env.reqId) return of "encountered.remove": # 6.1 (G): the only way an entry leaves a player's list (8). The token itself is untouched. var player = 0 if not intField(env, "player", player): ackErr(conn, env.reqId, CodeInvalid) return var id: string if not stringField(env, "id", id): ackErr(conn, env.reqId, CodeInvalid) return var removed = false withLock app.dbLock: if playerById(app.db, player).isSome: removed = deleteEncountered(app.db, player, id) if removed: app.encountered[player].del id if not removed: ackErr(conn, env.reqId, CodeNotFound) # no such player, or no such entry return app.lg.log(lvInfo, "encountered_remove", [("player", $player), ("token", id)]) settle(conn, env.reqId) return of "scene.set": # DESIGN 6.1, slice 10 / #25: a hello-equivalent reset of every connection (the client resets on # `hello`, 6.1) after a GM edit of the settable scene fields. `w`, `h`, `tile_size`, `cell` and # `art_version` are not patch fields (import is the M6 CLI) and are ignored as unknown fields # (6.2); a patch carrying only those has no field and is `invalid`. if not sceneOk(conn, env): return var patchOpt = parseScenePatch(env.node) if patchOpt.isNone: if not env.node.isNil and env.node.hasKey("extra"): opaqueRefused("extra", env.node{"extra"}) ackErr(conn, env.reqId, CodeInvalid) return var patch = patchOpt.get var changed: seq[string] if patch.name.isSome: changed.add "name" if patch.gridSize.isSome: changed.add "grid_size" if patch.visionRadiusDefault.isSome: changed.add "vision_radius_default" if patch.tokenRadiusDefault.isSome: changed.add "token_radius_default" if patch.extra.isSome: changed.add "extra" var candidateId = 0 var resizedCount = 0 withLock app.dbLock: # The base record is read under the lock (#31): `scene.set` must not patch a record that a # concurrent `scene.set` is replacing, and every comparison below is against this same base. # `name` and `extra` are stored verbatim, so detach them here; `candidate`, `storedPatch` and # `tokenChanges` hold world refs and all die inside this block (ANALYSIS 4.1). var storedPatch = patch if patch.name.isSome: storedPatch.name = some(detachedString(patch.name.get)) if patch.extra.isSome: storedPatch.extra = some(detachedJson(patch.extra.get)) let candidate = app.scene.patched(storedPatch) var tokenChanges: seq[(int, TokenRec)] # 5.6 `token_radius_default`: every token that uses the default changes effective size; a grow # pushes (or squeezes), a shrink clears the `walls` entries only when the overlap ends. The # rules run on a snapshot with the OLD radii (the candidate default is not in `app.scene` yet), # then one FULL transaction writes the scene row and every token it resized. if candidate.tokenRadiusDefault != app.scene.tokenRadiusDefault: var mr = moveScene(app.scene, app.tokens) for i, t in app.tokens: if t.radius.isSome: continue # an own radius is not the default (#4) discard moverules.resizeToken(mr, i, candidate.tokenRadiusDefault) var rec = app.tokens[i] let outcome = rec.applyOutcome(mr.tokens[i]) if outcome.moved or outcome.statuses: tokenChanges.add (i, rec) app.db.exec(sql"PRAGMA synchronous=FULL") try: app.db.withTransaction: writeSceneRow(app.db, candidate) for (_, rec) in tokenChanges: discard writePosition(app.db, rec) writeStatuses(app.db, rec) finally: app.db.exec(sql"PRAGMA synchronous=NORMAL") app.scene = candidate for (i, rec) in tokenChanges: app.tokens[i] = rec refreshAll() persistAllDerived() recordEncounters() ackOk(conn, env.reqId) resyncEveryone() candidateId = candidate.id resizedCount = tokenChanges.len app.lg.log(lvInfo, "scene_set", [("scene", $candidateId), ("fields", changed.join(",")), ("tokens_resized", $resizedCount)]) return of "wall.add": if not sceneOk(conn, env): return # One parser for add and update. A raw-setting create starts from the `wall` defaults; a preset # replaces the setting set. Both go through the same expand-and-validate path (DESIGN 6.1, # #55); `a` and `b` are the only required fields here. var patch: WallPatch if not parseWallPatch(env, patch, allowOpen = true): if present(env, "flags"): opaqueRefused("flags", env.node{"flags"}) ackErr(conn, env.reqId, CodeInvalid) return if patch.a.isNone or patch.b.isNone: ackErr(conn, env.reqId, CodeInvalid) return let resolved = patched(defaultWall(patch.a.get, patch.b.get), patch) if resolved.isNone: ackErr(conn, env.reqId, CodeInvalid) return var candidate = resolved.get # `label` is the intent's string: copy it at the boundary so the stored wall shares no payload # with the request (ANALYSIS 4.1, jsonbound). if candidate.label.isSome: candidate.label = some(detachedString(candidate.label.get)) var addedId = 0 var addedKind = "" var sceneId = 0 var ok = false withLock app.dbLock: sceneId = app.scene.id # the request's one read (#31) # The record is copied here so its `flags` object and the record copy both die under the # lock; `detachedJson` keeps the stored object independent of `env` (ANALYSIS 4.1). var stored = candidate stored.flags = detachedJson(candidate.flags) # 5.5 SET: the new wall sticks every token its circle overlaps. The rules run on a snapshot # taken before the write (the id is assigned by the write), and their outcome is applied only # after it committed, so a failed write leaves every token untouched. var mr = moveScene(app.scene, app.tokens) let id = addWall(app.db, app.scene, stored) if id.isSome: let added = wallById(app.scene, id.get) discard moverules.addWall(mr, ruleWall(added.get)) discard applyRuleOutcome(mr) refreshAll() # 4.2 step 5: a wall change moves every player's sight persistAllDerived() # step 6: the chunks the new wall revealed, before the ack addedId = added.get.id addedKind = derivedKind(added.get) # The wall frame references `added.flags`; build it and fan it out here, before the record # copy leaves scope, never after the lock is released (ANALYSIS 4.1). settleWorldLocked(conn, env.reqId, wallFrame(sceneId, wallObjectOf(added.get)), %*{"id": added.get.id}) ok = true if not ok: ackErr(conn, env.reqId, CodeInvalid) # degenerate or out-of-bounds geometry return app.lg.log(lvInfo, "wall_add", [("scene", $sceneId), ("wall", $addedId), ("kind", addedKind)]) return of "wall.update": if not sceneOk(conn, env): return var id = 0 if not intField(env, "id", id): ackErr(conn, env.reqId, CodeInvalid) return var patch: WallPatch if not parseWallPatch(env, patch): if present(env, "flags"): opaqueRefused("flags", env.node{"flags"}) ackErr(conn, env.reqId, CodeInvalid) return if not wallPatchHasField(patch): # A fieldless update (or one naming only the ignored `open`/`kind`) is `invalid`, before the # target lookup (6.1, 6.5 steps 7 then 8). ackErr(conn, env.reqId, CodeInvalid) return var outcome = waNotFound var updatedKind = "" var sceneId = 0 var ok = false withLock app.dbLock: sceneId = app.scene.id # the request's one read (#31) # The label string and flags object go into the wall record verbatim: detach them here so # both the record and this local die under the lock (ANALYSIS 4.1). var storedPatch = patch if patch.label.isSome: storedPatch.label = some(detachedString(patch.label.get)) if patch.flags.isSome: storedPatch.flags = some(detachedJson(patch.flags.get)) let current = wallById(app.scene, id) if current.isSome: # `wall.update` = remove then add for the status rules (5.5): the rules run on the snapshot # with the patched wall at the same index, so a move away clears and a move onto a token sticks. let idx = wallIndex(app.scene, id).get let candidate = patched(current.get, storedPatch) if candidate.isNone: outcome = waInvalid # an impossible resulting switch set (5.8) else: var mr = moveScene(app.scene, app.tokens) outcome = updateWall(app.db, app.scene, candidate.get) if outcome == waOk: when defined(leakfault): # LEAK_FAULT=markerCrash (TESTING 10.3, #60): die between the wall commit and the # derived-memory transaction, to prove the marker deletes commit with the wall row. if faultActive("markerCrash"): crashNow() let updated = wallById(app.scene, id) discard moverules.updateWall(mr, idx, ruleWall(updated.get)) discard applyRuleOutcome(mr) refreshAll() persistAllDerived() updatedKind = derivedKind(updated.get) # Frame and record copy both live and die inside this lock (ANALYSIS 4.1). settleWorldLocked(conn, env.reqId, wallFrame(sceneId, wallObjectOf(updated.get))) ok = true if outcome == waNotFound: ackErr(conn, env.reqId, CodeNotFound) return if outcome != waOk or not ok: ackErr(conn, env.reqId, CodeInvalid) return app.lg.log(lvInfo, "wall_update", [("scene", $sceneId), ("wall", $id), ("kind", updatedKind)]) return of "wall.remove": if not sceneOk(conn, env): return var id = 0 if not intField(env, "id", id): ackErr(conn, env.reqId, CodeInvalid) return var outcome = waNotFound var sceneId = 0 withLock app.dbLock: sceneId = app.scene.id # the request's one read (#31) let idx = wallIndex(app.scene, id) if idx.isSome: # 5.5 KEEP/CLEAR: a removal frees only the tokens that no longer overlap any blocking wall. var mr = moveScene(app.scene, app.tokens) outcome = removeWall(app.db, app.scene, id) if outcome == waOk: discard moverules.removeWall(mr, idx.get) discard applyRuleOutcome(mr) refreshAll() persistAllDerived() if outcome == waNotFound: ackErr(conn, env.reqId, CodeNotFound) return app.lg.log(lvInfo, "wall_remove", [("scene", $sceneId), ("wall", $id)]) withLock app.dbLock: settleWorldLocked(conn, env.reqId, wallGoneFrame(sceneId, id)) return of "door.set": if not sceneOk(conn, env): return var id = 0 if not intField(env, "id", id): ackErr(conn, env.reqId, CodeInvalid) return let openNode = env.node{"open"} if openNode.isNil or openNode.kind != JBool: ackErr(conn, env.reqId, CodeInvalid) return let open = openNode.getBool var outcome = waNotFound var sceneId = 0 var ok = false withLock app.dbLock: sceneId = app.scene.id # the request's one read (#31) # 5.5: closing pushes overlapped tokens aside and squeezes the ones with no valid side; # opening re-evaluates the walls-sourced entries (KEEP while another wall still overlaps). # The rules run on a snapshot taken before the write; their positions and statuses are applied # only after it committed. let idx = wallIndex(app.scene, id) var mr = moveScene(app.scene, app.tokens) outcome = setDoor(app.db, app.scene, id, open) if outcome == waOk: let updated = wallById(app.scene, id) if idx.isSome: discard moverules.setDoor(mr, idx.get, open) discard applyRuleOutcome(mr) refreshAll() persistAllDerived() # Frame and record copy both live and die inside this lock (ANALYSIS 4.1). settleWorldLocked(conn, env.reqId, wallFrame(sceneId, wallObjectOf(updated.get))) ok = true if outcome == waNotFound: ackErr(conn, env.reqId, CodeNotFound) return if outcome != waOk or not ok: ackErr(conn, env.reqId, CodeInvalid) # waNotDoor: a plain wall has no open state return app.lg.log(lvInfo, "door_set", [("scene", $sceneId), ("wall", $id), ("open", $open)]) return else: # A catalogue intent whose slice has not landed yet (#21-#25). It still gets its one ack, with # a static code and no state; `unknown-type` is the honest answer until the handler exists # (DESIGN 6.1, slice-3 note). ackErr(conn, env.reqId, CodeUnknownType) proc malformedFrame(conn: Conn, nowMs: int64) {.gcsafe.} = ## DESIGN 6.5 step 2 / row 8: one `error malformed`, and the tenth inside 10 s closes with 1008. if app.conns.recordMalformed(conn.id, nowMs): closeRegistered(conn, ReasonMalformedFlood, CloseMalformedFlood) app.lg.log(lvWarn, "conn_malformed_flood", [("player", $conn.playerId), ("conn", $conn.id)]) else: sendError(conn, CodeMalformed) proc handleText(conn: Conn, text: string) {.gcsafe.} = ## DESIGN 6.5 steps 2 and 3: the bucket is spent by every inbound frame, readable or not. let nowMs = monotonicMs() let allowed = app.conns.takeIntentToken(conn.id, nowMs) let env = parseEnvelope(text) if not allowed: if env.ok: ackErr(conn, env.reqId, CodeRateLimited) else: sendError(conn, CodeRateLimited) return if not env.ok: malformedFrame(conn, nowMs) return # #32: one guard covers the whole handling of a readable envelope, so an escaping handler failure # is still exactly one ack. A failure after the handler's own ack is not answered twice; anything # else gets the static `internal` refusal. The transaction helpers roll back on every unwind path, # including `Defect`, before this runs. ackedReqId = -1 try: dispatch(conn, env) except Exception as e: if ackedReqId != env.reqId: ackErr(conn, env.reqId, CodeInternal) app.lg.log(lvError, "intent_failed", [("intent", env.t), ("reqId", $env.reqId), ("class", $e.name), ("message", "unhandled")]) proc websocketEvent(ws: WebSocket, event: WebSocketEvent, message: Message) {.gcsafe.} = case event of MessageEvent: let found = app.conns.connForWs(ws) if found.isNone: return let conn = found.get case message.kind of TextMessage: handleText(conn, message.data) of BinaryMessage: # DESIGN 6: a binary frame counts as malformed. malformedFrame(conn, monotonicMs()) of Ping: # mummy does not answer client Pings itself; RFC 6455 requires a Pong with the same payload. ws.send(message.data, Pong) of Pong: var seqNo: int64 try: seqNo = int64(parseInt(message.data)) except ValueError: seqNo = -1 app.conns.notePong(conn.id, seqNo, monotonicMs()) of CloseEvent, ErrorEvent: let found = app.conns.connForWs(ws) if found.isSome: app.conns.remove(found.get.id) app.lg.log(lvDebug, "conn_close", [("player", $found.get.playerId), ("conn", $found.get.id)]) else: discard # --------------------------------------------------------------------------------------------------- # Heartbeat: a Ping every PingIntervalMs on every connection. Lag measurement and the stop-feeding # rule are M5 (4.3); here the seq is only recorded when the Pong comes back. proc heartbeat() {.thread.} = while true: sleep(PingIntervalMs) if appHandle == nil: continue # no App yet: nothing to ping let payload = $nextPingSeq() for conn in app().conns.snapshot(): conn.ws.send(payload, Ping) # --------------------------------------------------------------------------------------------------- # Startup and CLI proc buildRouter(): Router = result.get("/healthz", healthz) result.post("/join", join) result.get("/tiles/@scene/@version/@file", tileGate) result.get("/ws", wsUpgrade) proc cliUsage(): string = """fff-vtt - server-authoritative vision VTT Usage: fff-vtt [options] fff-vtt gm-key [--new] [options] Options: --public-origin= Browser origin the site is served from (default: http://localhost:8080). Env: FFF_VTT_PUBLIC_ORIGIN --port= Listen port, 1..65535 (default: 9000). Env: FFF_VTT_PORT --state-dir= Directory holding state.db (default: run). Env: FFF_VTT_STATE_DIR -h, --help Print this help and exit. Commands: gm-key Create the single GM if needed and print the GM key (same key on re-run). gm-key --new Rotate the GM key and revoke all GM sessions. Refused while the server holds the state-dir lock (stop the server first). The bind address is fixed at 127.0.0.1 and is not a key: put nginx (or another TLS proxy) in front. """ proc mummyLog(level: LogLevel, args: varargs[string]) {.gcsafe.} = ## mummy's own lines (dropped oversize frame, bad frame) go through the event log, so nothing ## writes to stdout behind the logger's back (DESIGN 11.3). Details ride at debug level. if appHandle == nil: return var text = "" for arg in args: text.add arg app().lg.log(if level == ErrorLevel: lvWarn else: lvDebug, "mummy", [("msg", text)]) proc runGmKey(rawArgs: seq[string]): int = var rotate = false var cfgArgs: seq[string] for arg in rawArgs: if arg == "--new": rotate = true else: cfgArgs.add arg var cfg: Config try: cfg = parseConfig(cfgArgs) except ConfigError as e: stderr.writeLine "fff-vtt gm-key: " & e.msg return 2 if cfg.help: stdout.write cliUsage() return 0 try: createDir(cfg.stateDir) except CatchableError as e: stderr.writeLine "fff-vtt gm-key: cannot create " & cfg.stateDir & ": " & e.msg return 1 var lock: InstanceLock if rotate: lock = tryAcquire(cfg.stateDir) if not lock.held: stderr.writeLine "fff-vtt gm-key --new: the server is running on " & cfg.stateDir & " (state-dir lock held); stop it first" return 3 var conn: DbConn try: conn = openDatabase(cfg.dbPath) except CatchableError as e: stderr.writeLine "fff-vtt gm-key: cannot open " & cfg.dbPath & ": " & e.msg return 1 defer: close(conn) try: discard migrate(conn) let created = ensureGm(conn, rotate) if created.rotated: stdout.writeLine "GM key (new): " & created.key else: stdout.writeLine "GM key: " & created.key stdout.flushFile() except CatchableError as e: stderr.writeLine "fff-vtt gm-key: " & e.msg return 1 0 proc readRedactionSecrets(db: DbConn, lg: Logger) = ## The safety net behind "never log keys": register every stored key for redaction. for row in db.getAllRows(sql"SELECT secret FROM player_key"): if row.len > 0 and row[0].len >= MinSecretLen: try: lg.addSecret(row[0]) except ValueError: discard proc runServer(cfg: Config): int = let lg = newLogger() lg.log(lvInfo, "server_start", [("origin", cfg.publicOrigin), ("state_dir", cfg.stateDir), ("bind", BindAddress)]) try: createDir(cfg.stateDir) except CatchableError as e: lg.log(lvError, "state_dir_failed", [("path", cfg.stateDir), ("error", e.msg)]) return 1 var instanceLock = tryAcquire(cfg.stateDir) if not instanceLock.held: lg.log(lvError, "state_dir_locked", [("path", cfg.stateDir)]) return 1 var conn: DbConn try: conn = openDatabase(cfg.dbPath) except CatchableError as e: lg.log(lvError, "db_open_failed", [("path", cfg.dbPath), ("error", e.msg)]) return 1 let applied = try: migrate(conn) except CatchableError as e: lg.log(lvError, "db_migrate_failed", [("path", cfg.dbPath), ("error", e.msg)]) return 1 lg.log(lvInfo, "db_ready", [("path", cfg.dbPath), ("schema_version", $schemaVersion(conn)), ("applied", $applied)]) let state = App(cfg: cfg, lg: lg, db: conn, conns: newConns(), instanceLock: instanceLock, registry: props.defaultRegistry()) initLock(state.dbLock) readRedactionSecrets(conn, lg) # DESIGN 4.1/4.4: load everything into memory once; migration 3 seeds the single v1 scene. let loaded = loadScene(conn) if loaded.isNone: lg.log(lvError, "scene_missing", [("path", cfg.dbPath), ("scene", $DefaultSceneId)]) return 1 state.scene = loaded.get state.tokens = loadTokens(conn, state.scene.id) # 8 / slice 8: the characters, the per-player reveals and the encountered snapshots. state.characters = characters.loadCharacters(conn) state.reveals = characters.loadReveals(conn) state.encountered = characters.loadEncountered(conn) # 4.4 startup / slice 6: the players' explored grids come back from their chunk rows. Polygons are # never stored; the sight state is rebuilt from the loaded walls on the player's first refresh. state.visions = explored.restore(conn, state.scene) # 5.8 (#59): the per-player marker memory comes back with the explored state, before the first # connection, so a reconnecting player gets the full set they had. markers.restore(conn, state.scene, state.visions) let gm = gmPlayer(conn) if gm.isSome: state.gmPlayerId = gm.get.id lg.log(lvInfo, "scene_loaded", [("scene", $state.scene.id), ("walls", $state.scene.walls.len), ("tokens", $state.tokens.len), ("characters", $state.characters.len), ("next_wall_id", $state.scene.nextWallId)]) lg.log(lvInfo, "explored_loaded", [("players", $state.visions.len), ("chunks", $explored.chunkCount(conn, state.scene.id)), ("markers", $markers.markerCount(conn, state.scene.id))]) lg.log(lvInfo, "names_loaded", [("reveals", $state.reveals.pairs.len), ("encountered_players", $state.encountered.len)]) appHandle = cast[pointer](state) createThread(heartbeatThread, heartbeat) lg.log(lvInfo, "heartbeat", [("interval_ms", $PingIntervalMs), ("proto", $ProtoVersion)]) # maxMessageLen is DESIGN 6.4's 64 KB, stated explicitly rather than inherited from mummy. # `WorkerThreads`: mummy's default is 10 x cores, far too many for one table (ANALYSIS 4.1). let server = newServer(buildRouter().toHandler(), websocketEvent, mummyLog, workerThreads = WorkerThreads, maxMessageLen = MaxInboundBytes) lg.log(lvInfo, "listen", [("addr", BindAddress), ("port", $cfg.port)]) server.serve(Port(cfg.port), BindAddress) 0 proc main() = let args = commandLineParams() if args.len > 0 and args[0] == "gm-key": quit runGmKey(if args.len > 1: args[1 .. ^1] else: @[]) var cfg: Config try: cfg = parseConfig(args) except ConfigError as e: stderr.writeLine "fff-vtt: " & e.msg quit 2 if cfg.help: stdout.write cliUsage() quit 0 quit runServer(cfg) when isMainModule: main()