garage44.eu/jeroen/cartopolis

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

.. /.forgejo/workflows/deploy-wasm.yml

raw

name: Deploy wasm

# Build the wasm client and publish it to https://cartopolis.org/viewer/.
#
# **The fallback.** `midas deploy wasm` is the usual path since 2026-10-16: it builds
# a landed, gate-verified commit on a workshop node (deploy/build/wasm.sh, these steps)
# and publishes it on the VPS.
# This workflow is for when the workshop is down.
#
# Separate from ci.yml on purpose. This job rebuilds std (`-Z build-std`, needed
# for atomics) and links ~70 MB with LTO, so it is tens of minutes cold against a
# runner with capacity 3 — attached to the test lanes it would block them on
# every push. Here it runs only when `main` moves, plus on demand.
on:
  # Manual only. This used to run on every push to `main`, which on a
  # capacity-3 runner meant the web client competed with CI for a slot on every
  # merge — and a publish is not something you want to happen because a
  # README typo landed. `workflow_dispatch` from the Actions tab, or:
  #   curl -X POST -H "Authorization: token $FORGEJO_TOKEN" \
  #     -d '{"ref":"main"}' \
  #     "$FORGEJO_API/repos/$FORGEJO_REPO/actions/workflows/deploy-wasm.yml/dispatches"
  workflow_dispatch:

env:
  CARGO_TERM_COLOR: always
  CARGO_NET_RETRY: "3"
  # sccache, the same second cache layer ci.yml has had since it was written, and
  # for the reason that file states at length: `rust-cache` has exactly one key, so
  # a key change or a failed run leaves nothing behind, while sccache is keyed on
  # the compiler invocation and its inputs and therefore cannot miss for a reason
  # unrelated to the code. This lane is the one with the worst cache history in the
  # repo -- see CACHE_ON_FAILURE above -- so it is the one that needed a floor
  # under it most, and it was the only one without.
  #
  # This shares a cache *directory* with ci.yml but not its entries: a different
  # target triple and a different profile mean a different compiler invocation and
  # so a different key. What it warms from is its own history, which is the point.
  #
  # `[profile.release] incremental = false` (inherited by android-release) is what
  # makes this work at all -- sccache silently declines to cache an incremental
  # compilation. That setting was overridden by a `[build] incremental = true` in
  # .cargo/config.toml until it was removed; without that fix this block would
  # have been decoration.
  RUSTC_WRAPPER: sccache
  SCCACHE_DIR: /sccache
  SCCACHE_CACHE_SIZE: 20G

