garage44.eu/jeroen/cartopolis

logclone: git clone https://garage44.eu/jeroen/cartopolis.git

.. /docs/notes/hosted-simulator.md

raw


topic: deployment triggers: [deploy-sim.yml, vapid.key, "/api/push/key", "@webapi", backups, deploy-web.yml, deploy-wasm.yml, "/console/", atlas, http.rs, ws_transport.rs, "web.cartopolis.org", "hosted sim", "public server", caddy, systemd, admin, accounts, "--http-listen", "--create-admin", "/go", well-known, network.rs, http_surface.rs, systems::ws_transport, resolve_target, install_crypto_provider, FrameTransport, rustls] updated: 2026-10-17

The hosted simulator, and the two surfaces in front of it

There is a public simulator on code.garage44.eu (the same box as Forgejo, nominatim, overpass, the tile server and the CI runner). It exposes three things and each has a different audience:

AddressWhoWhat
wss://cartopolis.org/wsevery client — desktop, Android, browserthe wire (ADR-008/009), one binary WS message per frame, TLS terminated by Caddy
https://cartopolis.org/everyonethe atlas web UI (crates/atlas/web, static files published by midas deploy web; atlas-web-ui.md) since 2026-09-24 — Community at /, World at /world and, for operators, Admin at /admin (People, Content, Data), plus the players' /register, /verify and /buildings. Caddy's fallback, with index.html for any path that is not a file
https://cartopolis.org/terrain/, /height, /api/pipeline/the client, the web UIcartopolis_atlas (atlas.md), on 172.17.0.1:4749
https://cartopolis.org/viewer/players in a browserthe wasm client, published by deploy-wasm.yml into site/viewer/
https://cartopolis.org/console/nobodyredirects to /admin. The operator's pages lived here, beside a front page atlas served itself, until 2026-09-24; before that they were web.cartopolis.org and a separate repository, a hostname retired with no redirect

Everything Caddy does not route elsewhere is the web UI (from /data/cartopolis/admin, the directory name kept from when it was admin-only), which is why the site root is not the viewer's file directory any more. Two things stay files at the root, served from site/: /apk/ (deploy-android.yml), and /.well-known/assetlinks.json, which an Android phone reads from exactly that URL to decide the app may handle a place link (place-links.md) and which deploy-wasm.yml copies up out of the trunk dist. /go is a redirect to /viewer/?place=… rather than the page itself: the client fetches its assets relative to the page, so a page served at /go would ask atlas for /assets/….

There is no plaintext port. The simulator's TCP listener is bound to 127.0.0.1 and its HTTP listener to the docker0 gateway, so nothing it serves is reachable from off the machine except through Caddy. The address to give a person is cartopolis.org — no scheme, no port; network::resolve_target turns a bare hostname into wss://cartopolis.org/ws.

One connection loop, two carriers

net::handle_connection is generic over net::FrameTransport — anything that is a Stream of frames and a Sink of them. TCP supplies that through LengthDelimitedCodec; the browser supplies it through http::WsFrames over axum's WebSocket (one binary message per frame). On the client the same split is network::Wire (native: TCP or WebSocket, as resolve_target decides, below) and systems::ws_transport (wasm). The frame body is identical, so a WS carrier is not a protocol revision and PROTOCOL_HISTORY did not gain a row for it (wire-protocol-versions.md).

Writes are batched, not flushed per frame (2026-10-17). Every send used to flush, so a tick's snapshot, the chat and the voice queued beside it were a write (and through Caddy a WebSocket message) each, and the sign-in's run of permissions, block list, contacts, fifty Global lines, capacity and the full snapshot was fifty-odd. The loop now feeds what woke it, takes whatever else is already waiting on the three queues (feed_ready, at most SEND_BATCH), and flushes once; the sign-in feeds its run and the snapshot's send flushes it. Telling contacts that someone came online is spawned rather than awaited by the newcomer's sign-in. Not timed yet. Already right before this, and not worth revisiting: Nagle is off at both ends and in Caddy, each snapshot is encoded once for everyone, and every outgoing queue is bounded.

The alternative was a second copy of a 700-line select loop carrying its own rate limiters, chat replay and avatar teardown. Two loops that must stay identical, and nothing that says when they stop being — the transport refactor was cheaper than the first divergence would have been.

crates/simulator/tests/integration/http_surface.rs (a_websocket_client_completes_the_same_handshake) pins the property that matters: a token minted over WebSocket authenticates over TCP. They are one server sharing one session store, not two that happen to share a database.

Why the admin API is HTTP and not the wire

Account management is an operator action, not gameplay. Putting it on NetMessage would run an authorisation decision through the same path as a movement intent, and would make every client's protocol version move whenever the admin surface changed. It is a separate surface with a separate audience; what it shares with the game is the account table and the session map, which is the point — an admin signs in with an ordinary account, and disabling someone signs them out everywhere.

