garage44.eu/jeroen/cartopolis

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

.. /docs/adr/033-build-targets-and-wasm-packaging.md

raw

ADR-033: Build Targets — Standalone (Native) and Web (wasm32)


Metadata:


Context

Problem: We want cartopolis reachable in a browser without foreclosing native-only capability (ADR-030) and without the browser's limits dictating the architecture. ADR-030 set the pattern (substitutable providers + additive plugins) and ADR-031 the access model (anonymous Viewer → login → ACL). Neither says what we actually build and ship. This ADR defines the target matrix, the dependency/feature topology that produces both from one crate, the server-side work the web target implies, and the delivery order.

Current state (measured, crates/cartopolis):

Native-only primitiveSitesStatus
rusqlite (client SQLite)0Gone — dropped in 7b44042; no db/, no database.rs
ureq:: blocking HTTP14 across 10 filesone uniform pattern (see below)
std::thread::spawn15mostly the HTTP workers
std::fs::30disk caches, user.json, login TOML
tokio::net / TcpStream3the sim transport

No wasm scaffolding exists yet. Two facts shape the design:

  1. The HTTP surface is uniform. All 10 fetch files follow one shape — std::thread::spawn → blocking ureq::get → mpsc back to a Bevy system. One HttpFetch provider replaces all of them without touching their parsing/meshing logic. The uniformity is the leverage.
  2. Client SQLite is already gone, so the only remaining "embedded authority" is the solo in-process cartopolis_simulator — already a Cargo feature, already off-able.

New constraints since ADR-030:

Requirements:

Decision

Ship two build targets from one crate, with providers selected by cfg(target_arch) and additive capabilities selected by Cargo feature.

Target matrix

ConcernStandalone (native desktop)Web (wasm32-unknown-unknown)
Simsolo embedded sim, --connect, or noneremote only, via WebSocket
Session startany (CLI may pre-seed)always anonymous Viewer (ADR-031)
TransportTcpStream + LengthDelimitedCodecWebSocket (binary message = one app frame)
HTTPureq on AsyncComputeTaskPoolfetch
Storagestd::fs cache dir + user.jsonIndexedDB / OPFS
Clipboardarboardweb-sys
Configclap CLI + login TOMLURL query params (?lat=&lng=&alt=)
GRIB decodeserver endpoint (see below)server endpoint
--shot harnessyescompiled out
Native-only extrasin-world browser etc. (ADR-030)declared fallbacks (ADR-030)

Dependency topology

Providers by target (cfg(target_arch = "wasm32") — no feature flag; the target implies the impl). Four seams, matching ADR-030: Transport, HttpFetch, KvStore, Clipboard.

Additive capabilities become optional deps, off for wasm:

Known config points (small but must be handled, not discovered): getrandom needs its js backend on wasm (reached via uuid v4 and Bevy); jiff needs a bundled tzdb (no system tzdb in a browser); tzf-rs is pure Rust but embeds timezone polygons — verify it builds for wasm and weigh the binary-size cost, or put local-time behind a provider. Bevy needs a wasm feature profile: drop multi_threaded, wayland, x11; target WebGPU with WebGL2 fallback. Logging needs a wasm subscriber (console) instead of the env-filter writer.