jobs:
  deploy-wasm:
    name: build wasm & publish
    runs-on: ubuntu-latest
    container:
      image: cartopolis-ci:latest
      # The runner and the web host are the same machine, so publishing is a
      # copy rather than a transfer. `/data/cartopolis/site` is the only path the
      # runner permits mounting (`valid_volumes` in its config); Caddy has the
      # same directory mounted read-only as /srv/cartopolis.
      # `/data/ci-cache` is in `valid_volumes` too — ci.yml has mounted both of
      # these since it was written; the comment above predates them.
      #
      # **Its own registry copy, not the `test` job's**, for the reason ci.yml's
      # `targets` job states in full: a bind mount of `registry/` shares exactly
      # the data that needs protecting and excludes the lock that protects it —
      # cargo's lock is `$CARGO_HOME/.package-cache`, one level *above* the
      # mount, so each container takes a private one and two concurrent jobs
      # write one registry with nothing serialising them. That comment called
      # this lane's shared mount "not fixed, and worth knowing"; on 2026-08-21
      # it cost a deploy. The three `deploy-*` workflows were dispatched within
      # twenty seconds of each other against a runner of capacity 3, all three
      # mounted this directory, and this job died on
      #
      #   failed to unpack package `toml_datetime v0.7.3`
      #     failed to open …/toml_datetime-0.7.3/.cargo-ok: File exists (17)
      #
      # `.cargo-ok` is written last, so an interrupted extract leaves a
      # directory cargo can neither use nor replace. Note the second writer is
      # not only cargo: `Swatinem/rust-cache` restores a ~570 MB archive over
      # `/root/.cargo/registry` and prunes `registry/src` in its post step, and
      # neither of those takes cargo's lock even when it is shared. Isolation is
      # the only thing that covers both. ~310 MB of disk per lane, and the
      # copies are independent, so they cannot race whatever the runner starts.
      options: >-
        --volume /data/cartopolis/site:/publish
        --volume /data/ci-cache/sccache:/sccache
        --volume /data/ci-cache/cargo-registry-web:/root/.cargo/registry
    steps:
      - uses: actions/checkout@v4
        with:
          # The avatar body pack and its textures are LFS pointers otherwise,
          # and the client would read a 130-byte text file where a body should be.
          lfs: true

      - uses: https://github.com/Swatinem/rust-cache@v2
        with:
          # Distinct from the native lanes: different target triple, different
          # profile, and a std rebuild. Sharing one key would thrash both.
          key: wasm-web-release

      # A wasm-bindgen CLI that disagrees with the crate emits JS glue and a
      # module that do not match, and says nothing — it fails later, in the
      # browser, as an opaque import error. Cheap to assert, miserable to debug.
      - name: wasm-bindgen CLI matches the lockfile
        run: |
          # No `| head`: it closes the pipe on a reader that may still be
          # writing, and under `pipefail` that is a 141 that fails the deploy for
          # no reason. `awk` with an exit does the same job from inside one process.
          want=$(awk '/^name = "wasm-bindgen"$/ { found = 1; next }
                      found && /^version/ { gsub(/[",]/, "", $3); print $3; exit }' Cargo.lock)
          have=$(wasm-bindgen --version | awk '{print $2}')
          echo "lockfile: $want / image: $have"
          [ "$want" = "$have" ] || {
            echo "::error::wasm-bindgen $have in cartopolis-ci:latest, but Cargo.lock wants $want."
            echo "Rebuild the image with --build-arg WASM_BINDGEN_VERSION=$want (~/build/cartopolis-ci-image)."
            exit 1
          }

      # The same three-part configuration serve-threads.sh documents: atomics
      # alone gives every worker a private heap, so the shared-memory link args
      # are what actually make threading work; the TLS symbols must be exported
      # by name for wasm-bindgen's thread transform; and std needs rebuilding
      # because the shipped one has no atomics.
      #
      # RUSTFLAGS set here *replaces* `.cargo/config.toml`'s per-target entry
      # rather than merging with it, so `+simd128` is repeated — without it
      # tiny-skia silently falls back to scalar. `simd_baseline.rs` fails the
      # build if this is ever dropped.
      #
      # `--cfg=web_sys_unstable_apis` is repeated for the same reason and is the
      # harder one to spot, because nothing about the error names it: web-sys
      # gates the Geolocation family on that cfg, and without it
      # `platform::location` cannot see `GeolocationPosition` at all, which
      # cascades through `DriverState` into ~99 errors across driver mode. This
      # job failed on every push for exactly that reason until 2026-08-06.
      - name: Build (web-release, threads + SIMD)
        env:
          RUSTUP_TOOLCHAIN: nightly
          CARGO_UNSTABLE_BUILD_STD: std,panic_abort
          RUSTFLAGS: >-
            --cfg=web_sys_unstable_apis
            -C target-feature=+atomics,+bulk-memory,+mutable-globals,+simd128
            -C link-arg=--shared-memory
            -C link-arg=--import-memory
            -C link-arg=--max-memory=4294967296
            -C link-arg=--export=__heap_base
            -C link-arg=--export=__tls_base
            -C link-arg=--export=__wasm_init_tls
            -C link-arg=--export=__tls_size
            -C link-arg=--export=__tls_align
        # Deliberately not `trunk build --release`: that turns on wasm-opt, which
        # is fetched from GitHub at build time and, more importantly, rejects or
        # silently mangles a shared-memory module unless handed `--enable-threads
        # --enable-bulk-memory` to match. The size win is real but it is not free
        # to get right, and `web-release` already carries opt-level 3 + thin LTO.
        # Revisit as a deliberate change with the feature flags spelled out.
        # `--public-url /viewer/`: the client is served at cartopolis.org/viewer/,
        # and the site root belongs to atlas (docs/notes/atlas.md). Trunk writes the
        # module and loader URLs absolute from this; everything the app fetches at
        # run time (`assets/…`) is relative to the page, so it follows the page.
        run: |
          cd crates/cartopolis
          trunk build --cargo-profile web-release --dist dist --public-url /viewer/

      # Verify what was produced rather than assuming the flags took. Both of
      # these have silently regressed before: shared memory is what makes the
      # worker pool possible at all, and a stripped-symbol module is 71 MB
      # against 114 MB unstripped.
      # ci.yml's own rule for this cache: print the stats unconditionally, so the
      # next person can tell whether it worked instead of inferring it from a
      # duration. `if: always()` because a failed build is exactly when you want
      # to know whether the cache was cold.
      - name: sccache stats
        if: always()
        # **A diagnostic may not fail a deploy.** On 2026-09-05 this exact
        # command ended a web publish: the wasm build had finished and trunk had
        # written the distribution, and `--show-stats` then answered "Failed to
        # read response header … Mismatch of client/server versions?" and exited
        # 2 — so the threading check, the pre-compression and the publish never
        # ran, and a good artifact was thrown away over the answer to "how did
        # the cache do?".
        #
        # Why the server stopped answering is **not established**. It is not a
        # stale server shared between lanes: each container has its own network
        # namespace, so each has its own. What is established is that every
        # compile had already succeeded, so whatever happened to the server
        # happened after the work. Print the stats, say so when they cannot be
        # printed, and let the checks that actually inspect the artifact decide.
        run: sccache --show-stats || echo "sccache could not report its stats — the build above is unaffected"

      - name: Verify the module is threaded
        run: |
          wasm=$(ls crates/cartopolis/dist/*_bg.wasm)
          # The glue is the script index.html loads, never `ls *.js | head -1`
          # (a `data-initializer` loader once sorted first at random and never
          # constructs a `WebAssembly.Memory`), and not derived from the wasm's
          # name either: trunk 0.22 hashes the two separately, which failed
          # every wasm deploy from 2026-10-24 on a good build.
          js=$(grep -o 'cartopolis-[0-9a-f]*\.js' crates/cartopolis/dist/index.html | sort -u)
          [ "$(printf '%s\n' "$js" | grep -c .)" = 1 ] || {
            echo "::error::index.html does not name exactly one glue script: '$js'"
            exit 1
          }
          js="crates/cartopolis/dist/$js"
          echo "module: $wasm ($(( $(stat -c%s "$wasm") / 1000000 )) MB)"
          # These two exports exist only if wasm-bindgen's thread transform ran,
          # and it only runs when the link produced shared memory and the TLS
          # symbols. Grepping the export names is a far sturdier check than
          # re-parsing the binary, and catches the failure that matters: a build
          # that succeeds and quietly has no worker pool.
          for sym in wasm_thread_entry_point __wbindgen_thread_destroy; do
            grep -qa "$sym" "$wasm" || {
              echo "::error::$sym missing — the module was linked without shared memory."
              echo "RUSTFLAGS likely lost the --shared-memory/--export=__tls_* group."
              exit 1
            }
          done
          # The JS half has to agree, or the workers never get spawned browser-side.
          grep -qa "shared:true\|shared: true" "$js" || {
            echo "::error::JS glue does not construct a shared WebAssembly.Memory."
            exit 1
          }
          echo "threading: shared memory + thread transform confirmed"

      # Pre-compress so Caddy's `precompressed br zstd gzip` serves a file read
      # instead of compressing the module per cold request. Keep the original: a
      # client that sends no Accept-Encoding still needs it.
      #
      # Measured on the 87.7 MB module of 2026-10-05: gzip -9 21.2 MB, zstd -19
      # 14.2 MB (26 s), brotli q11 12.9 MB (~6 min, single-threaded). Brotli is
      # what every browser that has WebGPU accepts, so it is the one that counts
      # — 39 % less to download than the gzip this used to ship, on a phone link
      # where the download *is* the startup. `--large_window` is deliberately not
      # used: browsers refuse brotli windows over 16 MB. wasm-opt was measured
      # too and is not here on purpose: -O2 and -Oz shrank the raw module by
      # 11–22 % and the compressed one by nothing (gzip grew).
      - name: Pre-compress the large assets
        run: |
          apt-get update -qq && apt-get install -y -qq brotli >/dev/null
          cd crates/cartopolis/dist
          for f in *.wasm *.js; do
            [ -f "$f" ] || continue
            gzip -9 -k -f "$f"
            zstd -19 -T0 -q -f "$f" -o "$f.zst"
            brotli -q 11 -w 24 -k -f "$f"
          done
          ls -la *.wasm* *.js* | awk '{print $5, $9}'

      # Into `viewer/` under the site root, which is where Caddy serves
      # cartopolis.org/viewer/ from. `--delete` so files from a previous deploy
      # (old content-hashed modules) do not accumulate 70 MB at a time, and it is
      # scoped to `viewer/`, so it cannot reach `/apk/` (deploy-android.yml's) or
      # anything else beside it. Written last, after every check above has passed,
      # so a failed build leaves the live site untouched.
      #
      # `.well-known/assetlinks.json` has to stay at the *site* root: Android reads
      # it from https://cartopolis.org/.well-known/ to verify App Links, whatever
      # path the web build lives under, so it is copied up a level.
      - name: Publish
        run: |
          apt-get update -qq && apt-get install -y -qq rsync >/dev/null
          mkdir -p /publish/viewer /publish/.well-known
          rsync -a --delete crates/cartopolis/dist/ /publish/viewer/
          cp crates/cartopolis/dist/.well-known/assetlinks.json /publish/.well-known/assetlinks.json
          echo "published $(du -sh /publish/viewer | cut -f1) to /data/cartopolis/site/viewer"