Disabling revokes every token and ends open connections (2026-11-06). It used to flip disabled = 1 and nothing else, which gated only a password login: a saved session token never meets that check and slides its 30-day expiry on every use, so a disabled account's app reconnected indefinitely. update_account now calls Sessions::revoke_principal (a linear scan, as account deletion uses), and each open connection checks every token_check_ms that its credential — access token, or the session a sign-in was issued — still exists (Sessions::session_live, which also keeps an open connection's session from ageing out or being evicted at MAX_SESSIONS). A restart is not a way to sign anyone out: since 2026-08-21 the session map is written through to the sessions table (token hashes, 30-day sliding TTL), precisely so a redeploy stops signing everybody out — "stay signed in" was broken by every publish before that.

The last-admin guard

Demoting, disabling or deleting the last enabled admin is refused with a 409. It is checked before the write rather than repaired after, because there is no repair from a running server with no admin except shell access to the box — at which point the way back in is simulator --create-admin <user> with CARTO_ADMIN_PASSWORD set, which is idempotent and doubles as the password reset.

The password comes from the environment and not a flag on purpose: an argument is in the process table and in the operator's shell history, and this is the one credential that grants itself everything else.

Deployment shape, and why it is not a container

The simulator is a systemd unit running a native binary, not a service in /data/stack/docker-compose.yml like everything else on that host. The reason is that the Forgejo runner and the host are the same machine: CI publishes with a file copy, so there is no registry to push an image to and no image to build. Forgejo itself is deployed the same way for the same reason, and Caddy reaches both across the docker0 gateway (172.17.0.1).

Neither a deploy nor a CI job calls systemctl — giving either the host's init system would be a much larger grant than "may write these files". So the publish step (midas deploy's, or deploy-sim.yml's) writes the binary and touches restart.stamp; cartopolis-sim-reload.path on the host watches that file and restarts the service. The privilege stays on the host.

The binary is written to simulator.new and mvd into place. An interrupted copy would otherwise leave a truncated file that Restart=always loops on forever.

Deploying the simulator (updated 2026-10-16)