Server-side work the web target implies

  1. WebSocket acceptor in cartopolis_simulator, alongside the existing TCP listener. Same NetMessage frames (ADR-008/009 unchanged); WebSocket is already message-framed, so one encode_app_frame per binary message and length-delimiting is skipped on that path.
  2. Serve everything from one origin — no CORS. An earlier draft called for a "CORS edge"; that was wrong. Path-mount the app, our services and the relay under a single hostname (/tiles/*, /nominatim/*, /overpass/*, /3dbag/*, /v1/*, wss://…/ws) in the existing Caddy and same-origin requests need no CORS headers at all. Our services are on subdomains today, which are separate origins — the migration is Caddy routes, not headers. See ADR-034 for the layout.
  3. A Public-tier data relay — see ADR-034. A registry of upstream adapters (cartopolis_relay, lib + thin bin, embedded in cartopolis_simulator by default) on a three-level ladder: L0 direct (third-party that sends CORS and carries no identification obligation — currently empty), L1 path-mount (our services; Caddy config, no Rust), L2 relay adapter (transform, cache, identification, or otherwise unreachable). Every adapter inherits a TTL cache with single-flight, stale-if-error, one project User-Agent, politeness spacing, timeouts and TLS termination. The audit behind it found three constraints that outweigh CORS: secrets can't ship to a browser (the Anthropic key), mixed content (OVapi is plain http://), and User-Agent is a forbidden header in fetch().
  4. Self-host vector map tiles — see ADR-035. OSM discourages proxying their CDN and expects heavy users to self-host, and the browser cannot send our identifying User-Agent. Tiles are our largest byte volume, so this is on Phase 1's critical path: OSM vector tiles (MVT) built with planetiler, stored as PMTiles, served at /tiles/*; global low zoom plus regional extracts to ~z14 with client overzoom. Decode is pure Rust — no C dependency on the wasm path. The client-side vector rendering path is being built in a separate workstream.
  5. Move GRIB decode server-side (ADR-032) — the first L2 adapter (gfs-tcdc), returning the decoded 360×181 TCDC grid (65 KB of R8, ~8 KB gzipped) instead of the ~70 KB GRIB2 record. NOMADS sends no permissive headers, so a browser cannot fetch it directly whatever the decode costs (which is now pure Rust — see Context). Secondary wins: the client stops re-deriving the GFS cycle clock, and one warm cache serves every viewer. Native uses the same endpoint, at which point gribberish leaves the client for the relay.
  6. The AI assistant moves into cartopolis_simulator, admin-only. ai_assistant.rs sends an ANTHROPIC_API_KEY from the client — impossible in a browser, and undesirable on native. It becomes a NetMessage handled by the sim, gated on ADR-031's Authorized(ai) capability (admin users only, since it spends real money). It is not a relay adapter: the relay stays anonymous and stateless.

Delivery phases (mapped to ADR-031 tiers)

CI: add cargo check --target wasm32-unknown-unknown -p cartopolis --no-default-features to the existing Forgejo Actions fast-lane, so the web target cannot rot silently. Standalone release binaries keep the existing tag-driven Linux release workflow.

Rationale

Primary Reasoning:

  1. Phase 1 is decoupled from the hard work. Because ADR-031 made the Viewer tier sim-independent, the web build delivers real value with zero protocol/server changes. The access model is the wasm de-risking strategy.
  2. The uniform fetch pattern makes the big number small. 14 call sites across 10 files look daunting until you notice they are one shape; a single HttpFetch seam converts them all and improves native too (task pool instead of 15 ad-hoc OS threads).
  3. Client SQLite is already gone, so the remaining "native authority" is one Cargo feature (solo) — the topology is far closer to buildable than it was.
  4. Server-side GRIB decode is better on both targets (P-03): it solves CORS (the hard blocker), collapses N client fetches of NOMADS into one cached one, and lets the client drop a decoder it only needs for one 65 KB grid. The C dependency it was also going to remove is already gone (default-features = false), so this is now a simplification with a deadline set by web, not a prerequisite.
  5. cfg(target_arch) for providers, features for capabilities keeps the two axes from tangling: platform impl is implied by the target, while capability presence stays a deliberate build choice (and matches ADR-030's split).

Alternatives Considered:

AlternativeProsConsRejected Because
Separate cartopolis-web crateClean isolationDuplicate feature logic; driftViolates P-05; the whole point is one codebase
Web build waits for the WS transportOne big launchDelays all web value behind server workPhase 1 needs no server change; shipping earlier de-risks
Keep GRIB decode client-side, gribberish default-features = falseNo server work; drops the C dependency today; decode verified unchanged (template 5.3)NOMADS CORS still blocks the browser; every client re-fetchesAdopted for native now, but it does not unblock web — the endpoint still lands for CORS
Hand-roll a template 5.3 decoder to drop gribberish tooZero GRIB dependency~150 lines of bit-level packing + spatial differencing to own; breaks silently if NCEP repacksgribberish minus its C features is already pure Rust and wasm-clean — no benefit left to buy
Switch to the NOMADS OPeNDAP endpoint (plain float arrays, no GRIB)No GRIB decode at allSame CORS wall; 260 KB float32 vs 70 KB packed; NOMADS rate-limits DODS harderTrades a solved problem for a bigger payload
Cargo feature (web) instead of cfg(target_arch) for providersExplicitRedundant with the target; easy to build an incoherent comboTarget already determines the impl
Proxy everything through our edgeUniformBandwidth and operational cost for tiles we don't need to proxyProxy only what CORS forces (P-03)

Consequences

Positive:

Negative:

Related