midas deploy sim, from an agent container. It builds the tip of main on any free node — only a commit that landed, only with the landing gate's receipt — and publishes it here as root, after the same two checks the workflow ran: startup and migrations against an empty database, then this commit's migrations against a copy of the live one, as cartosim. A failing check leaves the old binary serving. A Mac node builds it too: deploy/build/server.sh cross-links the x86_64 Linux binary with cargo-zigbuild on either kind (measured 2026-11-05 on mac-2: atlas 2 m 49 s and the simulator 4 m 25 s from cold, both passing the recipe's checks on the VPS). The recipe is the deploy.sim section of the hub's /etc/midas/hub.conf (jeroen/midas, docs/hub.md); midas deploy atlas is the same for atlas. It is never automatic: publishing restarts a live service and drops every connection for a few seconds. So the server drifts behind main until somebody deploys it, and a client a protocol revision ahead of it fails to sign in with "Connection reset without closing handshake" (the server's journal says unsupported protocol version).

No deploy runs on a push to main any more — the web UI's was the last to, until 2026-10-16. deploy-sim.yml still works and is the fallback when the workshop is down — it builds on the Forgejo runner instead, and its checks are the recipe's:

source ~/.config/viberfox/forgejo.env      # FORGEJO_REPO_TOKEN may dispatch
curl -X POST -H "Authorization: token $FORGEJO_REPO_TOKEN" -H 'Content-Type: application/json' \
  -d '{"ref":"main"}' "$FORGEJO_API/repos/$FORGEJO_REPO/actions/workflows/deploy-sim.yml/dispatches"

The run is "build & publish the simulator" in the actions list. Before deploying either way, check what the deploy brings that a binary copy does not:

What the server keeps beside its binary, in /data/cartopolis/sim/data/ (the only path the unit may write), and which of it to back up:

FileWhatIf it is lost
world.db (+ -wal, -shm)accounts, sessions, prims, chats' sealed history, push addresseseverything; back it up
vapid.keythe key browsers subscribe to call pushes with (simulator::vapid, since 2026-10-11), made on the first start with calls on, mode 600every subscribed browser stops ringing for calls, silently, until its chat page is opened again and re-subscribes; back it up with the database
stats.db (+ -wal, -shm)usage counts for Admin › Stats (usage-stats.md, since 2026-10-18)the history of the charts; the server makes a new one and counts on. Back it up if the history matters
assets/uploaded models, one .glb per content hashthe models; back it up
texturesa link to /srv/library/game-texturesnothing; it is the library's

Checking a deploy went live:

curl -s https://cartopolis.org/api/push/key        # {"key": …} from the simulator
ssh host 'systemctl is-active cartopolis-sim; sudo journalctl -u cartopolis-sim -n 60 --no-pager'

/api/health is not routed publicly (it answers the web UI's HTML), so do not probe with it; from the host, curl http://172.17.0.1:4748/api/health reaches the simulator directly. Any listed route answering HTML rather than JSON means Caddy is sending it to the web UI — the matcher above, not the simulator.

Measured / observed, 2026-08-13

Rejected: the admin GUI as a Bun service

Codebrew's own apps are Bun services — Bun.serve, a WebSocket API router, a session middleware. Copying that here would have meant a second long-running process on the box, a second thing to supervise and restart, and a second place holding credentials, in order to serve 35 KB of static files and forward JSON to a Rust process that was already answering HTTP. What was worth borrowing from codebrew is its front end: the reactive store with its persistent/volatile split, and the App.init + components/{pages,elements} layout. Those are in crates/atlas/web and the GUI has no backend of its own — it is static files Caddy serves, and its API calls go to this simulator (/api/admin/*) and to atlas (/api/pipeline/*), which was already answering HTTP too.

The GUI lived in a separate repository until 2026-09, because it shared nothing with this one but an HTTP contract. It moved in with atlas, but it is still TypeScript beside Rust, so the one seam worth naming is unchanged: crates/atlas/web/src/types.ts describes what auth::AccountRow serialises. A person kept the two in step until web_mirror (the simulator's integration suite) began comparing them field by field (atlas-web-ui.md).

Rejected: CORS on the simulator

The GUI is static files (the site root of cartopolis.org now; it was web.cartopolis.org) and the API is on the simulator, so the obvious move is an Access-Control-Allow-Origin layer. Caddy proxies the API on the GUI's own hostname to the simulator instead, which makes every request same-origin — there is then no preflight, no origin allowlist to keep in step with the deployment, and no CORS misconfiguration that could expose the admin API to a page the operator was reading. Same trick as /up/nomads/ for NOAA and for the same reason (ADR-034 calls one origin the fix).

Still open

The CI registry cache could not be shared, and said so in three voices

Unrelated to the simulator, found while landing it, and recorded here because the next person to see it will also be looking at a red lane and their own diff.

ci.yml's two jobs both bind-mounted /data/ci-cache/cargo-registry onto /root/.cargo/registry, under a comment claiming cargo's file lock made that safe between concurrent jobs. It does not: the lock is $CARGO_HOME/.package-cache, a file one level above the mount, so each container took a private lock over shared data. Fixed 2026-08-13 by giving targets its own copy.

The reason it costs a day rather than a minute is that it never looks like a cache problem. Three failures on main that day, all this one cause:

.cargo-ok is written last, so an interrupted extract leaves a directory cargo can neither use nor replace, and a concurrent reader sees a crate whose source really is incomplete. It is intermittent, and it bites hardest immediately after a lockfile change — which is exactly when a dependency error reads as "something I just did".

Check the cache before the code. ls /data/ci-cache/cargo-registry/src/*/ | wc -l and look for a crate directory without a .cargo-ok.

Every build uses TLS, and opting out takes a scheme

The first cut of this had desktop and Android clients on a public plaintext TCP port, with the wire's own auth handshake — a password, and then a session token — crossing the network unencrypted. That is now closed: network::resolve_target maps a bare hostname to wss://host/ws, so the easy thing to type is the encrypted one, and the client reuses the same carrier and the same Caddy certificate the browser build already used.

Three rules, and the shape of them matters more than the list:

Loopback is exempt on purpose. A dev sim there is a listener on this machine; TLS to it would mean a self-signed certificate and a verifier turned off to accept it, which is the appearance of security over traffic that anything able to read could equally read out of this process's own memory. Encryption there would make the code harder to audit and no safer.

The escape hatches exist because two real cases need them — a private CA (webpki-roots is a compiled-in Mozilla trust store, so a corporate MITM root is not in it) and a plaintext dev sim on a LAN. Both require typing a scheme. Nobody reaches either by entering a hostname, which is the property a_remote_address_is_always_encrypted exists to pin.

rustls, not native-tls. native-tls is OpenSSL on Linux and Android, and the CI target lane checks aarch64-linux-android with nothing but the NDK's clang — a vendored OpenSSL build script would break the gate that exists to catch exactly this kind of dependency. webpki-roots over rustls-native-certs for the matching reason: Android has no /etc/ssl/certs, and its trust store is a JNI call this tree has no seam for.

rustls 0.23 panics at the first connection, not at build time, unless a CryptoProvider is settled. It ships no default and derives one from its features, panicking when that is ambiguous (none, or both ring and aws-lc-rs). So the failure is a client that builds, draws a map and dies the moment somebody signs in — and feature unification is workspace-wide, so a dependency added later can make a clean answer ambiguous. network::install_crypto_provider installs ring explicitly, once, before the first handshake.